import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, epoch,input_size=2, lr=0.1):
self.epoch = epoch
self.W = np.zeros(input_size + 1)
self.lr = lr
#定义激活函数
def activation_fn(self, x):
return 1 if x >= 0 else 0
def predict(self, x):
z = self.W.T.dot(x)
a = self.activation_fn(z)
return a
def train(self, X, d):
for i in range(self.epoch):
for j in range(d.shape[0]):
x = np.insert(X[j], 0, 1)
y = self.predict(x)
e = d[j] - y
self.W = self.W + self.lr * e * x
def plot_show(self, X):
x1 = np.linspace(-2, 2, 10)
x2 = -(self.W[0] / self.W[2]) - (self.W[1] / self.W[2]) * x1
plt.plot(x1, x2)
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()
#生成样本
# np.random.seed(0)
X = np.random.randn(100, 2)
y = np.array([0 if x1 + x2 < 0 else 1 for x1, x2 in X])
perceptron = Perceptron(epoch=1000)
perceptron.train(X, y)
perceptron.plot_show(X)
运行结果图