注意loc函数的端点是闭区间
#注意看我y和X这两行的注释:要么全是df.loc,要么全是df.iloc,核对一下自己代码
import matplotlib.pyplot as plt
import numpy as np
y = df.loc[0:100, 4].values #loc/iloc得统一
y = np.where(y == 'Iris-setosa', -1, 1)
#抽出第0列和第2列
X = df.loc[0:100, [0, 2]].values # loc/iloc得统一
plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa')
plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='versicolor')
plt.xlabel('花瓣长度')
plt.ylabel('花茎长度')
plt.legend(loc='upper left')
#plt.show()
两行code解决问题,只显示error级别的通知
from matplotlib.axes._axes import _log as matplotlib_axes_logger matplotlib_axes_logger.setLevel('ERROR')
我也用的python3.7,这是我的代码,谢谢采纳~
import numpy as np class 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()是做点积
from matplotlib.colors import ListedColormap
from matplotlib.colors import ListedColormap def plot_decision_region(X, y, classifier, resolution=0.02): 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() 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) plt.contourf(xx1, xx2, z, alpha=0.4, cmap=cmap) plt.xlim(xx1.min(), xx1.max()) plt.xlim(xx2.min(), xx2.max()) plt.scatter(X[:50,0],X[:50,1],color='red',marker='o',label='setosa') plt.scatter(X[50:100,0],X[50:100,1],color='blue',marker='x',label='versicolor') # 执行语句 plot_decision_regions(X,y,ppn,resolution=0.02) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.xlabel('花茎长度') plt.ylabel('花瓣长度') plt.legend(loc='upper left') plt.show()
设置的类型不对呀
将y = df.loc[0:100, 4].values改为y = df.iloc[0:100, 4].values
看出区别了吗?loc前面多个i。不然y的维度为101。
当然你也可以直接改成y = df.loc[0:99, 4].values
是的,classifier参数对应的就是感知器
通过图上xlabel可以看到显示的是“Epocha”,是上一张图的横轴,
plot_decision_reqions()的图画成这样应该是和上一张图叠加在一起显示了,建议在plot_decision_reqions(X,y,ppn,resolution=0.02)语句前面添加一句代码:plt.figure(),表示新建一个画板,这样就不会出现和上面的图叠加显示的情况了。
#拼写错误,应该是'contourf'
可以啊,搜索关键词“python anaconda jupyter”+“教程 安装”。mac用命令行安装更简单,先搜索”homebrew 教程”
我是这样改的:
import matplotlib.pyplot as plt
import numpy as np
y = df.loc[0:99, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
#print(y)
X = df.iloc[0:100, [0, 2]].values
#print(X)
plt.scatter(X[:50, 0], X[:50, 1], color='red', marker='o', label='setosa')
plt.scatter(X[50:100, 0], X[50:100, 1], color='blue', marker='x', label='vericolor')
plt.rcParams['font.sans-serif']=['SimHei']
plt.xlabel('花瓣长度')
plt.ylabel('花茎长度')
plt.legend(loc='upper left')
plt.show()
另外,还有一处会报错,makers这,改成maker:
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)
y = df.loc[:100, 4].values 改为 y = df.loc[:99, 4].values
或者
x = df.iloc[:100, [0, 2]].values 改为 x = df.iloc[:101, [0, 2]].values
不知道为啥,反正能运行了就,不然说数组越界
你看下你的classifier在函数plot_decision_regions(X, y, resolution=0.02)没有定义吧,肯定报错。
看看你的输入数据
回答楼主第二个问题
from matplotlib.colors import ListedColormap
def plot_decision_regions(X,y,classifier,resolution=0.02):
markers=('o','x','s','v')
colors=('red','blue','lightgreen','gray','cyan')
把老师写的marker元组改成markers就可以了。
# 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: 输入样本向量 :param y: 对应样本分类 X:shape[n_samples, n_features] X:[[1,2,3],[4,5,6]] n_samples :2 n_features:3 y:[1,-1] """ """ 初始化向量为0 加一是因为步调函数阈值 """ 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) self.errors_.append(errors) 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 import pandas as pd file = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' df = pd.read_csv(file,header=None) import matplotlib.pyplot as plt y = df.loc[0:100,4].values y=np.where(y=='Iris-setosa',-1,1) #根据整数位置选取单列或单行数据 X = df.loc[0:100,[0,2]].values plt.scatter(X[:50,0],X[:50,1],color='red',marker='o',label="setosa") plt.scatter(X[50:100,0],X[50:100,1],color='blue',marker='x',label="versicolor") plt.xlabel('huabanchangdu') plt.ylabel('huajingchangdu') plt.legend(loc='upper left') ppn =Perceptron(eta=0.1,n_iter=10) ppn.fit(X,y) from matplotlib.colors import ListedColormap def plot_decision_region(X,y,classifier,resolution=0.02): markers=('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() 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) print (xx1.ravel()) print(xx2.ravel()) print Z Z=Z.reshape(xx1.shape) 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=markers[idx],label=cl) plot_decision_region(X,y,ppn,resolution=0.02) plt.xlabel('huajingchang') plt.ylabel('huabanchang') plt.legend(loc='upper left') plt.show()
C1代表数据的类别,即+1或者-1。
x的含义是导入数据X中标号为c1的数据的第一列
y的含义是导入数据X中标号为c1的数据的第二列
在上一节的开头能看到用csv文件的数据进行训练的代码的
我的python3.6,没问题的。
是不是没有写predict这个函数?或者函数名写错了?
ppn训练怎么做?
把net_input predict函数拿到fit函数外部 与fit函数平级 检查下自己的函数名以及 __init__函数
你可以试试把y的数值减小一个
y=df.loc[0:99,4].values
不用导入,只是函数里的一个可变参数