ppn = Perceptron(eta=0.1, n_iter=10) ppn.fit(X, y) plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') plt.xlabel("Epochs") plt.ylabel("error count") plt.show()
from matplotlib.colors import ListedColormapdef plot_decision_region(X, y, classifier, resolution=0.02): marker = ('s', 'x', 'o', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') # len(np.unique(y)=2 cmap = ListedColormap(colors[:len(np.unique(y))]) # 花茎的长度 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() # 花瓣的长度 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() print(x1_min, x1_max) print(x2_min, x2_max) # (备注) xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) # 输出语句 print(np.arange(x1_min, x1_max, resolution).shape) print(np.arange(x1_min, x1_max, resolution)) print(xx1.shape) print(xx1) print(np.arange(x2_min, x2_max, resolution).shape) print(np.arange(x2_min, x2_max, resolution)) print(xx2.shape) print(xx2)# 执行语句plot_decision_region(X, y, ppn, resolution=0.02)
备注: 将np.arange()中的向量扩展成一个矩阵 a = np.arange(x1_min, x1_max, resolution) 向量元素为185个 xx1[255, 185],将a中的元素作为一行,重复255行 b = np.arange(x2_min, x2_max, resolution) 向量元素为255个 xx2[255, 185],将b中的元素作为一列,重复185列
谢谢采纳~
x小写
把predict函数拿出来,和fit函数并列
predict函数和fit函数对齐就可以了。刚刚才发现的。
看看你的定义初始化函数 def __init__;
你可能写成了def __int__
他就是一个参数变量,代表类对象,感知器算法中是一个Perceptron对象,适应性神经元算法中是一个AdlineGD对象。
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)
我觉得应该是对的
需要把def net_input()和def predict()两个函数放到def fit()函数的前面
原因:代码好像是从上往下解释的,执行到fit函数式,程序还不知道有net_input和predict这两个函数
、你看185的是从3.3开始的,到7.0结束。255的是从0.0开始到5.1结束,自增是0.02,这样就形成了对应的点
少了,而且加上了还报错
假设向量w有m+1个元素,但只有后m个是权重,第一个是阈值
你看一下代码,照着改一下,应该就能解决。 from matplotlib.colors import ListedColormap def plot_decision_regions(X, y, classifier, resolution=0.02): marker = ('s', 'x', 'o', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() #将x1、x2最大最小值通过arange函数得到的向量,扩展成两个二维矩阵 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) #预测 Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) #ravel还原成单维向量 #绘制 Z= Z.reshape(xx1.shape) #将Z转换成与xx1一样的二维数组 plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap) #在两组分类结果中间画分割线-->必须线性可分 plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y==cl, 0], y=X[y==cl, 1], alpha=0.8, c=cmap(idx), marker=marker[idx], label=cl) ppn = Perceptron(0.1, 10) ppn.fit(X, y) plot_decision_regions(X, y, ppn, resolution=0.02)
第一段改为如下写法,具体原因可以对照得出:
import numpy as np
class Perceptron(object):
"""
eta:学习率
n_iter:权重向量的训练次数
w_:神经分叉权重向量
errors_:用于记录神经元判断出错次数
"""
def __init__(self, eta = 0.01, n_iter=10):
self.eta = eta;
self.n_iter = n_iter;
pass
def fit(self, X, y):
"""
输入训练数据,培训神经元,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
加一是因为前面算法提到的w0,也就是步调函数阈值
"""
self.w_ = np.zeros(1 + X.shape[1]);
self.errors_ = [];
for _ in range(self.n_iter) :
errors = 0
"""
X:[[1,2,3], [4,5,6]]
y:[1,-1]
zi(X,y) = [([1,2,3],1), ([4,5,6],-1)]
"""
for xi, target in zip(X,y):
"""
update = η * (y - y')
"""
update = self.eta * (target - self.predict(xi))
"""
xi是一个向量
update * xi 等价:
[▽W(1) = X[1]*update, ▽w(2) = X[2]*update, ▽w(3) = X[3]*update]
"""
self.w_[1:] += update * xi
self.w_[0] += update;
errors += int(update != 0.0)
self.errors_.append(errors)
pass
pass
pass
def net_input(self, X):
"""
z = W0*1 + W1*X1 +.... Wn*Xn
"""
return np.dot(X, self.w_[1:]) + self.w_[0]
pass
def predict(self, X):
return np.where(self.net_input(X) >= 0.0 , 1, -1)
pass
pass
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.4,3.7,1.5,0.2,Iris-setosa
4.8,3.4,1.6,0.2,Iris-setosa
4.8,3.0,1.4,0.1,Iris-setosa
4.3,3.0,1.1,0.1,Iris-setosa
5.8,4.0,1.2,0.2,Iris-setosa
5.7,4.4,1.5,0.4,Iris-setosa
5.4,3.9,1.3,0.4,Iris-setosa
5.1,3.5,1.4,0.3,Iris-setosa
5.7,3.8,1.7,0.3,Iris-setosa
5.1,3.8,1.5,0.3,Iris-setosa
5.4,3.4,1.7,0.2,Iris-setosa
5.1,3.7,1.5,0.4,Iris-setosa
4.6,3.6,1.0,0.2,Iris-setosa
5.1,3.3,1.7,0.5,Iris-setosa
4.8,3.4,1.9,0.2,Iris-setosa
5.0,3.0,1.6,0.2,Iris-setosa
5.0,3.4,1.6,0.4,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa
5.2,3.4,1.4,0.2,Iris-setosa
4.7,3.2,1.6,0.2,Iris-setosa
4.8,3.1,1.6,0.2,Iris-setosa
5.4,3.4,1.5,0.4,Iris-setosa
5.2,4.1,1.5,0.1,Iris-setosa
5.5,4.2,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
5.0,3.2,1.2,0.2,Iris-setosa
5.5,3.5,1.3,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa
4.4,3.0,1.3,0.2,Iris-setosa
5.1,3.4,1.5,0.2,Iris-setosa
5.0,3.5,1.3,0.3,Iris-setosa
4.5,2.3,1.3,0.3,Iris-setosa
4.4,3.2,1.3,0.2,Iris-setosa
5.0,3.5,1.6,0.6,Iris-setosa
5.1,3.8,1.9,0.4,Iris-setosa
4.8,3.0,1.4,0.3,Iris-setosa
5.1,3.8,1.6,0.2,Iris-setosa
4.6,3.2,1.4,0.2,Iris-setosa
5.3,3.7,1.5,0.2,Iris-setosa
5.0,3.3,1.4,0.2,Iris-setosa
7.0,3.2,4.7,1.4,Iris-versicolor
6.4,3.2,4.5,1.5,Iris-versicolor
6.9,3.1,4.9,1.5,Iris-versicolor
5.5,2.3,4.0,1.3,Iris-versicolor
6.5,2.8,4.6,1.5,Iris-versicolor
5.7,2.8,4.5,1.3,Iris-versicolor
6.3,3.3,4.7,1.6,Iris-versicolor
4.9,2.4,3.3,1.0,Iris-versicolor
6.6,2.9,4.6,1.3,Iris-versicolor
5.2,2.7,3.9,1.4,Iris-versicolor
5.0,2.0,3.5,1.0,Iris-versicolor
5.9,3.0,4.2,1.5,Iris-versicolor
6.0,2.2,4.0,1.0,Iris-versicolor
6.1,2.9,4.7,1.4,Iris-versicolor
5.6,2.9,3.6,1.3,Iris-versicolor
6.7,3.1,4.4,1.4,Iris-versicolor
5.6,3.0,4.5,1.5,Iris-versicolor
5.8,2.7,4.1,1.0,Iris-versicolor
6.2,2.2,4.5,1.5,Iris-versicolor
5.6,2.5,3.9,1.1,Iris-versicolor
5.9,3.2,4.8,1.8,Iris-versicolor
6.1,2.8,4.0,1.3,Iris-versicolor
6.3,2.5,4.9,1.5,Iris-versicolor
6.1,2.8,4.7,1.2,Iris-versicolor
6.4,2.9,4.3,1.3,Iris-versicolor
6.6,3.0,4.4,1.4,Iris-versicolor
6.8,2.8,4.8,1.4,Iris-versicolor
6.7,3.0,5.0,1.7,Iris-versicolor
6.0,2.9,4.5,1.5,Iris-versicolor
5.7,2.6,3.5,1.0,Iris-versicolor
5.5,2.4,3.8,1.1,Iris-versicolor
5.5,2.4,3.7,1.0,Iris-versicolor
5.8,2.7,3.9,1.2,Iris-versicolor
6.0,2.7,5.1,1.6,Iris-versicolor
5.4,3.0,4.5,1.5,Iris-versicolor
6.0,3.4,4.5,1.6,Iris-versicolor
6.7,3.1,4.7,1.5,Iris-versicolor
6.3,2.3,4.4,1.3,Iris-versicolor
5.6,3.0,4.1,1.3,Iris-versicolor
5.5,2.5,4.0,1.3,Iris-versicolor
5.5,2.6,4.4,1.2,Iris-versicolor
6.1,3.0,4.6,1.4,Iris-versicolor
5.8,2.6,4.0,1.2,Iris-versicolor
5.0,2.3,3.3,1.0,Iris-versicolor
5.6,2.7,4.2,1.3,Iris-versicolor
5.7,3.0,4.2,1.2,Iris-versicolor
5.7,2.9,4.2,1.3,Iris-versicolor
6.2,2.9,4.3,1.3,Iris-versicolor
5.1,2.5,3.0,1.1,Iris-versicolor
5.7,2.8,4.1,1.3,Iris-versicolor
6.3,3.3,6.0,2.5,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
7.1,3.0,5.9,2.1,Iris-virginica
6.3,2.9,5.6,1.8,Iris-virginica
6.5,3.0,5.8,2.2,Iris-virginica
7.6,3.0,6.6,2.1,Iris-virginica
4.9,2.5,4.5,1.7,Iris-virginica
7.3,2.9,6.3,1.8,Iris-virginica
6.7,2.5,5.8,1.8,Iris-virginica
7.2,3.6,6.1,2.5,Iris-virginica
6.5,3.2,5.1,2.0,Iris-virginica
6.4,2.7,5.3,1.9,Iris-virginica
6.8,3.0,5.5,2.1,Iris-virginica
5.7,2.5,5.0,2.0,Iris-virginica
5.8,2.8,5.1,2.4,Iris-virginica
6.4,3.2,5.3,2.3,Iris-virginica
6.5,3.0,5.5,1.8,Iris-virginica
7.7,3.8,6.7,2.2,Iris-virginica
7.7,2.6,6.9,2.3,Iris-virginica
6.0,2.2,5.0,1.5,Iris-virginica
6.9,3.2,5.7,2.3,Iris-virginica
5.6,2.8,4.9,2.0,Iris-virginica
7.7,2.8,6.7,2.0,Iris-virginica
6.3,2.7,4.9,1.8,Iris-virginica
6.7,3.3,5.7,2.1,Iris-virginica
7.2,3.2,6.0,1.8,Iris-virginica
6.2,2.8,4.8,1.8,Iris-virginica
6.1,3.0,4.9,1.8,Iris-virginica
6.4,2.8,5.6,2.1,Iris-virginica
7.2,3.0,5.8,1.6,Iris-virginica
7.4,2.8,6.1,1.9,Iris-virginica
7.9,3.8,6.4,2.0,Iris-virginica
6.4,2.8,5.6,2.2,Iris-virginica
6.3,2.8,5.1,1.5,Iris-virginica
6.1,2.6,5.6,1.4,Iris-virginica
7.7,3.0,6.1,2.3,Iris-virginica
6.3,3.4,5.6,2.4,Iris-virginica
6.4,3.1,5.5,1.8,Iris-virginica
6.0,3.0,4.8,1.8,Iris-virginica
6.9,3.1,5.4,2.1,Iris-virginica
6.7,3.1,5.6,2.4,Iris-virginica
6.9,3.1,5.1,2.3,Iris-virginica
5.8,2.7,5.1,1.9,Iris-virginica
6.8,3.2,5.9,2.3,Iris-virginica
6.7,3.3,5.7,2.5,Iris-virginica
6.7,3.0,5.2,2.3,Iris-virginica
6.3,2.5,5.0,1.9,Iris-virginica
6.5,3.0,5.2,2.0,Iris-virginica
6.2,3.4,5.4,2.3,Iris-virginica
5.9,3.0,5.1,1.8,Iris-virginica
同问
自己写进去的代码执行报错
TypeError Traceback (most recent call last)<ipython-input-65-7b957d04361e> in <module>----> 1 ppn = Perceptron(eta=0.1, n_iter=10) 2 ppn.fit(X, y) 3 plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') 4 plt.xlabel('Epochs') 5 plt.ylabel('错误分类次数')TypeError: Perceptron() takes no arguments
应该是zeros
你可以试试把y的数值减小一个
y=df.loc[0:99,4].values
https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
这一节有问题,运行时有错误,解决方法如下:
import numpy as np
class Perceptron(object):
def __init__(self, eta=0.01, n_iter=10):
self.eta=eta
self.n_iter=n_iter
def fit(self, X, y):
self.w_=np.zeros(1+X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors =0
for xi,target in zip(X,y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.net_input(X) >= 0.0, 1, -1)
ppn = Perceptron(eta=0.1,n_iter=10)
ppn.fit(X,y)
print('Totalnumberofmisclassifications:%dof100'%(y!=ppn.predict(X)))
plt.plot(range(1,len(ppn.errors_) + 1),ppn.errors_,marker='o')
plt.xlabel('Epochs')
plt.ylabel('errorclassifynumber')
plt.show()
意思就是把这个类和ppn=.... 放在一起,同时,这个类还要改一下,你可以发现我这个类和视频里的有一点点不一样,但没有影响
先创建感知器
ppn = Perceptron(eta=0.1, n_iter=10)
然后训练就可以了
ppn.fit(X, y)
np.zeros()
将net_input 和 predict 方法 放到 fit方法外面
#画分界线 x1_min, x1_max = X[:, 0].min()-1, X[:, 0].max() x2_min, x2_max = X[:, 1].min()-1, X[:, 1].max() ## 生成网格数据 ## xx1为横隔线 ## xx2为纵隔线 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution)) z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) z = z.reshape(xx1.shape) ## 绘制denggaoxian, f代表fill, 没有f则不填充颜色 ## alpha 为颜色为填充颜色透明度 plt.contour(xx1,xx2,z,alpha=0.4,cmap = cmap) plt.contourf(xx1,xx2,z,alpha=0.4,cmap = cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) plt.xlabel('pedal length') plt.ylabel('scape length')
这部分代码其实只是为了描绘出分隔两类的那条分界线,减1只是为了扩大坐标轴范围,点更居中一些,这样画出的图会更好看。
以上,谢谢!
ppn = Perceptron(eta=0.1, n_iter=10) ppn.fit(X, y)
先要定义ppn这个对象
同问!