本笔记来源于B站Up主: 有Li 的影像组学系列教学视频
本节(12)主要介绍: SVM参数优化(代码)
参数优化:
自动寻找最合适的γ和C组合。
原理:遍历所有给定的参数组合,对数据进行训练,找到最合适的参数组合。
函数:GridSearchCV
创建字典dict
存储结果
(书接上文:导入数据、清洗、特征筛选)
#SVM
X_train, X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3)
model_svm = svm.SVC(kernel = 'rbf',gamma = 'auto',probability = True).fit(X_train,y_train)
score_svm = model_svm.score(X_test,y_test)
print(score_svm)
#params opt: svm 参数优化
Cs = np.logspace(-1,3,10,base = 2)
gammas = np.logspace(-4,1,50,base = 2)
param_grid = dict(C = Cs, gamma = gammas)
grid = GridSearchCV(svm.SVC(kernel = 'rbf'),param_grid = param_grid, cv = 10).fit(X,y)
print(grid.best_params_)
C = grid.best_params_['C']
gamma = grid.best_params_['gamma']
#svm
X_train, X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3)
model_svm = svm.SVC(kernel = 'rbf',C = C, gamma = gamma,probability = True).fit(X_train,y_train)
score_svm = model_svm.score(X_test,y_test)
print(score_svm)