spam_filter

# ------------------------------
# 导入必要的库
# ------------------------------
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np

# ------------------------------
# 定义用于绘制分类决策边界的函数
# ------------------------------
def plot_decision_regions(X, y, classifier, resolution=0.02):
    markers = ('s', 'x', 'o', '^', 'v')  # 不同类别的标记样式
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')  # 不同类别的颜色
    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=markers[idx], label=f'Class {cl}')

 

Scroll to Top