import numpy as np
import matplotlib.pyplot as plt
# 定义感知器,并使其可以预测输入数据类型,可以训练感知器
class Perceptron:
def __init__(self, input, lrate=0.1, epochs=100):
self.weights = np.zeros(input + 1)
self.lrate = lrate
self.epochs = epochs
def activation_fn(self, x):
return 1 if x >= 0 else 0
def predict(self, x):
z = self.weights.T.dot(x)
a = self.activation_fn(z)
return a
def train_fitable(self, X, d):
for _ in range(self.epochs):
for i in range(d.shape[0]):
x = np.insert(X[i], 0, 1)
y = self.predict(x)
e = d[i] - y
self.weights = self.weights + self.lrate * e * x
# 随机生成数据
np.random.seed(0)
num_samples = 200
X = np.random.randn(num_samples, 2)
d = np.zeros(num_samples)
d[X[:, 0] + X[:, 1] >= 0] = 1
# 创建感知器实例并训练 perceptron = Perceptron(input=2) perceptron.train_fitable(X, d)# 绘制分类结果 plt.scatter(X[d == 0][:, 0], X[d == 0][:, 1], color='b', marker='o', label='0') plt.scatter(X[d == 1][:, 0], X[d == 1][:, 1], color='r', marker='o', label='1') x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max, 0.1)) Z = np.array([perceptron.predict(np.array([1, xx1_, xx2_])) for xx1_, xx2_ in np.c_[xx1.ravel(), xx2.ravel()]]) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.3) plt.xlabel('X1') plt.ylabel('X2') plt.legend(loc='best',edgecolor='blue') plt.show()
结果: