/*************************************************** Starter code for CS182 Assignment 4: Backpropagation Net.java **************************************************/ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; import java.util.*; /** * Class implementing a basic three-layer neural network. */ public class Net { // All initial weights in the network range from -1 to 1. static double MIN_WEIGHT = -1.0; static double MAX_WEIGHT = 1.0; // training parameters (with some defaults) // Don't change these defaults or the test function won't work static double learningRate = 0.1; static double momentum = 0.1; static double errorCriterion = .1; // error threshold for training to stop int numEpochs = 10000; // number of epochs before training stops // (unless error drops below threshold) int curEpochs; int[][] trainingData; int[][] trainingTargets; /** A bias neuron, with output always equal to 1 */ Unit Bias; /** The first input neuron, should take on first value from trainingData */ Unit inUnit1; /** The second input neuron, should take on second value from trainingData */ Unit inUnit2; /** The output neuron, should compute function of inputs and give Net's output */ Unit outUnit; // other Net attributes ? /** * Constructor for Net class. * * Create Net with the specified architecture and data. * * @param patterns * Array of input patterns (each an array of int) * @param targets * Array of output patterns (each an array of int) */ public Net(int[][] patterns, int[][] targets) { this.trainingData = patterns; this.trainingTargets = targets; // The Bias is implemented as a unit connected directly to every none input // node. // The bias node will always be active, and have no incomming connections. Bias = new Unit(); Bias.activation = 1.0; inUnit1 = new Unit(); inUnit2 = new Unit(); outUnit = new Unit(); inUnit1.setOutgoingUnit(outUnit); inUnit2.setOutgoingUnit(outUnit); outUnit.addIncomingUnit(inUnit1); outUnit.addIncomingUnit(inUnit2); outUnit.addIncomingUnit(Bias); outUnit.initialize(); } /** * feedforward() * * @param pattern * An input training pattern * * Present pattern and compute activations for rest of net. */ public void feedforward(int[] pattern) { inUnit1.activation = pattern[0]; inUnit2.activation = pattern[1]; outUnit.computeActivation(); } /** * computeError() * * @return current network error * * Present all patterns to network and calculate current error. Current error * is measured by sum of squared error on output nodes. */ public double computeError() { double sumErr = 0; for (int i=0; ierrorCriterion) { for (int i=0; i