数学建模(4)——支持向量机算法

一、代码示例

python 复制代码
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix

# 生成示例数据
# 这里我们使用sklearn自带的鸢尾花数据集
iris = datasets.load_iris()
X= iris.data[:, :2]  # 我们只使用前两个特征
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
#
# 标准化特征值
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 定义SVM分类器
svc = SVC(kernel='linear', random_state=42)
#核函数有:kernel='linear'  和 kernel='poly' 和 kernel='rbf' 和 kernel='sigmoid'
#SVC(kernel='poly', degree=3),degree控制多项式的阶数
#SVC(kernel='rbf', gamma=0.1) ,gamma控制高斯函数的宽度
# # 训练模型
svc.fit(X_train, y_train)
#
# # 进行预测
y_pred = svc.predict(X_test)
#
# # 评估模型
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))
#
# # 可视化决策边界
def plot_decision_boundary(X, y, model):
    h = .02  # 步长
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm, edgecolors='k')
    plt.xlabel('Feature 1')
    plt.ylabel('Feature 2')
    plt.title('SVM Decision Boundary')
    plt.show()

plot_decision_boundary(X_test, y_test, svc)

二、算法简介

支持向量机(Support Vector Machine, SVM)是一种监督学习算法,用于分类回归任务。

SVM 的基本思想是找到一个最优的超平面,使得超平面两侧的样本点距离最大化,从而实现良好的分类效果。

支持向量机的基本概念

  1. 超平面(Hyperplane):在特征空间中将不同类别分开的决策边界。对于二维数据,超平面是一条直线;对于三维数据,超平面是一个平面;对于更高维数据,超平面是一个高维空间中的子空间。

  2. 支持向量(Support Vectors):离超平面最近的样本点。这些点对确定超平面的位置和方向起到关键作用。

  3. 间隔(Margin):支持向量到超平面的距离。SVM 的目标是最大化间隔,以提高模型的泛化能力

相关推荐
白狐_79819 分钟前
408数据结构第5章:树与二叉树②——遍历、线索树、森林与哈夫曼
数据结构·算法·深度优先
致Great3 小时前
科研人的 AI,不该只回答问题:我用字节TraeWork 跑了一遍真实研究任务
算法
纵有疾風起4 小时前
线性表的定义与基本操作 — 从逻辑结构到 ADT 接口
数据结构·算法·408·线性表·adt
测试_AI_一辰4 小时前
AI Agent 评测最隐蔽的坑-记忆
人工智能·算法·ai·自动化·ai编程
lucas_AI4 小时前
给YOLO检测器插 LoRA,'插对地方'比'插什么'更要命
人工智能·算法
LuminousCPP5 小时前
数据结构-时间与复杂度|时间/空间复杂度 + 两道力扣练习 + 二分查找复盘
c语言·数据结构·经验分享·算法·leetcode
Nil2085 小时前
leetcode 三数之和
数据结构·算法·leetcode
小小龙学IT5 小时前
C++ std::vector 底层实现深度解析:内存布局、扩容策略、移动语义与迭代器失效
开发语言·c++·算法
noipp5 小时前
推荐题目:洛谷 P16689 出征
java·开发语言·数据结构·c++·算法·洛谷·luogu
eBest数字化转型方案6 小时前
从工程视角拆解冰柜资产管理:拍照识别 pipeline、纯净度算法与 IoT 选型踩坑
人工智能·物联网·算法