##
## 1. Understand how to use kNN
##
## Example from 
## http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html#example-neighbors-plot-classification-py
##
## Read also the documentation at
##
## http://scikit-learn.org/stable/modules/neighbors.html
##
##
## -Identify the code training the classifier 
## -Identify the code using the classifier for making predictions
##
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets

n_neighbors = 15

# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2]  # we only take the first two features. We could
                      # avoid this ugly slicing by using a two-dim dataset
y = iris.target

h = .02  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights)
    clf.fit(X, y)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("3-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()


##
## TODO
## 1.1. Try different values for n_neighbors and compare the separation
##    boundaries obtained
## 1.2. Select the samples corresponding to classes '0' and '1' and use
##    k-fold cross validation to estimate the error rate of k-NN with
##    different number of neighbors (try 1,3,5,7,9). Which one gives
##    the best estimated error?


##
## 2. Build a "face recognition system": given a number of individuals, each
## being represented by several frontal images, use k-NN to assign new images
## to one of then known identities.
##
## - download the file olivetti.pkz from IS and save it to some folder 
##
## Read the descriptions at 
## http://scikit-learn.org/stable/datasets/index.html#the-olivetti-faces-dataset
## and
## http://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_olivetti_faces.html#sklearn.datasets.fetch_olivetti_faces

from sklearn.datasets import fetch_olivetti_faces

d = fetch_olivetti_faces(data_home="...folder where you saved the olivetti.pkz file...")

## d['data'] is a matrix 400x4096
## To see one image, try
plt.gray() # grey scale images
plt.imshow(d['data'][0,:].reshape(64,64))

##
plt.imshow(d['images'][0])

## Build a training set using 5 images/identity. For example, assuming
## the images are still ordered by identity, with 0...9 for the first identity,
## 10,...,19 for the second, etc.:
idx = [10*id+j for id in np.arange(40) for j in np.arange(5)]
Xtrain = d['data'][idx,:]
ytrain = d['target'][idx]

## Build the corresponding test set, where all images not in the training set
## are included.
Xtest = ...
ytest = ...

## Train a classifier, considering Euclidean distance between points.
## use weights='uniform' and set n_neighbors to some value (say 3)
clf = neighbors.KNeighborsClassifier(n_neighbors, weights='uniform',
                                     algorithm='brute', p=2)
clf.fit(Xtrain, ytrain)

## TODO
## 2.1. Predict the identities of the images in the test set, for the model
##    built.
## 2.2. Change the number of neighbors, see how performance varies.
## 2.3. Change the distance: look at 
## http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.DistanceMetric.html
## 2.4. Write your own distance function. For example use a "distance"
## (better called similarity) based on correlation or cosine distance and see
## how the face recognition works...
