用 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