package neuralnetwork; public class Constants { private Constants(){ } public static final int NUM_OF_FEATURES = 2; public static final int NUM_OF_DATA = 4; public static final double LEARNING_RATE = 0.1; public static final int THREASHOLD = 1; }
package neuralnetwork; public class And { private int[][] trainingData; private int[] trainingTargets; private double[] weights; private double error = 1; public And(int[][] trainingData, int[] trainingTargets, double[] weights){ this.trainingData = trainingData; this.trainingTargets = trainingTargets; this.weights = weights; } public void trainNetwork(){ while( error != 0 ){ for(int rowIndex=0;rowIndex<Constants.NUM_OF_DATA;++rowIndex){ double weightedSum = 0; weightedSum = getWeightedSum(rowIndex, weightedSum); int outputValue = activationFunction(weightedSum); error = this.trainingTargets[rowIndex] - outputValue; // update the weights for(int j=0;j<this.weights.length;++j){ this.weights[j] += Constants.LEARNING_RATE * error * trainingData[rowIndex][j]; } } System.out.println("Edge weights are: " + weights[0]+" - " + weights[1]); } System.out.println("Final edge weights are: " + weights[0]+"-"+weights[1]); } private int activationFunction(double weightedSum) { if( weightedSum >= Constants.THREASHOLD ){ return 1; } return 0; } private double getWeightedSum(int index, double weightedSum) { for(int j=0;j<Constants.NUM_OF_FEATURES;++j){ weightedSum = weightedSum + trainingData[index][j] * weights[j]; } return weightedSum; } }
package neuralnetwork; public class App { public static void main(String[] args) { double[] weights = { 0 , 0 }; int[][] trainingData = { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } }; int[] trainingTargets = { 0, 0, 0, 1 }; And problem = new And(trainingData, trainingTargets, weights); problem.trainNetwork(); } }
Output of the program is :
Edge weights are: 0.1 - 0.1 Edge weights are: 0.2 - 0.2 Edge weights are: 0.30000000000000004 - 0.30000000000000004 Edge weights are: 0.4 - 0.4 Edge weights are: 0.5 - 0.5 Edge weights are: 0.5 - 0.5 Final edge weights are: 0.5-0.5