32 lines
785 B
Python
32 lines
785 B
Python
import random
|
|
|
|
class Perceptron:
|
|
def __init__(self, n):
|
|
self.weights = [random.randint(-1, 1) for _ in range(0, n)]
|
|
self.lr = 0.1
|
|
|
|
@staticmethod
|
|
def sign(output):
|
|
if output >= 0:
|
|
return 1
|
|
else:
|
|
return -1
|
|
|
|
def guess(self, inputs):
|
|
s = 0
|
|
for i, inp in enumerate(inputs):
|
|
s += inp * self.weights[i]
|
|
|
|
return Perceptron.sign(s)
|
|
|
|
def guessY(self, x):
|
|
w0 = self.weights[0]
|
|
w1 = self.weights[1]
|
|
w2 = self.weights[2]
|
|
|
|
return -(w2 / w1) - (w0 / w1) * x
|
|
|
|
def train(self, inputs, target):
|
|
error = target - self.guess(inputs)
|
|
for i, w in enumerate(self.weights):
|
|
self.weights[i] += error * inputs[i] * self.lr
|