Python 机器学习核心入门与实战进阶 Day 4 - 支持向量机(SVM)原理与分类实战

发布于:2025-07-10 ⋅ 阅读:(18) ⋅ 点赞:(0)

✅ 今日目标

  • 理解支持向量机(SVM)分类器的基本原理
  • 掌握核函数的作用(线性、RBF 等)
  • 使用 sklearn.svm.SVC 实现 SVM 分类任务
  • 可视化超平面与边界
  • 比较不同核函数下的分类表现

📘 一、SVM 核心概念

概念 解释
支持向量 离分类边界最近的点
间隔最大化 SVM 寻找最大间隔的超平面
核函数 用于处理非线性分类任务,将数据映射到高维空间
常见核函数 linear、poly、rbf(高斯径向基)、sigmoid

🧪 二、基本用法演示

from sklearn.svm import SVC

model = SVC(kernel='rbf', C=1.0, gamma='scale')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
参数 含义
kernel 核函数类型
C 正则项系数,控制间隔与误差的权衡
gamma 核函数系数,控制模型复杂度

🧠 三、训练与可视化思路

  1. 构造二维特征数据(成绩 + 性别)
  2. 使用 SVC 分别训练 linear 和 rbf 模型
  3. 可视化不同核函数下的决策边界(使用 contourf)
  4. 输出分类准确率与报告

📈 四、模型调参建议

方法 工具
网格搜索 GridSearchCV
交叉验证 cross_val_score
可视化比较 画出不同模型边界

🧾 今日总结

收获 技能
支持向量的思想 核函数映射
分类建模能力 sklearn.svm.SVC() 使用
参数调优意识 gamma 和 C 的权衡

💻 练习脚本

# SVM 实战演示:学生是否及格分类任务

import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

plt.rcParams['font.family'] = 'Arial Unicode MS'  # Mac 用户可用
plt.rcParams['axes.unicode_minus'] = False
# 1. 构造数据(成绩 + 性别)
np.random.seed(42)
size = 100
scores = np.random.randint(40, 100, size)
genders = np.random.choice([0, 1], size=size)
labels = (scores >= 60).astype(int)

X = np.column_stack(((scores - scores.mean()) / scores.std(), genders))
y = labels

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 2. 训练两个 SVM 模型
models = {
    'Linear SVM': SVC(kernel='linear'),
    'RBF SVM': SVC(kernel='rbf')
}

# 3. 画图准备
def plot_decision_boundary(model, X, y, title):
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300),
                         np.linspace(y_min, y_max, 300))
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)

    plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.coolwarm)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm, edgecolors='k')
    plt.xlabel("标准化成绩")
    plt.ylabel("性别(0=女,1=男)")
    plt.title(title)
    plt.tight_layout()
    plt.show()

# 4. 训练 & 可视化每个模型
for name, model in models.items():
    model.fit(X_train, y_train)
    y_pred = model.predict(X_test)
    print(f"\\n=== {name} ===")
    print("准确率:", accuracy_score(y_test, y_pred))
    print(classification_report(y_test, y_pred))
    plot_decision_boundary(model, X, y, title=name + " 分类边界")

运行输出:
在这里插入图片描述

=== Linear SVM ===
准确率: 1.0
              precision    recall  f1-score   support

           0       1.00      1.00      1.00         7
           1       1.00      1.00      1.00        13

    accuracy                           1.00        20
   macro avg       1.00      1.00      1.00        20
weighted avg       1.00      1.00      1.00        20

网站公告

今日签到

点亮在社区的每一天
去签到