更新、更全的《機器學習》的更新網站,更有python、go、數據結構與算法、爬蟲、人工智能教學等着你: https://www.cnblogs.com/nickchen121/p/11686958.html
感知機原始形式(鳶尾花分類)
一、導入模塊
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.font_manager import FontProperties
# jupyter顯示matplotlib生成的圖片
%matplotlib inline
# 中文字體設置
font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
二、自定義感知機模型
class Perceptron():
"""自定義感知機算法"""
def __init__(self, learning_rate=0.01, num_iter=50, random_state=1):
self.learning_rate = learning_rate
self.num_iter = num_iter
self.random_state = random_state
def fit(self, X, y):
"""初始化並更新權重"""
# 通過標准差為0.01的正態分布初始化權重
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1])
self.errors_ = []
# 循環遍歷更新權重直至算法收斂
for _ in range(self.num_iter):
errors = 0
for x_i, target in zip(X, y):
# 分類正確不更新,分類錯誤更新權重
update = self.learning_rate * (target - self.predict(x_i))
self.w_[1:] += update * x_i
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def predict_input(self, X):
"""計算預測值"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
"""得出sign(預測值)即分類結果"""
return np.where(self.predict_input(X) >= 0.0, 1, -1)
三、獲取數據
由於獲取的鳶尾花數據總共有3個類別,所以只提取前100個鳶尾花的數據得到正類(versicolor 雜色鳶尾)和負類(setosa 山尾),並分別用數字1和-1表示,並存入標記向量y,之后邏輯回歸會講如何對3個類別分類。同時由於三維以上圖像不方便展示,將只提取第三列(花瓣長度)和第三列(花瓣寬度)的特征放入特征矩陣X。
df = pd.read_csv(
'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
# 取出前100行的第五列即生成標記向量
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-versicolor', 1, -1)
# 取出前100行的第一列和第三列的特征即生成特征向量
X = df.iloc[0:100, [2, 3]].values
plt.scatter(X[:50, 0], X[:50, 1], color='r', s=50, marker='x', label='山鳶尾')
plt.scatter(X[50:100, 0], X[50:100, 1], color='b',
s=50, marker='o', label='雜色鳶尾')
plt.xlabel('花瓣長度(cm)', fontproperties=font)
plt.ylabel('花瓣寬度(cm)', fontproperties=font)
plt.legend(prop=font)
plt.show()
四、構造決策邊界
邊界函數即的之前提及的代價函數,通過決策邊界將鳶尾花數據正確的分為兩個類別。
def plot_decision_regions(X, y, classifier, resolution=0.02):
# 構造顏色映射關系
marker_list = ['o', 'x', 's']
color_list = ['r', 'b', 'g']
cmap = ListedColormap(color_list[:len(np.unique(y))])
# 構造網格采樣點並使用算法訓練陣列中每個元素
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 # 第0列的范圍
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 第1列的范圍
t1 = np.linspace(x1_min, x1_max, 666) # 橫軸采樣多少個點
t2 = np.linspace(x2_min, x2_max, 666) # 縱軸采樣多少個點
# t1 = np.arange(x1_min, x1_max, resolution)
# t2 = np.arange(x2_min, x2_max, resolution)
x1, x2 = np.meshgrid(t1, t2) # 生成網格采樣點
# y_hat = classifier.predict(np.array([x1.ravel(), x2.ravel()]).T) # 預測值
y_hat = classifier.predict(np.stack((x1.flat, x2.flat), axis=1)) # 預測值
y_hat = y_hat.reshape(x1.shape) # 使之與輸入的形狀相同
# 通過網格采樣點畫出等高線圖
plt.contourf(x1, x2, y_hat, alpha=0.2, cmap=cmap)
plt.xlim(x1.min(), x1.max())
plt.ylim(x2.min(), x2.max())
for ind, clas in enumerate(np.unique(y)):
plt.scatter(X[y == clas, 0], X[y == clas, 1], alpha=0.8, s=50,
c=color_list[ind], marker=marker_list[ind], label=clas)
五、訓練模型
可以看出模型在第6次迭代的時候就已經收斂了,即可以對數據正確分類。
perceptron = Perceptron(learning_rate=0.1, num_iter=10)
perceptron.fit(X, y)
plt.plot(range(1, len(perceptron.errors_) + 1), perceptron.errors_, marker='o')
plt.xlabel('迭代次數', fontproperties=font)
plt.ylabel('更新次數', fontproperties=font)
plt.show()
六、可視化
plot_decision_regions(X, y, classifier=perceptron)
plt.xlabel('花瓣長度(cm)', fontproperties=font)
plt.ylabel('花瓣寬度(cm)', fontproperties=font)
plt.legend(prop=font)
plt.show()