统计学习方法笔记 | Python实现 | Chapter2 感知机学习方法

第2章 感知机学习方法

参考:https://github.com/fengdu78/lihang-code

参考代码清晰易懂,本文只是将参考代码中的ipynb改写为python。


本章概要

1.感知机是根据输入实例的特征向量 x x x对其进行二类分类的线性分类模型:

f ( x ) = sign ⁡ ( w ⋅ x + b ) f(x)=\operatorname{sign}(w \cdot x+b) f(x)=sign(wx+b)

感知机模型对应于输入空间(特征空间)中的分离超平面 w ⋅ x + b = 0 w \cdot x+b=0 wx+b=0

2.感知机学习的策略是极小化损失函数:

min ⁡ w , b L ( w , b ) = − ∑ x i ∈ M y i ( w ⋅ x i + b ) \min _{w, b} L(w, b)=-\sum_{x_{i} \in M} y_{i}\left(w \cdot x_{i}+b\right) w,bminL(w,b)=xiMyi(wxi+b)

损失函数对应于误分类点到分离超平面的总距离。

3.感知机学习算法是基于随机梯度下降法的对损失函数的最优化算法,有原始形式和对偶形式。算法简单且易于实现。原始形式中,首先任意选取一个超平面,然后用梯度下降法不断极小化目标函数。在这个过程中一次随机选取一个误分类点使其梯度下降。

4.当训练数据集线性可分时,感知机学习算法是收敛的。感知机算法在训练数据集上的误分类次数 k k k满足不等式:

k ⩽ ( R γ ) 2 k \leqslant\left(\frac{R}{\gamma}\right)^{2} k(γR)2

当训练数据集线性可分时,感知机学习算法存在无穷多个解,其解由于不同的初值或不同的迭代顺序而可能有所不同。

二分类模型

f ( x ) = s i g n ( w ⋅ x + b ) f(x) = sign(w\cdot x + b) f(x)=sign(wx+b)

sign ⁡ ( x ) = { + 1 , x ⩾ 0 − 1 , x < 0 \operatorname{sign}(x)=\left\{\begin{array}{ll}{+1,} & {x \geqslant 0} \\ {-1,} & {x<0}\end{array}\right. sign(x)={+1,1,x0x<0

给定训练集:

T = { ( x 1 , y 1 ) , ( x 2 , y 2 ) , ⋯   , ( x N , y N ) } T=\left\{\left(x_{1}, y_{1}\right),\left(x_{2}, y_{2}\right), \cdots,\left(x_{N}, y_{N}\right)\right\} T={(x1,y1),(x2,y2),,(xN,yN)}

定义感知机的损失函数

L ( w , b ) = − ∑ x i ∈ M y i ( w ⋅ x i + b ) L(w, b)=-\sum_{x_{i} \in M} y_{i}\left(w \cdot x_{i}+b\right) L(w,b)=xiMyi(wxi+b)


算法

随机梯度下降法 Stochastic Gradient Descent (SGD)

随机抽取一个误分类点使其梯度下降。

w = w + η y i x i w = w + \eta y_{i}x_{i} w=w+ηyixi

b = b + η y i b = b + \eta y_{i} b=b+ηyi

当实例点被误分类,即位于分离超平面的错误侧,则调整 w w w, b b b的值,使分离超平面向该误分类点的一侧移动,直至误分类点被正确分类

拿出iris数据集中两个分类的数据和[sepal length,sepal width]作为特征

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
# print(df.keys())
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']  # 重命名feature_names
# print(df.label.value_counts())
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

所选取数据满足线性可分
显然其满足线性可分,将其作为训练感知机的数据集。

# 制造数据集
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])

Perceptron

# 数据线性可分,二分类数据
# 此处为一元一次线性方程
class Model:
    def __init__(self):
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        self.b = 0
        self.l_rate = 0.1

    def sign(self, x, w, b):
        y = np.dot(w, x) + b
        return y

    # 随机梯度下降法
    def fit(self, X_train, y_train):
        is_wrong = True
        while 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
            if wrong_count == 0:
                is_wrong = False
        return 'Perceptron Model!'

    def score(self):
        pass
if __name__ == '__main__':
    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:, 0], data[50:, 1], 'bo', color='orange', label='1')
    plt.xlabel('sepal length')
    plt.ylabel('sepal width')
    plt.legend()
    plt.show()

perceptron

scikit-learn实例

import sklearn
from sklearn.linear_model import Perceptron
# definite perceptron
clf = Perceptron(fit_intercept=True, max_iter=1000, shuffle=True)
# train
clf.fit(X, y)
# Weights assigned to the features.
print(clf.coef_)
# 截距 Constants in decision function.
print(clf.intercept_)

# 画布大小
plt.figure(figsize=(10, 10))
# 中文标题
# 设置字体为SimHei显示中文
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:, 0], data[50:, 1], c='orange', label='Iris-versicolor')  # 杂色鸢尾
# 分离超平面
x_points = np.arange(4, 8)
y_ = -(clf.coef_[0][0] * x_points + clf.intercept_) / clf.coef_[0][1]
plt.plot(x_points, y_)
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()  # 显示图例
plt.show()

sklearn_perceptron
注意 !

在上图中,有一个位于左下角的蓝点没有被正确分类,这是因为 SKlearn 的 Perceptron 实例中有一个tol参数。

tol 参数规定了如果本次迭代的损失和上次迭代的损失之差小于一个特定值时,停止迭代。所以我们需要设置 tol=None 使之可以继续迭代:

clf = Perceptron(fit_intercept=True, max_iter=1000, tol=None, shuffle=True)

pol=None
现在可以看到,所有的两种鸢尾花都被正确分类了。

完整代码

# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import sklearn
from sklearn.linear_model import Perceptron

# load data
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
# print(df.keys())
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']  # 重命名feature_names
# print(df.label.value_counts())
plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()
# 制造数据集
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])


# # Perceptron
# 数据线性可分,二分类数据
# 此处为一元一次线性方程
class Model:
    def __init__(self):
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        self.b = 0
        self.l_rate = 0.1

    def sign(self, x, w, b):
        y = np.dot(w, x) + b
        return y

    # 随机梯度下降法
    def fit(self, X_train, y_train):
        is_wrong = True
        while 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
            if wrong_count == 0:
                is_wrong = False
        return 'Perceptron Model!'

    def score(self):
        pass


if __name__ == '__main__':
    # # 自定义Perceptron Model
    # 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:, 0], data[50:, 1], 'bo', color='orange', label='1')
    # plt.xlabel('sepal length')
    # plt.ylabel('sepal width')
    # plt.legend()
    # plt.show()

    # # scikit-learn实例
    # definite perceptron
    clf = Perceptron(fit_intercept=True, max_iter=1000, tol=None, shuffle=True)
    # train
    clf.fit(X, y)
    # Weights assigned to the features.
    print(clf.coef_)
    # 截距 Constants in decision function.
    print(clf.intercept_)

    # 画布大小
    plt.figure(figsize=(10, 10))
    # 中文标题
    # 设置字体为SimHei显示中文
    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:, 0], data[50:, 1], c='orange', label='Iris-versicolor')  # 杂色鸢尾
    # 画感知机的线
    x_points = np.arange(4, 8)
    y_ = -(clf.coef_[0][0] * x_points + clf.intercept_) / clf.coef_[0][1]
    plt.plot(x_points, y_)
    plt.xlabel('sepal length')
    plt.ylabel('sepal width')
    plt.legend()  # 显示图例
    plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值