游戏介绍
# -*- coding: utf-8 -*- """ Created on Wed Oct 12 13:28:28 2022 @author: 31479 """ import numpy as np class Perceptron: def __init__(self, N, alpha=0.1): # 初始化权重矩阵W,并存储学习率alpha self.W = np.random.randn(N + 1) / np.sqrt(N) self.alpha = alpha def step(self, x): # 应用阶跃函数 return 1 if x > 0 else 0 def fit(self, X, y, epochs=10): # 在训练数据中插入一列1以处理偏置项 X = np.c_[X, np.ones((X.shape[0]))] # 循环epochs指定的次数 for epoch in np.arange(0, epochs): # 循环每个单独的数据点 for (x, target) in zip(X, y): # 计算输入特征和权重矩阵的点积,然后通过阶跃函数传递该值以获得预测值 p = self.step(np.dot(x, self.W)) # 仅当预测值不正确时,才进行权重更新 if p != target: # 计算误差 error = p - target # 更新权重矩阵 self.W += -self.alpha * error * x def predict(self, X, addBias=True): # 确保输入是矩阵 X = np.atleast_2d(X) # 检查是否需要添加偏置列 if addBias: X = np.c_[X, np.ones((X.shape[0]))] # 计算输入特征和权重矩阵的点积,然后通过阶跃函数传递该值 return self.step(np.dot(X, self.W)) # 构造或门数据集 X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([[0], [1], [1], [1]]) # 定义感知机并训练它 print("[INFO] 正在训练感知机...") p = Perceptron(X.shape[1], alpha=0.1) p.fit(X, y, epochs=20) # 现在可以测试感知机 print("[INFO] 正在测试感知机...") # 遍历所有数据点 for (x, target) in zip(X, y): # 对数据点进行预测并显示结果 pred = p.predict(x) print("[INFO] 数据点={}, 真实标签={}, 预测值={}".format( x, target[0], pred))