Skip to content

Commit 68676b4

Browse files
author
magicindian
committed
checking in perceptron
1 parent 914dad4 commit 68676b4

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package aima.learning.neural;
2+
3+
import aima.util.Matrix;
4+
5+
public class Perceptron implements FunctionApproximator {
6+
7+
private final Layer layer;
8+
private Vector lastInput;
9+
10+
public Perceptron(int numberOfNeurons, int numberOfInputs) {
11+
12+
this.layer = new Layer(numberOfNeurons, numberOfInputs, 2.0, -2.0,
13+
new HardLimitActivationFunction());
14+
15+
}
16+
17+
public Vector processInput(Vector input) {
18+
lastInput = input;
19+
return layer.feedForward(input);
20+
}
21+
22+
public void processError(Vector error) {
23+
Matrix weightUpdate = error.times(lastInput.transpose());
24+
layer.acceptNewWeightUpdate(weightUpdate);
25+
26+
Vector biasUpdate = layer.getBiasVector().plus(error);
27+
layer.acceptNewBiasUpdate(biasUpdate);
28+
29+
}
30+
31+
public void trainOn(NNDataSet innds, int numberofEpochs) {
32+
for (int i = 0; i < numberofEpochs; i++) {
33+
innds.refreshDataset();
34+
while (innds.hasMoreExamples()) {
35+
NNExample nne = innds.getExampleAtRandom();
36+
processInput(nne.getInput());
37+
Vector error = layer.errorVectorFrom(nne.getTarget());
38+
processError(error);
39+
}
40+
}
41+
}
42+
43+
public Vector predict(NNExample nne) {
44+
return processInput(nne.getInput());
45+
}
46+
47+
public int[] testOnDataSet(NNDataSet nnds) {
48+
int[] result = new int[] { 0, 0 };
49+
nnds.refreshDataset();
50+
while (nnds.hasMoreExamples()) {
51+
NNExample nne = nnds.getExampleAtRandom();
52+
Vector prediction = predict(nne);
53+
if (nne.isCorrect(prediction)) {
54+
result[0] = result[0] + 1;
55+
} else {
56+
result[1] = result[1] + 1;
57+
}
58+
}
59+
return result;
60+
}
61+
62+
}

0 commit comments

Comments
 (0)