Skip to content

Instantly share code, notes, and snippets.

@CoffiDev
Created August 20, 2015 09:16
Show Gist options
  • Save CoffiDev/d144f6cd81a9df0b75c1 to your computer and use it in GitHub Desktop.
Save CoffiDev/d144f6cd81a9df0b75c1 to your computer and use it in GitHub Desktop.
import timing
import sys
from random import randint, uniform
class Perceptron:
weights = []
c = 0.01
error_0 = 0
error_1 = 0
error_n1 = 0
def __init__(self):
self.weights = [uniform(-1, 1), uniform(-1, 1), 1]
#self.weights = [-7.064101819032928, 3.030346989299225, 1]
def feedforward(self, inputs):
total_sum = 0
for index, weight in enumerate(self.weights):
total_sum += inputs[index] * weight
return self.activate(total_sum)
def activate(self, total_sum):
if total_sum > 0:
return 1
return -1
def train(self, inputs, desired):
guess = self.feedforward(inputs)
error = desired - guess
self.count_results(error)
for index, weight in enumerate(self.weights):
self.weights[index] += self.c * error * inputs[index]
if index == 2:
self.weights[index] = 1
return error
def count_results(self, error):
if error == 0:
self.error_0 += 1
elif error == 2:
self.error_1 += 1
else:
self.error_n1 += 1
class Trainer:
inputs = []
answer = 0
def __init__(self, x, y, a):
self.inputs = [x, y, 1]
self.answer = a
def f(x):
return 2 * x + 1
def setup():
training = []
for i in range(1000000):
x = randint(0, 10)
y = randint(0, 10)
answer = 1
if y < f(x):
answer = -1
training.append(Trainer(x, y, answer))
return training
def set_up(number_of_iterations):
for i in range(number_of_iterations):
x = randint(0, 10)
y = randint(0, 10)
answer = 1
if y < f(x):
answer = -1
yield Trainer(x, y, answer)
def main():
if len(sys.argv) > 1:
number_of_iterations = int(sys.argv[1])
else:
number_of_iterations = 1000000
ptron = Perceptron()
first_score = 0
last_score = 0
range_score = 20
for i, train in enumerate(set_up(number_of_iterations)):
result = ptron.train(train.inputs, train.answer)
if i == (number_of_iterations / 10000) - 1:
print 'De %s hay %s Aciertos: ' % (i + 1, ptron.error_0)
if i == (number_of_iterations / 100) - 1:
print 'De %s hay %s Aciertos: ' % (i + 1, ptron.error_0)
if i == number_of_iterations - 1:
print 'De %s hay %s Aciertos: ' % (i + 1, ptron.error_0)
if result == 0:
if i < range_score:
first_score += 1
elif i >= number_of_iterations - range_score:
last_score += 1
print 'Score first %s: %s' % (range_score, first_score)
print 'Score last %s: %s' % (range_score, last_score)
print ptron.weights
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment