python 实现 Peceptron Learning Algorithm ( 三) 感知机模型应用于Iris数据集

参考 《python machine learning》

代码读的很费劲,应该是没有功底的原因吧然后就挨个的百度不懂的函数,函数记录在了(一)中,

链接为 http://blog.csdn.net/Amy_mm/article/details/79625288

Iris数据集 以及源码 可以在github上下载~~

GIT:  https://github.com/xuman-Amy/Perceptron_python

代码及详细注释如下

# load iris dataset
import pandas as pd
df = pd.read_csv("G:\Machine Learning\python machine learning\python-machine-learning-book-2nd-edition-master\code\ch02\iris.data",header = None)
df.tail()
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# select setosa and versicolor
#iloc()提取某列 ----前100行的第四列,第四例为versicolor和setosa属性
y = df.iloc[0:100,4].values 
#进行分类   1 ( versicolor ) and -1 ( setosa )
y = np.where(y == 'Iris-setosa',-1, +1)  

# first feature column (sepal length) and the third feature column (petal length)  花瓣长度和花萼长度
X = df.iloc[0:100,[0,2]].values  

#plot data
#前50是setosa,属于类别 -1 
plt.scatter(X[:50,0],X[:50,1],color = 'red',marker = 'o',label = 'setosa') 
#后50行是versilor,属于类别 +1 
plt.scatter(X[50:100,0],X[50:100,1],color = 'blue',marker = 'x',label = 'versilor')


plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')

plt.legend(loc = 'upper left')
plt.show()


#train perceptron alogrithm
ppn = Perceptron(eta = 0.1 ,n_iter = 10)
#fit函数即继续数据拟合,也就是进行分类的迭代过程
ppn.fit(X,y)

plt.plot(range(1,len(ppn.errors_)+1),ppn.errors_,marker = 'o')

plt.xlabel('Epochs')
plt.ylabel('Number of updates')

from matplotlib.colors import ListedColormap

def plot_decision_regions(X, y, classifier, resolution=0.02):
    #具体函数 在博文(一)中有记录  博文地址http://blog.csdn.net/Amy_mm/article/details/79625288
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])
    
    # plot the decision surface 画分离超平面
    
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    
    #生成间隔为resolution的网格
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    #调用感知机分类函数进行预测
    #np.array([xx1.ravel(),xx2.ravel()]).T 为*行两列的矩阵,对应二维平面上xx1,xx2行程的网格点
    #对这些网格点进行分类为+1,-1,
    #画出等高线,+1类画一种颜色,-1另一种
    Z = classifier.predict(np.array([xx1.ravel(),xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    
    #contour()函数(一)中有记录
    plt.contourf(xx1,xx2,Z,alpha = 0.3,cmap = cmap)
    
    plt.xlim(xx1.min(),xx1.max())
    plt.ylim(xx2.min(),xx2.max())
    
    # plot class samples 画出样本点
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x = X[y == cl, 0], 
                    y = X[y == cl, 1],
                    alpha = 0.8, 
                    c = colors[idx], 
                    marker = markers[idx],  
                    label = cl,
                    edgecolor = 'black')
    
#画图
plot_decision_regions(X,y,classifier = ppn)
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc = 'upper left')
plt.show

 

 

 

 

 

 

 

你可能感兴趣的:(python,机器学习)