Professional Documents
Culture Documents
The Perceptron Algorithm
The Perceptron Algorithm
The Perceptron Algorithm
https://github.com/RichardKnop/ansi-c-perceptron
*/
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
class Perceptron
{
static int MAX_ITER = 100;
static double LEARNING_RATE = 0.1;
static int NUM_INSTANCES = 100;
static int theta = 0;
public static void main(String args[]){
double[] weights = new double[4];// 3 for input variables and one for bias
double localError, globalError;
int i, p, iteration, output;
weights[0] = randomNumber(0,1);// w1
weights[1] = randomNumber(0,1);// w2
weights[2] = randomNumber(0,1);// w3
weights[3] = randomNumber(0,1);// this is the bias
iteration = 0;
do {
iteration++;
globalError = 0;
//loop through all instances (complete one epoch)
for (p = 0; p < NUM_INSTANCES; p++) {
// calculate predicted class
output = calculateOutput(theta,weights, x[p], y[p], z[p]);
// difference between predicted and actual class values
localError = outputs[p] - output;
//update weights and bias
weights[0] += LEARNING_RATE * localError * x[p];
weights[1] += LEARNING_RATE * localError * y[p];
weights[2] += LEARNING_RATE * localError * z[p];
weights[3] += LEARNING_RATE * localError;
//summation of squared error (error value for all instances)
globalError += (localError*localError);
}
/**
* returns a random double value within a given range
* @param min the minimum value of the required range (int)
* @param max the maximum value of the required range (int)
* @return a random double value between min and max
*/
public static double randomNumber(int min , int max) {
DecimalFormat df = new DecimalFormat("#.####");
double d = min + Math.random() * (max - min);
String s = df.format(d);
double x = Double.parseDouble(s);
return x;
}
/**
* returns either 1 or 0 using a threshold function
* theta is 0range
* @param theta an integer value for the threshold
* @param weights[] the array of weights
* @param x the x input value
* @param y the y input value
* @param z the z input value
* @return 1 or 0
*/
static int calculateOutput(int theta, double weights[], double x, double y, double z)
{
double sum = x * weights[0] + y * weights[1] + z * weights[2] + weights[3];
return (sum >= theta) ? 1 : 0;
}