《统计学习方法》—— 2. 感知器(Python实现)

本文完整代码 github 地址:https://github.com/anlongstory/awsome-ML-DL-leaning/lihang-reading_notes ( 如果觉得不错,欢迎 Star ?)

本文主要是在阅读过程中对本书的一些概念摘录,包括一些个人的理解,主要是思想理解不涉及到复杂的公式推导。若有不准确的地方,欢迎留言指正交流

感知器

感知机(perceptron) 是而二分类的线性分类模型,输入为特征向量,输出为类别取,+1,-1二值。用函数式来表达就是下面的公式:

f(x) = sign (w*x + b)

 其中 w 称为权重(weight), b 叫做偏置(bias)。

对应理解就是在特征空间 Rn中的一个超平面,w 是超平面的法向量, b 是超平面的截距。

感知器学习策略

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

损失函数对应的是误分类点到分类超平面的总距离。其中 y i 只有 +1,或 -1,当 w\*x i + b > 0 时, y i = 1 ,反之 w\*x i + b < 0 时, y i = -1 。所以 -y i(w\*x i + b)> 0 时,w\*x i + b > 0 时, y i = -1,反之为正 1,可以表示误分类点到超平面的距离。
感知器学习算法

感知器学习算法是基于随机梯度下降法的对损失函数的最优化算法,有原始形式和对偶形式两种。

  • 原始形式

   学习过程:

w = w + ηyixi
b = b + ηyi

  • 对偶形式
    感知器模型为:
   学习过程:

αi = αi + η
b = b + ηyi

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

其中,R 是所有特征向量 x i 中的最大模,γ 为当前所有特征向量 x i 分别代入超平面方程中的最小值。

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

代码实现

感知器示例代码:

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

# 数据集准备
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
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])


# part 1 感知器模型
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
            if wrong_count == 0:
                is_wrong = True
        return '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]


# part 2 scikit-learn 实现
# clf = Perceptron(fit_intercept=False, max_iter=1000, shuffle=False)
# clf.fit(X, y)
#
# 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.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()
plt.show()

运行完 part 1 结果为:

也可以将part 1 感知器模型 部分注释,将 part 2 scikit-learn 实现 解注释,运行,运行完 part 2 结果为:

相关阅读:

《统计学习方法》—— 1. 统计学习方法概论(Python实现)
《统计学习方法》—— 3. K近邻法(Python实现)
《统计学习方法》—— 4. 朴素贝叶斯(Python实现)
《统计学习方法》—— 5. 决策树(Python实现)
《统计学习方法》—— 6. 逻辑斯特回归与最大熵模型(Python实现)
《统计学习方法》—— 7. 支持向量机(Python实现)
《统计学习方法》—— 8. 提升方法 (Python实现)
《统计学习方法》—— 9. EM 算法(Python实现)
《统计学习方法》——10. 隐马尔可夫模型(Python实现)
《统计学习方法》—— 11. 条件随机场

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
感知器是一种二分类的线性分类器,它的基本思想是利用输入信息的线性组合,对输入进行二分类。感知器实现可以使用Python语言来完成。 首先,需要定义感知器的类。在这个类中,需要定义感知器的初始化方法,训练方法和预测方法。初始化方法需要定义感知器的权重和偏置,训练方法需要根据训练数据来更新感知器的权重和偏置,预测方法需要根据输入数据和感知器的权重和偏置来判断输入数据是属于哪一类。 代码如下: ```python import numpy as np class Perceptron: def __init__(self, learning_rate=0.1, epochs=1000): self.learning_rate = learning_rate self.epochs = epochs self.weights = None self.bias = None def fit(self, X, y): n_samples, n_features = X.shape self.weights = np.zeros(n_features) self.bias = 0 y_ = np.where(y <= 0, -1, 1) for _ in range(self.epochs): for idx, x_i in enumerate(X): linear_output = np.dot(x_i, self.weights) + self.bias y_predicted = np.where(linear_output <= 0, -1, 1) update = self.learning_rate * (y_[idx] - y_predicted) self.weights += update * x_i self.bias += update def predict(self, X): linear_output = np.dot(X, self.weights) + self.bias y_predicted = np.where(linear_output <= 0, -1, 1) return y_predicted ``` 以上代码中,Perceptron类的初始化方法中包含学习率和迭代次数等参数。在训练方法中,首先将标签y的值转换为-1和1,然后根据迭代次数和输入数据更新感知器的权重和偏置。在预测方法中,通过感知器的权重和偏置进行线性组合,然后根据线性输出的值判断输入数据是属于哪一类。 下面是一个简单的例子,用于说明如何使用感知器进行分类: ```python X = np.array([[2, 3], [1, 1.5], [3, 4], [4, 4], [1.5, 2], [2.5, 3], [2, 2], [4.5, 5]]) y = np.array([1, -1, 1, 1, -1, 1, -1, 1]) perceptron = Perceptron() perceptron.fit(X, y) X_test = np.array([[1, 1], [3, 3.5], [2.5, 2]]) y_pred = perceptron.predict(X_test) print(y_pred) # Output: [-1 1 -1] ``` 以上代码中,我们使用了一组二维数据和标签,然后通过Perceptron类进行训练和预测,最终得到了数据的分类结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值