Java: training a perceptron to learn AND

A perceptron computes a weighted sum of its inputs plus a bias and outputs 1 if the sum is above zero, otherwise 0. Learning adjusts the weights whenever the output is wrong: each weight changes by the learning rate times the error times its input.

Java
class Main {
  public static void main(String[] args) {
    int[][] inputs = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
    int[] targets = {0, 0, 0, 1};
    double w1 = 0, w2 = 0, bias = 0, rate = 0.1;

    for (int epoch = 0; epoch < 50; epoch++) {
      for (int i = 0; i < inputs.length; i++) {
        double sum = w1 * inputs[i][0] + w2 * inputs[i][1] + bias;
        int output = sum > 0 ? 1 : 0;
        int error = targets[i] - output;
        w1 += rate * error * inputs[i][0];
        w2 += rate * error * inputs[i][1];
        bias += rate * error;
      }
    }

    for (int[] in : inputs) {
      double sum = w1 * in[0] + w2 * in[1] + bias;
      System.out.println(in[0] + " AND " + in[1] + " = " + (sum > 0 ? 1 : 0));
    }
  }
}
Read the full lesson