《統計學習方法》第2章_感知機

  • 根據鳶尾花數據集繪製正例和反例的散點圖

"""基於numpy的一種工具,爲了解決數據分析任務而創建的
    高效操作大型數據集"""
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from sklearn.linear_model import Perceptron

"""sklearn自帶的數據集"""
"""鳶尾花數據集"""
iris = load_iris()
"""iris.data(獲取屬性數據),iris.feature_names(獲取列屬性值)"""
df = pd.DataFrame(iris.data, columns=iris.feature_names)
# print(df)
"""獲取類別數據,這裏注意的是已經經過處理,targe裏0、1、2分別代表三種類別"""
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', color='blue')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1', color='orange')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

  • 手動實現感知機算法

data = np.array(df.iloc[:100, [0, 1, -1]])
# print(data)
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

    def sign(self, X, w, b):
        """dot()返回的是兩個數組的點積"""
        Y = np.dot(X, w) + b
        return Y

    """隨機梯度下降法  """
    """實現書P29,算法2.1--感知機學習算法"""
    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)

"""4-7中生成10個等差數據"""
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
"""x軸數據爲x_points,y軸數據爲y_"""
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()

  • 從sklearn.linear_model中調用Perceptron以實現感知機問題

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

"""自定義感知機"""
clf = Perceptron(fit_intercept=False, n_iter=1000, shuffle=False)
"""使用訓練數據進行訓練"""
clf.fit(x, y)
"""得到訓練結果,權重矩陣"""
print(clf.coef_)
"""超平面的截距,此處輸出W爲:[0.]"""
print(clf.intercept_)

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

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