from sklearn import datasets
digits = datasets.load_digits()

%pylab inline

digits.data

digits.data.shape  # n_samples, n_features

"""
Explanation: Introduction to scikit-learn
Classification of Handwritten Digits the task is to predict, given an image, which digit it represents. We are given samples of each of the 10 possible classes (the digits zero through nine) on which we fit an estimator to be able to predict the classes to which unseen samples belong.
1. Data collection
2. Data preprocessing
A dataset is a dictionary-like object that holds all the data and some metadata about the data.
End of explanation
"""


digits.target

digits.target.shape

# show images
fig = plt.figure(figsize=(6, 6))  # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

# plot the digits: each image is 8x8 pixels
for i in range(64):
    ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
    ax.imshow(digits.images[i], cmap=plt.cm.binary)
    
    # label the image with the target value
    ax.text(0, 7, str(digits.target[i]))

"""
Explanation: digits.images.shape
End of explanation
"""


from sklearn import svm
clf = svm.SVC(gamma=0.001, C=100.)

"""
Explanation: 3. Build a model on training data
In scikit-learn, an estimator for classification is a Python object that implements the methods fit(X, y) and predict(T).
An example of an estimator is the class sklearn.svm.SVC that implements support vector classification.
End of explanation
"""


clf.fit(digits.data[:-500], digits.target[:-500]) 

"""
Explanation: learning
End of explanation
"""


clf.predict(digits.data[-1]), digits.target[-1]

"""
Explanation: predicting
End of explanation
"""


(clf.predict(digits.data[:-500]) == digits.target[:-500]).sum() / float(len(digits.target[:-500]))

"""
Explanation: 4. Evaluate the model on the test data
learning dataset
End of explanation
"""


(clf.predict(digits.data[-500:]) == digits.target[-500:]).sum() / 500.0

"""
Explanation: test dataset
End of explanation
"""


import pickle
s = pickle.dumps(clf)
clf2 = pickle.loads(s)

clf2.predict(digits.data[-1])

"""
Explanation: 5. Deploy to the real system
End of explanation
"""


