from sklearn.grid_search import GridSearchCV
from sklearn.svm import SVC

from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
digits = load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)

"""
Explanation: Grid Searches
Grid-Search with build-in cross validation
End of explanation
"""


import numpy as np

param_grid = {'C': 10. ** np.arange(-3, 3),
              'gamma' : 10. ** np.arange(-5, 0)}
              

np.set_printoptions(suppress=True)
print(param_grid)

grid_search = GridSearchCV(SVC(), param_grid, verbose=3, cv=5)

"""
Explanation: Define parameter grid:
End of explanation
"""


grid_search.fit(X_train, y_train)

grid_search.predict(X_test)

grid_search.score(X_test, y_test)

grid_search.best_params_

# We extract just the scores
%matplotlib notebook
import matplotlib.pyplot as plt

scores = [x[1] for x in grid_search.grid_scores_]
scores = np.array(scores).reshape(6, 5)

plt.matshow(scores)
plt.xlabel('gamma')
plt.ylabel('C')
plt.colorbar()
plt.xticks(np.arange(5), param_grid['gamma'])
plt.yticks(np.arange(6), param_grid['C']);

"""
Explanation: A GridSearchCV object behaves just like a normal classifier.
End of explanation
"""


# %load solutions/grid_search_k_neighbors.py

"""
Explanation: Exercises
Use GridSearchCV to adjust n_neighbors of KNeighborsClassifier.
End of explanation
"""


