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
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler

pipeline = Pipeline([("scaler", StandardScaler()), ("svm", SVC())])
# in new versions: make_pipeline(StandardScaler(), SVC())

pipeline.fit(X_train, y_train)

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 = {'svm__C': 10. ** np.arange(-3, 3), 'svm__gamma' : 10. ** np.arange(-3, 3)}

grid_pipeline = GridSearchCV(pipeline, param_grid=param_grid, n_jobs=-1)

grid_pipeline.fit(X_train, y_train)

grid_pipeline.score(X_test, y_test)

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


