1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 读取数据集
df = pd.read_excel('~/数模/2020C/附件/指标选择.xlsx', sheet_name='第一题')
X = df.iloc[:, 1:6]
y = df.iloc[:, 0]
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=36)
# 创建SVM模型
svm_model = SVC()
'''
C: 这个参数控制SVM中的正则化强度,它指定了对错误分类的惩罚。较小的C值会导致更宽的间隔,但可能会产生更多的错误分类;而较大的C值会导致更窄的间隔,但错误分类较少。在示例中,使用的取值为[0.1, 1, 10]。
kernel:SVM使用核函数将输入数据转换为更高维的特征空间,从而更容易找到一个分离超平面。可以使用不同的核函数,例如'linear'(线性核函数)、'rbf'(径向基函数)、'poly'(多项式核函数)等。在示例中,使用的选项为['linear', 'rbf']。
gamma:这个参数定义了每个训练样本的影响力。它指定了核函数的系数,控制了样本点对决策边界的影响程度。较小的gamma值表示影响范围较大,较大的gamma值表示影响范围较小。选项有 ['scale', 'auto']。
'''
# 定义参数网格
param_grid = {
'C': [0.1, 1, 10], # 正则化参数
'kernel': ['linear', 'rbf'], # 核函数
'gamma': ['scale', 'auto'] # 核函数参数
}
# 创建GridSearchCV对象
grid_search = GridSearchCV(estimator=svm_model, param_grid=param_grid, cv=5)
# 在训练集上进行网格搜索
grid_search.fit(X_train, y_train)
# 输出最佳参数组合
print("最佳参数组合:", grid_search.best_params_)
# 使用最佳参数的模型进行预测
y_pred = grid_search.predict(X_test)
# 计算模型在测试集上的准确性
accuracy = accuracy_score(y_test, y_pred)
print("模型在测试集上的准确性:", accuracy)
|