main function

void main()

Implementation

void main() {
  const lr = 0.05;
  final model = MultiLayerPerceptron(lr); // 4 inputs → 2 outputs

  final inputs = [
    ValueVector([Value(0.0), Value(0.0)]),
    ValueVector([Value(0.0), Value(1.0)]),
    ValueVector([Value(1.0), Value(0.0)]),
    ValueVector([Value(1.0), Value(1.0)]),
  ];

  final targets = [
    ValueVector([Value(1.0), Value(0.0)]),
    ValueVector([Value(0.0), Value(1.0)]),
    ValueVector([Value(1.0), Value(0.0)]),
    ValueVector([Value(0.0), Value(1.0)]),
  ];

  const epochs = 10000;

  for (int epoch = 0; epoch < epochs; epoch++) {
    final losses = <Value>[];

    // Reset gradients
    model.zeroGrad();

    // Compute loss for all samples
    for (int i = 0; i < inputs.length; i++) {
      final yPred = model.forward(inputs[i]);
      final yTrue = targets[i];
      final diff = yPred - yTrue;
      final squared = diff.squared();
      final sampleLoss = squared.mean();
      losses.add(sampleLoss);
    }

    final totalLoss = losses.reduce((a, b) => a + b);
    final avgLoss = totalLoss * (1.0 / inputs.length);
    avgLoss.backward();

    // Gradient descent
    model.updateWeights();
    if (epoch % 700 == 0) {
      print("Epoch $epoch | Loss = ${totalLoss.data.toStringAsFixed(4)}");
    }
  }

  for (var input in inputs) {
    // Reset gradients
    model.zeroGrad();

    print("");
    print("Input: ${input}");
    print("Output: ${model.forward(input)}");
    print("");
  }
}