用python写一段最优化SVM惩罚参数c和核参数gamma,并输出识别正确率和混淆矩阵的代码
时间: 2024-02-28 19:55:51 浏览: 133
好的,以下是代码:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import GridSearchCV
# 加载数据
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义SVM模型
svm = SVC()
# 定义参数搜索范围
param_grid = {'C': [0.1, 1, 10, 100], 'gamma': [0.001, 0.01, 0.1, 1]}
# 使用网格搜索交叉验证选择最优参数
grid_search = GridSearchCV(svm, param_grid, cv=5)
grid_search.fit(X_train, y_train)
# 输出最优参数
print("最优惩罚参数C:", grid_search.best_params_['C'])
print("最优核参数gamma:", grid_search.best_params_['gamma'])
# 使用最优参数训练模型
svm_best = SVC(C=grid_search.best_params_['C'], gamma=grid_search.best_params_['gamma'])
svm_best.fit(X_train, y_train)
# 在测试集上进行预测并输出准确率和混淆矩阵
y_pred = svm_best.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)
confusion = confusion_matrix(y_test, y_pred)
print("混淆矩阵:\n", confusion)
```
该代码使用sklearn库中的SVC类实现SVM分类器,并使用GridSearchCV类进行参数搜索。运行代码后,输出最优惩罚参数C和最优核参数gamma,并在测试集上输出准确率和混淆矩阵。
阅读全文