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

相关推荐
仟濹31 分钟前
【前缀和与差分 二分搜索 C/C++】洛谷 P1083 借教室
c语言·c++·算法
xinxiangwangzhi_1 小时前
多视图几何--从线性变换到射影变换--2线性变换
人工智能·算法·计算机视觉
AI技术控1 小时前
计算机视觉算法实战——昆虫识别检测(主页有源码)
人工智能·算法·计算机视觉
西猫雷婶2 小时前
python学智能算法(七)|KNN邻近算法
算法
用户9080321969252 小时前
OpenCV三大经典项目实战 掌握计算机视觉核心技能-|果fx
算法
Vitalia2 小时前
⭐算法OJ⭐经典题目分类索引(持续更新)
算法
Alchemist012 小时前
算法笔记
算法
请来次降维打击!!!3 小时前
算法优选系列(1.双指针_下)
c++·算法
汤姆和佩琦3 小时前
LLMs基础学习(一)概念、模型分类、主流开源框架介绍以及模型的预训练任务
人工智能·学习·算法·分类·数据挖掘