Copyright © 2019 Sebastian Raschka
https://github.com/rasbt/python-machine-learning-book-3rd-edition
《Python机器学习 第三版》第二章训练简单的机器学习分类算法
文章目录
人工神经元 - 机器学习的早期历史
人工神经元的定义
我们把人工神经元的逻辑放在二元分类的场景,将这两个类分别命名为1(正类)和-1(负类)然后定义决策函数
ϕ
(
z
)
\phi(z)
ϕ(z)。给出以下定义:
z
=
w
0
x
0
+
w
1
x
1
+
⋯
+
w
m
x
m
=
w
T
x
z = w_0x_0+w_1x_1+\cdots+w_mx_m = \boldsymbol{w^Tx}
z=w0x0+w1x1+⋯+wmxm=wTx
其中,权重零定义为
w
0
=
−
θ
,
x
0
=
1
w_0=-\theta, x_0=1
w0=−θ,x0=1,且在机器学习文献中,我们通常把负的阈值或权重
w
0
=
−
θ
w_0=-\theta
w0=−θ称为偏置
ϕ ( z ) = { 1 如果 z > = 0 − 1 否则 \phi(z)=\left\{ \begin{aligned} 1 & 如果z>=0 \\ -1 & 否则 \ \end{aligned} \right. ϕ(z)={1−1如果z>=0否则
感知器的学习规则
罗森布拉特的初始感知器规则,总结为以下几个步骤:
1)把权重初始化为0或者小的随机数
2)分别对每个训练样本
x
(
i
)
x^{(i)}
x(i)
a.计算输出值
y
^
\hat{y}
y^
b.更新权重
更准确的表达式为:
w
j
:
=
w
j
+
Δ
w
j
w_j :=w_j+\Delta w_j
wj:=wj+Δwj
其中,
Δ
w
j
\Delta w_j
Δwj是用来更新
w
j
w_j
wj的值,计算该值的方式如下:
$ \Delta w_j = \eta (y^{(i)} - \hat{y}{i})x_j{(i)}$
其中
η
\eta
η为学习速率
注意:只有两个类线性可分且学习速率足够小时,感知器的收敛性才能得到保证。如果不能用线性决策边界分离两个类,可以为训练数据集设置最大通过次数(迭代次数)及容忍误分类的阈值,否则分类感知器将会永不停止的更新权重。线性不可分示例如图2-3,感知器规则图示如图2-4。
图2-3
图2-4
用Python实现感知器学习算法
面向对象的感知器API
import numpy as np
class Perceptron(object):
"""Perceptron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
random_state : int
Random number generator seed for random weight
initialization.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications (updates) in each epoch.
"""
#初始化新的Perceptron对象
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta #学习速率
self.n_iter = n_iter #学习次数(遍历训练集的次数)
self.random_state = random_state
def fit(self, X, y):
"""Fit training data.
Parameters
----------
X : {array-like}, shape = [n_examples, n_features]
Training vectors, where n_examples is the number of examples and
n_features is the number of features.
y : array-like, shape = [n_examples]
Target values.
Returns
-------
self : object
"""
rgen = np.random.RandomState(self.random_state)
#我们在属性后面添加下划线,如self.w_;
#初始化权重:通过调用rgen.normal产生标准差为0.01的正太分布,rgen是Numpy的随机数生成器,随机种子由用户指定,保证在需要时可以重现结果
self.w_ = rgen.normal(loc=0.0, scale=0.01, size=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.predict(xi)输出都是整数,0,-1,1
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)
在鸢尾花数据集上训练感知器模型
加载鸢尾花数据集
import os
import pandas as pd
s = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
print('URL:', s)
df = pd.read_csv(s,
header=None,
encoding='utf-8')
df.tail()
URL: https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
0 | 1 | 2 | 3 | 4 | |
---|---|---|---|---|---|
145 | 6.7 | 3.0 | 5.2 | 2.3 | Iris-virginica |
146 | 6.3 | 2.5 | 5.0 | 1.9 | Iris-virginica |
147 | 6.5 | 3.0 | 5.2 | 2.0 | Iris-virginica |
148 | 6.2 | 3.4 | 5.4 | 2.3 | Iris-virginica |
149 | 5.9 | 3.0 | 5.1 | 1.8 | Iris-virginica |
绘制数据分布
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# select setosa and versicolor
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)
# extract sepal length and petal length
X = df.iloc[0:100, [0, 2]].values
# plot data
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('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')
# plt.savefig('images/02_06.png', dpi=300)
plt.show()
训练感知器模型
ppn = Perceptron(eta=0.1, n_iter=1)
ppn.fit(X, y)
plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of updates')
# plt.savefig('images/02_07.png', dpi=300)
plt.show()
画决策边界的函数
from matplotlib.colors import ListedColormap
def plot_decision_regions(X, y, classifier, resolution=0.02):
# setup marker generator and color map
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
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.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
# plot class examples
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.savefig('images/02_08.png', dpi=300)
plt.show()