Last active
August 29, 2015 14:12
-
-
Save tmiz/a5ab0ec73e03025ef174 to your computer and use it in GitHub Desktop.
Perceptron
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include "Perceptron.h" | |
#include <math.h> | |
const float c = 0.01; | |
Perceptron::Perceptron(int n) { | |
weights = new float[n]; | |
for (int i = 0; i < n; i++) { | |
weights[i] = generateRandFloatValue(); | |
} | |
} | |
Perceptron::~Perceptron() | |
{ | |
delete weights; | |
} | |
void Perceptron::getWeights(float *out,int weightNum) | |
{ | |
for (int i = 0; i < weightNum; i++) { | |
out[i] = weights[i]; | |
} | |
} | |
float Perceptron::feedforward(float *inputs, int inputNum) | |
{ | |
float sum = 0; | |
for (int i = 0; i < inputNum; i++) { | |
sum += inputs[i]*weights[i]; | |
} | |
return activate(sum); | |
} | |
float Perceptron::activate(float sum) | |
{ | |
#if 0 | |
return 1/(1+exp(-sum)); //standard sigmoid | |
#else | |
if (sum > 0) { | |
return 1.0f; | |
} else { | |
return -1.0f; | |
} | |
#endif | |
} | |
void Perceptron::train(float *inputs,int inputNum, int desired) | |
{ | |
int guess = feedforward(inputs, inputNum); | |
float error = desired - guess; | |
for (int i = 0; i < inputNum; i++) { | |
weights[i] += c * error * inputs[i]; | |
} | |
} | |
float generateRandFloatValue() | |
{ | |
float r = (float)rand()/(float)RAND_MAX; | |
return r * 2.0 - 1.0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ported from example 10.1 of The Nature of code
http://natureofcode.com/book/chapter-10-neural-networks/