运行视频中的代码有问题
运行 In [5] plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') 报错 'module' object has no attribute 'scatter' 什么意思
运行 In [5] plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') 报错 'module' object has no attribute 'scatter' 什么意思
2017-07-27
这一节有问题,运行时有错误,解决方法如下:
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=.... 放在一起,同时,这个类还要改一下,你可以发现我这个类和视频里的有一点点不一样,但没有影响
# -*-coding: utf-8
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):
"""
:param X:训练样本,电信号向量;
X:shape(n_samples,n_features)X中的样本个数,接收电信号的个数
X:[[1,2,3],[4,5,6]] n_samples:2;n_features:3
:param y:样本对应的分类
y:[1,-1]
zip(X,y)=[[1,2,3,1],[4,5,6,-1]]
初始化权重向量
加一是因为将阈值作为w0
"""
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 = eta*(y-y')
xi是一个向量,更新权重
"""
update=self.eta*(target-self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update # 更新阈值
errors+=int(update)
self.errors_.append(errors)
pass
pass
pass
def net_input(self, X):
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
import pandas as pd
import matplotlib.pyplot as plt
file='/home/bokebi/competition/tianchi_speed_prediction/learn_project/LSTM-Neural-Network-for-Time-Series-Prediction/imoocdata.csv'
df=pd.read_csv(file,header=None)
y=df.loc[0:100,4].values
y=np.where(y=='Iris-setosa',-1,1)
x=df.loc[0:100,[0,2]].values
from matplotlib.colors import ListedColormap
def plot_decision_regions(X,y,classifier,resolution=0.02):
markers=('s','x','o','v')
colors=('red','blue','lightgreen','gray','cyan')
cmap=ListedColormap(colors[:len(np.unique(y))])
pass
x1_min,x1_max=x[:,0].min()-1,x[:,0].max()
x2_min,x2_max=x[:,1].min()-1,x[:,1].max()
xx1,xx2=np.meshgrid(np.arange(x1_min,x1_max,resolution),np.arange(x2_min,x2_max,resolution))
classifier.fit(X,y)
Z=classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
Z=Z.reshape(xx1.shape)
plt.contourf(xx1,xx2,Z,alpha=0.4,cmap=cmap)
plt.xlim(xx1.min(),xx1.max())
plt.xlim(xx2.min(),xx2.max())
for idx,c1 in enumerate(np.unique(y)):
plt.scatter(x=X[y==c1,0],y=X[y==c1,1],alpha=0.8,c=cmap(idx),marker=markers[idx],label=c1)
pass
ppn=Perceptron()
plot_decision_regions(x,y,ppn,resolution=0.02)
plt.xlabel('len1')
plt.ylabel('len2')
plt.legend(loc='upper left')
plt.show()
举报