Java: a two-layer network that computes XOR
A hidden layer lets a network build new features. One hidden neuron can learn OR and another can learn AND. The output neuron then fires when OR is on but AND is off, which is exactly XOR.
Java
import java.util.Locale;
class Main {
static double sigmoid(double z) {
return 1.0 / (1.0 + Math.exp(-z));
}
public static void main(String[] args) {
int[][] inputs = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
for (int[] in : inputs) {
double or = sigmoid(20 * in[0] + 20 * in[1] - 10);
double and = sigmoid(20 * in[0] + 20 * in[1] - 30);
double out = sigmoid(20 * or - 20 * and - 10);
System.out.printf(Locale.ROOT, "%d XOR %d = %.3f%n", in[0], in[1], out);
}
}
}