001 package aima.learning.neural; 002 003 import aima.util.Matrix; 004 005 public class Perceptron implements FunctionApproximator { 006 007 private final Layer layer; 008 private Vector lastInput; 009 010 public Perceptron(int numberOfNeurons, int numberOfInputs) { 011 012 this.layer = new Layer(numberOfNeurons, numberOfInputs, 2.0, -2.0, 013 new HardLimitActivationFunction()); 014 015 } 016 017 public Vector processInput(Vector input) { 018 lastInput = input; 019 return layer.feedForward(input); 020 } 021 022 public void processError(Vector error) { 023 Matrix weightUpdate = error.times(lastInput.transpose()); 024 layer.acceptNewWeightUpdate(weightUpdate); 025 026 Vector biasUpdate = layer.getBiasVector().plus(error); 027 layer.acceptNewBiasUpdate(biasUpdate); 028 029 } 030 031 public void trainOn(NNDataSet innds, int numberofEpochs) { 032 for (int i = 0; i < numberofEpochs; i++) { 033 innds.refreshDataset(); 034 while (innds.hasMoreExamples()) { 035 NNExample nne = innds.getExampleAtRandom(); 036 processInput(nne.getInput()); 037 Vector error = layer.errorVectorFrom(nne.getTarget()); 038 processError(error); 039 } 040 } 041 } 042 043 public Vector predict(NNExample nne) { 044 return processInput(nne.getInput()); 045 } 046 047 public int[] testOnDataSet(NNDataSet nnds) { 048 int[] result = new int[] { 0, 0 }; 049 nnds.refreshDataset(); 050 while (nnds.hasMoreExamples()) { 051 NNExample nne = nnds.getExampleAtRandom(); 052 Vector prediction = predict(nne); 053 if (nne.isCorrect(prediction)) { 054 result[0] = result[0] + 1; 055 } else { 056 result[1] = result[1] + 1; 057 } 058 } 059 return result; 060 } 061 062 }