总是显示错误:AttributeError: 'Perception' object has no attribute 'predict'
总是找不到predict函数,是怎么回事?求大侠帮忙!
源代码:
总是找不到predict函数,是怎么回事?求大侠帮忙!
源代码:
2018-11-05
import numpy as npclass Perceptron(object): # 注释1 def __init__(self, eta = 0.01, n_iter = 10): self.eta = eta self.n_iter = n_iter def fit(self, X, y): # 注释2 self.w_ = np.zeros(1 + X.shape[1]) self.errors_ = [] for _ in range(self.n_iter): errors = 0 # 注释3 for xi, target in zip(X, y): update = self.eta * (target - self.predict(xi)) # 注释4 self.w_[1:] += update * xi self.w_[0] += update errors += int(update != 0.0) self.errors_.append(errors) def net_input(self, X): # 注释5 return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, -1)
注释1: eta:学习率 n_iter:权重向量的训练次数 w_:神经分叉权重向量 errors_:用于记录神经元判断出错次数 注释2: 输入训练数据,培训神经元,X是输入样本向量,y是对应的样本分类 X:shape[n_samples, n_features] 比如:X:[[1, 2, 3], [4, 5, 6]] 那么:n_samples: 2,n_features: 3,y:[1, -1] 初始化权重向量为0,加1是因为提到的w0,即步调函数的阈值 注释3: 比如:X:[[1, 2, 3], [4, 5, 6] 所以y:[1, -1],zip(X, y):[[1, 2, 3, 1]. [4, 5, 6, -1]] update = n * (y - y') 注释4: xi是一个向量 update * xi等价于:[ w1 = x1*update, w2 = x2*update, ...] 注释5: z = w0*1 + w1*x1 + w2*x2 + ... np.dot()是做点积
举报