自学内容网 自学内容网

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

 一、代码示例

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

 

 


原文地址:https://blog.csdn.net/m0_74807013/article/details/140579563

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!