此段代码报错怎么修改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 11:07:20 浏览: 182
这段代码的报错可能是因为在初始化权重 self.W 时,括号不完整,应该是 np.zeros((input_size, 1)) 。
修改后的代码如下:
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)
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)