目录
感知机
感知机是一种二分类的线性模型
几何意义上是一个分离输入空间的超平面:
s
i
g
n
(
w
+
b
=
0
)
sign(w+b=0)
sign(w+b=0)
感知机的损失函数为:
min
w
,
b
L
(
w
,
b
)
=
−
∑
x
i
∈
M
y
i
(
s
i
g
n
(
w
⋅
x
i
+
b
)
)
\min _{w, b} L(w, b)=-\sum_{x_{i} \in M} y_{i} (sign\left (w \cdot x_{i}+b\right))
w,bminL(w,b)=−xi∈M∑yi(sign(w⋅xi+b))
如果分类错误
y i ( s i g n ( w ⋅ x i + b ) ) = − 1 y_{i}(sign\left(w \cdot x_{i}+b\right))=-1 yi(sign(w⋅xi+b))=−1
所以前面加一个“-“,将其变为正数
几何意义上是误分类点对超平面的距离
−
1
∥
w
∥
∑
x
i
∈
M
y
i
(
w
⋅
x
i
+
b
)
-\frac{1}{\|w\|} \sum_{x_{i} \in M} y_{i}\left(w \cdot x_{i}+b\right)
−∥w∥1xi∈M∑yi(w⋅xi+b)
y i y_{i} yi不影响误分类点到超平面的距离值而且加上之后表示误分类点
去掉 − 1 ∥ w ∥ -\frac{1}{\|w\|} −∥w∥1后即为损失函数
因为最后的结果一定是很好的分离的变量,没有误分类点,损失函数为0,所以 − 1 ∥ w ∥ -\frac{1}{\|w\|} −∥w∥1不影响最后的结果,所以可以去掉
随机梯度下降法求解损失函数:
∇
w
L
(
w
,
b
)
=
−
∑
x
e
,
M
y
i
x
i
\nabla_{w} L(w, b)=-\sum_{x_{e}, M} y_{i} x_{i}
∇wL(w,b)=−xe,M∑yixi
∇
b
L
(
w
,
b
)
=
−
∑
x
i
∈
M
y
i
\nabla_{b} L(w, b)=-\sum_{x_{i} \in M} y_{i}
∇bL(w,b)=−xi∈M∑yi
代码实现:
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
%matplotlib inline
# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = [
'sepal length', 'sepal width', 'petal length', 'petal width', 'label'
]
data = np.array(df.iloc[:100, [0, 1, -1]])
X, y = data[:,:-1], data[:,-1]
y = np.array([1 if i == 1 else -1 for i in y])
# 数据线性可分,二分类数据
# 此处为一元一次线性方程
class Model:
def __init__(self):
self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
self.b = 0
self.l_rate = 0.1
# self.data = data
def sign(self, x, w, b):
y = np.dot(x, w) + b
return y
# 随机梯度下降法
def fit(self, X_train, y_train):
is_wrong = False
while not is_wrong:
wrong_count = 0
for d in range(len(X_train)):
X = X_train[d]
y = y_train[d]
if y * self.sign(X, self.w, self.b) <= 0:
self.w = self.w + self.l_rate * np.dot(y, X)
self.b = self.b + self.l_rate * y
wrong_count += 1
print(self.w)
print(self.b)
if wrong_count == 0:
is_wrong = True
return 'Perceptron Model!'
def score(self):
pass
perceptron = Model()
perceptron.fit(X, y)
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.plot(x_points, y_)
plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
import sklearn
from sklearn.linear_model import Perceptron
clf = Perceptron(fit_intercept=True,
max_iter=1000,
shuffle=True)
clf.fit(X, y)
# 画布大小
plt.figure(figsize=(10,10))
# 中文标题
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title('鸢尾花线性数据示例')
plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Iris-setosa',)
plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')
# 画感知机的线
x_ponits = np.arange(4, 8)
y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
plt.plot(x_ponits, y_)
# 其他部分
plt.legend() # 显示图例
plt.grid(False) # 不显示网格
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
在上图中,有一个位于左下角的蓝点没有被正确分类,这是因为 SKlearn 的 Perceptron 实例中有一个tol参数。
tol 参数规定了如果本次迭代的损失和上次迭代的损失之差小于一个特定值时,停止迭代。所以我们需要设置 tol=None 使之可以继续迭代:
clf = Perceptron(fit_intercept=True,
max_iter=1000,
tol=None,
shuffle=True)
clf.fit(X, y)
# 画布大小
plt.figure(figsize=(10,10))
# 中文标题
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title('鸢尾花线性数据示例')
plt.scatter(data[:50, 0], data[:50, 1], c='b', label='Iris-setosa',)
plt.scatter(data[50:100, 0], data[50:100, 1], c='orange', label='Iris-versicolor')
# 画感知机的线
x_ponits = np.arange(4, 8)
y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
plt.plot(x_ponits, y_)
# 其他部分
plt.legend() # 显示图例
plt.grid(False) # 不显示网格
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
np.ones(5)
array([1., 1., 1., 1., 1.])