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

相关推荐
SHOJYS5 分钟前
思维难度较大 贪心优化背包 [USACO22DEC] Bribing Friends G
数据结构·算法·深度优先
啊董dong6 分钟前
课后作业-2025年12月07号作业
数据结构·c++·算法·深度优先·noi
椰萝Yerosius10 分钟前
MATLAB简介
开发语言·数学建模·matlab
无限进步_26 分钟前
C语言宏的魔法:探索offsetof与位交换的奇妙世界
c语言·开发语言·windows·后端·算法·visual studio
Lucky“经营分析”34 分钟前
经营分析师-《经营分析能力》
算法
狐5737 分钟前
2025-12-04-LeetCode刷题笔记-2211-统计道路上的碰撞次数
笔记·算法·leetcode
listhi5201 小时前
激光雷达点云拟合中的ICP(迭代最近点)算法
算法
持续学习的程序员+11 小时前
强化学习阶段性总结
人工智能·算法
爱装代码的小瓶子1 小时前
【cpp知识铺子】map与set的底层AVL树
开发语言·数据结构·c++·b树·算法·链表
IT·小灰灰1 小时前
腾讯HY2.0 Think推理模型深度解析:技术突破、应用场景与实践指南
开发语言·人工智能·python·深度学习·神经网络·算法·数据分析