数学建模(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 的目标是最大化间隔,以提高模型的泛化能力

相关推荐
V搜xhliang02466 分钟前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化
汉克老师21 分钟前
GESP2025年3月认证C++五级( 第三部分编程题(2、原根判断))
c++·算法·模运算·gesp5级·gesp五级·原根·分解质因数
热心网友俣先生25 分钟前
2026年第二十三届五一数学建模竞赛C题各问题参考答案
数学建模
数据皮皮侠42 分钟前
上市公司创新韧性数据(2000-2024)|顶刊同款 EIR 指数
大数据·人工智能·算法·智慧城市·制造
WL_Aurora1 小时前
Python 算法基础篇之链表
python·算法·链表
科研前沿1 小时前
纯视觉无感解算 + 动态数字孪生:室内外无感定位技术全新升级
大数据·人工智能·算法·重构·空间计算
Wadli2 小时前
26.单调栈
算法
晨曦夜月2 小时前
进程的五大状态及特殊进程解析
linux·服务器·算法
吟安安安安2 小时前
适合短期冲刺的学习工作流(针对算法)
学习·算法
科研前沿2 小时前
什么是时空融合技术?
大数据·人工智能·数码相机·算法·重构·空间计算