Skip to content

Instantly share code, notes, and snippets.

@tmiz tmiz/Perceptron.cpp
Last active Aug 29, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.