Created
April 14, 2019 14:43
-
-
Save draganczukp/ae241311c3d1d6bc3aec3b58622f26db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.DecimalFormat; | |
import java.util.Random; | |
public class Perceptron { | |
public static void main (String[] args) { | |
double[][] inputs = { | |
{1, 1}, | |
{1, 0}, | |
{0, 1}, | |
{0, 0} | |
}; | |
double[] outputs = { | |
1, | |
0, | |
0, | |
0 | |
}; | |
Perceptron p = new Perceptron(2); | |
DecimalFormat df = new DecimalFormat("0.000000"); | |
System.out.println("untrained"); | |
for(double[] input : inputs){ | |
double guess = p.guess(input); | |
System.out.println(df.format(guess)); | |
} | |
Random random = new Random(System.nanoTime()); | |
for (int i = 0; i < 10000; i++) { | |
int index = random.nextInt(4); | |
p.train(inputs[index], outputs[index]); | |
} | |
System.out.println("trained"); | |
for(double[] input : inputs){ | |
double guess = p.guess(input); | |
System.out.println(df.format(guess)); | |
} | |
} | |
double[] weights; | |
double learningRate = 0.1; | |
public Perceptron(int inputCount){ | |
this.weights = new double[inputCount+1]; | |
for (int i = 0; i < weights.length; i++) { | |
weights[i] = .5f; | |
} | |
} | |
public double guess(double[] input){ | |
double sum = 0; | |
for (int i = 0; i < input.length; i++) { | |
sum += input[i] * weights[i]; | |
} | |
// BIAS | |
sum += weights[weights.length-1]; | |
return this.activation(sum); | |
} | |
public void train(double[] input, double label){ | |
double guess = this.guess(input); | |
double error = label - guess; | |
for (int i = 0; i < input.length; i++) { | |
this.weights[i] += error * input[i] * this.learningRate; | |
} | |
int lastIndex = weights.length - 1; | |
this.weights[lastIndex] += error * this.learningRate; | |
} | |
public double activation(double n){ | |
return 1d/(1d + Math.exp(-n)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
kozak