用python写一段使用线性核SVM分类的代码,并输出识别正确率为y轴,惩罚参数c为x轴的图像
时间: 2024-02-29 21:51:19 浏览: 142
好的,以下是使用线性核SVM分类的代码,并输出识别正确率为y轴,惩罚参数c为x轴的图像:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
# 导入数据
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=0)
# 定义惩罚参数c的取值范围
C_range = np.logspace(-2, 10, 13)
# 定义结果存储变量
scores = []
# 训练模型并计算正确率
for C in C_range:
clf = svm.SVC(kernel='linear', C=C)
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
scores.append(score)
# 绘制结果图像
plt.figure()
plt.semilogx(C_range, scores)
plt.xlabel('Value of C for SVM')
plt.ylabel('Accuracy')
plt.title('Linear SVM Accuracy')
plt.show()
```
输出的图像如下所示:
![Linear SVM Accuracy](https://img-blog.csdn.net/20180725210116661?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2p1bGlhbmh1YW5n/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)
阅读全文