```
%matplotlib inline
```

```
import numpy as np
from sklearn import datasets
#iris = datasets.load_iris()
digits = datasets.load_digits()
print(type(digits))
```

The digits dataset is a dictionary-like objects, containing the actual data and some metadata.

```
print(digits.data)
```

digits.data contains the features, i.e. images of handwritten images of digits, which can be used for classification.

```
digits.target
```

```
len(digits.data), len(digits.target)
```

digits.target contain the labels, i.e. digits from 0 to 9 for the digits of digits.data. The data "digits" is a 2 D array with the shape (number of samples, number of features). In our case, a sample is an image of shape (8, 8):

```
print(digits.target[0], digits.data[0])
print(digits.images[0])
```

We want to predict for a given image, which digit it depicts. Our data set contains samples for the classes 0 (zero) to 9 (nine). We will use these samples to fit an estimator so that we can predict unseen samples as well.

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. The constructor of an estimator takes as arguments the parameters of the model, but for the time being, we will consider the estimator as a black box:

```
from sklearn import svm # import support vector machine
classifier = svm.SVC(gamma=0.001, C=100.)
classifier.fit(digits.data[:-3], digits.target[:-3])
```

The classifier, which we have created with svm.SVC, is an estimator object. In general the scikit-learn API provides estimator objects, which can be any object that can learn from data. Learning can be done by classification, regression or clustering algorithm or a transformer that extracts/filters useful features from raw data.

All estimator objects expose a fit method that takes a dataset (usually a 2-d array):

```
classifier.predict(digits.data[-3:])
```

```
digits.target[-3:]
```

```
digits.data[-3]
```

```
import matplotlib.pyplot as plt
from PIL import Image
img = Image.fromarray(np.uint8(digits.images[-2]))
plt.gray()
plt.imshow(img)
plt.show()
```

```
plt.imshow(digits.images[-2], cmap=plt.cm.gray_r)
```

## Iris Dataset

The Iris flower data set is a multivariate data set introduced by Ronald Fisher in his 1936 paper "The use of multiple measurements in taxonomic problems as an example of linear discriminant analysis."

The data set consists of 50 samples from each of three species of Iris

- Iris setosa,
- Iris virginica and
- Iris versicolor).

Four features were measured from each sample the length and the width of the sepals and petals, in centimetres.

Based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other.

```
from sklearn import svm, datasets
import pickle
iris = datasets.load_iris()
clf = svm.SVC()
X, y = iris.data, iris.target
clf.fit(X, y)
```

```
fname = open("classifiers/iris.pkl", "bw")
pickle.dump(clf, fname)
# load the saved classifier:
fname = open("classifiers/iris.pkl", "br")
clf2 = pickle.load(fname)
```

```
clf2.predict(iris.data[::5])
```

```
iris.target[::5]
```

Now, we will do the same with joblib package from sklearn.externals. joblib is more efficient on big data:

```
from sklearn.externals import joblib
joblib.dump(clf, 'classifiers/iris2.pkl')
clf3 = joblib.load('classifiers/iris2.pkl')
clf3.predict(iris.data[::5])
```

## Statistical-learning for Scientific Data Processing

We saw that the "iris dataset" consists of 150 observations of irises, i.e. the samples. Each oberservation is described by four features (the length and the width of the sepals and petals).

In general, we can say that Scikit-learn deals with learning information from one or more datasets that are represented as 2D arrays. Such an array can be seen as a list of multi-dimensional observations. The first axis of such an array is the samples axis and the second one is the features axis.

### Supervised Learning

Supervised learning consists in the task of finding or deducing a function from labeled training data. The training data consist of a set of training examples. In other words: We have the actual data X and the corresponding "targets" y, also called "labels". Often y is a one dimensional array.

An estimator in scikit-learn provides a fit method to fit the model: fit(X, y). It also supplies a predict method which returns predicted labels y for (unlabeled) observations X: predict(X) --> y.

## Instance Based Learning -- -k-nearest-neighbor

Instance based learning works directly on the learned samples, instead of creating rules compared to other classification methods.

Way of working: Each new instance is compared with the already existing instances. The instances are compared by using a distance metric. The instance with the closest distance value detwermines the class for the new instance. This classification method is called nearest-neighbor classification.

```
### k-nearest-neighbor from Scratch
```

```
import numpy as np
from sklearn import datasets
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
print(iris_X[:8])
```

We create a learnsetfrom the sets above. We use permutation from np.random to split the data randomly:

```
np.random.seed(42)
indices = np.random.permutation(len(iris_X))
n_training_samples = 12
iris_X_train = iris_X[indices[:-n_training_samples]]
iris_y_train = iris_y[indices[:-n_training_samples]]
iris_X_test = iris_X[indices[-n_training_samples:]]
iris_y_test = iris_y[indices[-n_training_samples:]]
print(iris_X_test)
```

To determine the similarity between to instances, we need a distance function. In our example, the Euclidean distance is ideal:

```
def distance(instance1, instance2):
# just in case, if the instances are lists or tuples:
instance1 = np.array(instance1)
instance2 = np.array(instance2)
return np.linalg.norm(instance1 - instance2)
print(distance([4, 3, 2], [1, 1,1]))
```

```
def get_neighbors(training_set, test_instance, k):
distances = []
for training_instance in training_set:
dist = distance(test_instance, training_instance[:-1])
distances.append((training_instance, dist))
distances.sort(key=lambda x: x[1])
neighbors = []
for i in range(k):
neighbors.append(distances[i][0])
return neighbors
train_set = [(1, 2, 2, 'apple'),
(-3, -2, 0, 'banana'),
(1, 1, 3, 'apple'),
(-3, -3, -1, 'banana')
]
k = 1
for test_instance in [(0, 0, 0), (2, 2, 2), (-3, -1, 0)]:
neighbors = get_neighbors(train_set, test_instance, 2)
print(test_instance, neighbors)
```

```
```