Skip to content

Instantly share code, notes, and snippets.

@draganczukp
Created April 14, 2019 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draganczukp/ae241311c3d1d6bc3aec3b58622f26db to your computer and use it in GitHub Desktop.
Save draganczukp/ae241311c3d1d6bc3aec3b58622f26db to your computer and use it in GitHub Desktop.
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));
}
}
@Kamol3k
Copy link

Kamol3k commented Apr 14, 2019

kozak

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment