此段代码报错怎么处理import numpy as np class Perceptron: def __init__(self, input_size, lr=0.01, epochs=100): self.W = np.zeros(input_size + 1) self.lr = lr self.epochs = epochs def sigmoid(self, x): return 1 / (1 + np.exp(-x)) def fit(self, X): for i in range(self.epochs): for j in range(len(X)): y_pred = np.dot(X[j].reshape(-1, 1), self.W) * self.sigmoid(X[j]) error = y_pred - X[j][0] delta = error * self.sigmoid(X[j]) * (1 - self.sigmoid(X[j])) self.W = self.W - self.lr * np.dot(X[j].reshape(-1, 1).T, delta) self.W = self.W * self.lr * (1 - self.sigmoid(X[j])) def predict(self, X): y_pred = np.dot(X.reshape(-1, 1), self.W) * self.sigmoid(X) return np.where(y_pred == 1, 1, -1) X = np.array([[1, 1, -1], [1, 2, -1], [2, 2, -1], [2, 1, -1], [3, 3, 1], [3, 4, 1], [4, 4, 1], [4, 3, 1]]) perceptron = Perceptron(input_size=3) perceptron.fit(X)
时间: 2023-06-08 22:07:32 浏览: 107
numpy_class.7z
这段代码的报错是缺失一个 ")" 符号,需要在第5行 "self.W = np.zeros(input_size 1)" 的结尾加上 ")",即改为 "self.W = np.zeros((input_size, 1))"。这样修改后,代码就可以正常运行了。
阅读全文