SVM Hyperparameter Tuning - Using GridSearchCV to Tune a SVC Model
Python
In this code example we tune a support vector machine classification model using Grid Search CV. We tune the C and kernel parameters using the the default 5 fold cross validation strategy and set accuracy as the scoring metric.
1| from sklearn.svm import SVC 2| from sklearn.metrics import classification_report 3| from sklearn.model_selection import GridSearchCV 4| 5| # declare parameter ranges to try 6| params = {'C':[1, 2, 3], 7| 'kernel':['linear', 'poly', 'rbf']} 8| 9| # initialise estimator 10| svm_classifier = SVC(class_weight='balanced') 11| 12| # initialise grid search model 13| model = GridSearchCV(estimator=svm_classifier, 14| param_grid=params, 15| scoring='accuracy', 16| n_jobs=-1) 17| 18| model.fit(X_train, y_train) 19| 20| y_pred = model.predict(X_test) 21| 22| print(model.best_params_) 23| print(classification_report(y_test, y_pred))
149
132
127
119