用 Python 可視化二維數據集的決策邊界


1、用 Python 實現 Rosenblatt 感知器算法

import numpy as np

class Perceptron():
    """感知機分類器
    
    參數
    ==========
    eta: 學習速率,區間 [0.0, 1.0] 上的浮點數
    n_iter: 迭代次數
    
    屬性
    ==========
    w_: 權重,1維數組
    errors_: 以列表形式存儲每一次迭代過程中分類錯誤的樣本數
    """
    
    def __init__(self, eta=0.01, n_iter=10): # 設置默認參數
        self.eta= eta
        self.n_iter = n_iter
    
    def fit(self, X, y):
        """學習訓練數據
        
        參數
        ==========
        X:訓練集的特征數據
        y: 訓練集的類標號數據        
        """
        self.w_ = np.zeros(1 + X.shape[1]) # 初始化權重
        self.errors_ = []
    
        for _ in range(self.n_iter):
            errors = 0
            for xi, yi in zip(X, y):
                delta = self.eta * (yi - self.predict(xi))
                self.w_[0] += delta
                self.w_[1:] += delta * xi
                errors += int(delta != 0.0)
            self.errors_.append(errors)
        return self
    
    def net_input(self, X):
        """計算凈輸入"""
        z = np.dot(X, self.w_[1:]) + self.w_[0]
        return z
    
    def predict(self, X):
        """用 sign 函數預測類標號"""
        yHat = np.where(self.net_input(X) > 0.0, 1, -1)
        return yHat
View Code

2、抽取 iris 中的數據訓練一個感知器模型

import numpy as np, pandas as pd
df = pd.read_csv('D:\\pySpace\\iris.data', header=None)
y = df.iloc[:100, 4].values
y = np.where( y == 'Iris-setosa', -1, 1) 
X = df.iloc[:100, [0, 2]].values

ppn = Perceptron(eta=0.1, n_iter=10)
ppn.fit(X, y)
View Code

 

3、編寫一個可視化決策區域的函數

import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

def plotDecisionRegions(X, y, classifier, resolution=0.02):
    
    # 定義顏色和標記符號,通過顏色列圖表生成顏色示例圖
    marker = ('o', 's', 'v', 'x', '^')
    colors = ('lightgreen', 'red', 'cyan', 'blue', 'gray')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # 可視化決策邊界
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())
    
    # 
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl,  0], y=X[y == cl, 1], alpha=0.8,
                    c=cmap(idx), marker=marker[idx], label=cl)

4、繪制決策區域

import matplotlib.pyplot as plt

%matplotlib inline
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(13, 9))
plotDecisionRegions(X, y, classifier=ppn)
plt.xlabel('萼片長度(cm)', fontsize=17)
plt.ylabel('花瓣長度(cm)', fontsize=17)
plt.yticks(fontproperties='Times New Roman', size=15, alpha=0.6)
plt.xticks(fontproperties='Times New Roman', size=15, alpha=0.6)
plt.legend(loc=2)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM