документация: http://scikit-learn.org/stable/modules/grid_search.html
In [1]:
from sklearn import cross_validation, datasets, grid_search, linear_model, metrics
import numpy as np
import pandas as pd
In [2]:
iris = datasets.load_iris()
In [3]:
train_data, test_data, train_labels, test_labels = cross_validation.train_test_split(iris.data, iris.target,
test_size = 0.3,random_state = 0)
In [4]:
classifier = linear_model.SGDClassifier(random_state = 0)
In [5]:
classifier.get_params().keys()
Out[5]:
In [6]:
parameters_grid = {
'loss' : ['hinge', 'log', 'squared_hinge', 'squared_loss'],
'penalty' : ['l1', 'l2'],
'n_iter' : range(5,10),
'alpha' : np.linspace(0.0001, 0.001, num = 5),
}
In [7]:
cv = cross_validation.StratifiedShuffleSplit(train_labels, n_iter = 10, test_size = 0.2, random_state = 0)
In [20]:
grid_cv = grid_search.GridSearchCV(classifier, parameters_grid, scoring = 'accuracy', cv = cv)
grid_cv.get_params().keys()
Out[20]:
In [9]:
%%time
grid_cv.fit(train_data, train_labels)
Out[9]:
In [10]:
grid_cv.best_estimator_
Out[10]:
In [11]:
print grid_cv.best_score_
print grid_cv.best_params_
In [12]:
grid_cv.grid_scores_[:10]
Out[12]:
In [13]:
randomized_grid_cv = grid_search.RandomizedSearchCV(classifier, parameters_grid, scoring = 'accuracy', cv = cv, n_iter = 20,
random_state = 0)
In [14]:
%%time
randomized_grid_cv.fit(train_data, train_labels)
Out[14]:
In [15]:
print randomized_grid_cv.best_score_
print randomized_grid_cv.best_params_