下载鸢尾花数据集,分别使用Hard Margin SVM和Soft Margin SVM来进行分类, 要求总结出参数C在SVM中的作用并能够绘制出决策边界。

目录

代码:

运行结果:


代码:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 导入鸢尾花数据集
iris = datasets.load_iris()
X = iris.data[:, :2]  # 为了方便可视化,我们只使用前两个特征
y = iris.target

# 数据预处理
scaler = StandardScaler()
X = scaler.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义绘制决策边界的函数
def plot_decision_boundary(model, X, y):
    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')

# 使用Hard Margin SVM进行分类
hard_svm = SVC(kernel='linear', C=1e6)  # C设置为一个非常大的数,表示Hard Margin
hard_svm.fit(X_train, y_train)

# 绘制Hard Margin SVM的决策边界
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plot_decision_boundary(hard_svm, X_train, y_train)
plt.title('Hard Margin SVM')

# 使用Soft Margin SVM进行分类
soft_svm = SVC(kernel='linear', C=0.1)  # C设置为一个较小的数,表示Soft Margin
soft_svm.fit(X_train, y_train)

# 绘制Soft Margin SVM的决策边界
plt.subplot(1, 2, 2)
plot_decision_boundary(soft_svm, X_train, y_train)
plt.title('Soft Margin SVM')

plt.show()

运行结果:

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值