scikit learn has a function called grid search. A nice feature that automatically optimizes the hyperparameters of the machine learning model. For example, for SVM, C, kernel, gamma, etc. From Scikit-learn User Guide, here is the reference this time.
--Classify handwritten digit (0-9) dataset digits by SVM -Optimize hyperparameters with cross-validation using GridSearchCV --Use f1 for the evaluation function of the model at the time of optimization.
Import handwritten digit digits.
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
digits = datasets.load_digits()
n_samples = len(digits.images) #Number of specimens 1797
X = digits.images.reshape((n_samples, -1)) #Convert from an 8x8 array to a 64-dimensional vector
y = digits.target #Correct label
train_test_split
splits the dataset into two, one for training and one for testing.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
print(X.shape)
>>> (1797, 64)
print(X_train.shape)
>>> (898, 64)
print(X_test.shape)
>>> (899, 64)
Next, define the parameters you want to optimize in a list. Added poly and sigmoid kernels in addition to the example ones.
tuned_parameters = [
{'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'kernel': ['rbf'], 'gamma': [0.001, 0.0001]},
{'C': [1, 10, 100, 1000], 'kernel': ['poly'], 'degree': [2, 3, 4], 'gamma': [0.001, 0.0001]},
{'C': [1, 10, 100, 1000], 'kernel': ['sigmoid'], 'gamma': [0.001, 0.0001]}
]
Optimize the parameters defined above using GridSearchCV
. There are four specified variables: the model to be used, the parameter set to be optimized, the number of cross-validations, and the evaluation value of the model. The evaluation value was f1
. You can also use precision
or recall
. For more information, click here (http://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter).
score = 'f1'
clf = GridSearchCV(
SVC(), #Identifyer
tuned_parameters, #Parameter set you want to optimize
cv=5, #Number of cross-validations
scoring='%s_weighted' % score ) #Specifying the evaluation function of the model
Perform optimizations using only training datasets. The parameter set etc. are displayed.
clf.fit(X_train, y_train)
>>> GridSearchCV(cv=5, error_score='raise',
>>> estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
>>> decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
>>> max_iter=-1, probability=False, random_state=None, shrinking=True,
>>> tol=0.001, verbose=False),
>>> fit_params={}, iid=True, n_jobs=1,
>>> param_grid=[{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}, {'kernel': ['rbf'], 'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001]}, {'kernel': ['poly'], 'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'degree': [2, 3, 4]}, {'kernel': ['sigmoid'], 'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001]}],
pre_dispatch='2*n_jobs', refit=True, scoring='f1_weighted',
verbose=0)
You can check the score in each trial with clf.grid_scores_
.
clf.grid_scores_
>>> [mean: 0.97311, std: 0.00741, params: {'kernel': 'linear', 'C': 1},
>>> mean: 0.97311, std: 0.00741, params: {'kernel': 'linear', 'C': 10},
>>> mean: 0.97311, std: 0.00741, params: {'kernel': 'linear', 'C': 100},
>>> ...
>>> mean: 0.96741, std: 0.00457, params: {'kernel': 'sigmoid', 'C': 1000, 'gamma': 0.0001}]
You can check the optimized parameters with clf.best_params_
.
clf.best_params_
{'C': 10, 'gamma': 0.001, 'kernel': 'rbf'}
The score of each trial is displayed in text, and the accuracy of the optimized parameters is displayed in a table.
print("# Tuning hyper-parameters for %s" % score)
print()
print("Best parameters set found on development set: %s" % clf.best_params_)
print()
#Display of trial results for each parameter
print("Grid scores on development set:")
print()
for params, mean_score, scores in clf.grid_scores_:
print("%0.3f (+/-%0.03f) for %r"
% (mean_score, scores.std() * 2, params))
print()
#Show classification accuracy in test dataset
print("The scores are computed on the full evaluation set.")
print()
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
It will be output like this.
# Tuning hyper-parameters for f1
Best parameters set found on development set: {'kernel': 'rbf', 'C': 10, 'gamma': 0.001}
Grid scores on development set:
0.973 (+/-0.015) for {'kernel': 'linear', 'C': 1}
0.973 (+/-0.015) for {'kernel': 'linear', 'C': 10}
0.973 (+/-0.015) for {'kernel': 'linear', 'C': 100}
[Omitted because it is long]
0.967 (+/-0.009) for {'kernel': 'sigmoid', 'C': 1000, 'gamma': 0.0001}
The scores are computed on the full evaluation set.
precision recall f1-score support
0 1.00 1.00 1.00 89
1 0.97 1.00 0.98 90
2 0.99 0.98 0.98 92
3 1.00 0.99 0.99 93
4 1.00 1.00 1.00 76
5 0.99 0.98 0.99 108
6 0.99 1.00 0.99 89
7 0.99 1.00 0.99 78
8 1.00 0.98 0.99 92
9 0.99 0.99 0.99 92
avg / total 0.99 0.99 0.99 899