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: Preprocessing and Pipelines
End of explanation
"""


from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler

standard_scaler = StandardScaler()
standard_scaler.fit(X_train)
X_train_scaled = standard_scaler.transform(X_train)
svm = SVC().fit(X_train_scaled, y_train)

#pipeline = Pipeline([("scaler", StandardScaler()),
#                     ("svm", SVC())])
# short version:
pipeline = make_pipeline(StandardScaler(), SVC())

pipeline.fit(X_train, y_train)

pipeline.score(X_test, y_test)

pipeline.predict(X_test)

"""
Explanation: Cross-validated pipelines including scaling, we need to estimate mean and standard deviation separately for each fold.
To do that, we build a pipeline.
End of explanation
"""


from sklearn.cross_validation import cross_val_score
cross_val_score(pipeline, X_train, y_train)

"""
Explanation: Cross-validation with a pipeline
End of explanation
"""


import numpy as np
from sklearn.grid_search import GridSearchCV

param_grid = {'svc__C': 10. ** np.arange(-3, 3),
              'svc__gamma' : 10. ** np.arange(-3, 3)
             }

grid_pipeline = GridSearchCV(pipeline, param_grid=param_grid) 

grid_pipeline.fit(X_train, y_train)

grid_pipeline.score(X_test, y_test)

"""
Explanation: Grid Search with a pipeline
End of explanation
"""


# %load solutions/pipeline_knn.py

"""
Explanation: Exercise
Make a pipeline out of the StandardScaler and KNeighborsClassifier and search over the number of neighbors.
End of explanation
"""


