Skip to content

Instantly share code, notes, and snippets.

@tmiz
Last active August 29, 2015 14:12
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 tmiz/a5ab0ec73e03025ef174 to your computer and use it in GitHub Desktop.
Save tmiz/a5ab0ec73e03025ef174 to your computer and use it in GitHub Desktop.
Perceptron
#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;
}
@tmiz
Copy link
Author

tmiz commented Dec 28, 2014

ported from example 10.1 of The Nature of code
http://natureofcode.com/book/chapter-10-neural-networks/

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