《統計學習方法》代碼全解析——第二部分 感知機

1.感知機是根據輸入實例的特徵向量 𝑥 x 對其進行二類分類的線性分類模型:

感知機模型對應於輸入空間(特徵空間)中的分離超平面 𝑤⋅𝑥+𝑏=0 

2.感知機學習的策略是極小化損失函數:

3.感知機學習算法是基於隨機梯度下降法的對損失函數的最優化算法,有原始形式和對偶形式。算法簡單且易於實現。原始形式中,首先任意選取一個超平面,然後用梯度下降法不斷極小化目標函數。在這個過程中一次隨機選取一個誤分類點使其梯度下降。
4.當訓練數據集線性可分時,感知機學習算法是收斂的。感知機算法在訓練數據集上的誤分類次數 𝑘  滿足不等式:

當訓練數據集線性可分時,感知機學習算法存在無窮多個解,其解由於不同的初值或不同的迭代順序而可能有所不同。

 

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' ] 
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()

 

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
        # 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!'

    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()

scikit-learn實例 

import sklearn
from sklearn.linear_model import Perceptron
clf = Perceptron(fit_intercept=True, 
                 max_iter=1000, 
                 shuffle=True)
clf.fit(X, y)
# Weights assigned to the features.
print(clf.coef_)

# 截距 Constants in decision function.
print(clf.intercept_)

# 畫布大小
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()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章