Similarity-based Learning

Similiarity-based approaches in machine learning come from the idea that the best way to make predictions is simply to look at what has worked in the past and predict the same thing again. The fundamental concepts required to build a system based on this idea are feature spaces and measures of similarity.

What is a metric?

The "distance" $d$ between two points in a vector space must satisfy the following requirements:

  • It is non-negative: $d(x,y) \geq 0$ for all $x$, $y$, with $d(x,y) = 0$ if and only if $x = y$
  • It is symmetric: $d(x,y) = d(y,x)$
  • It satisfies the triangle inequality: $d(x,y) \leq d(x,z) + d(z,y)$

Some common measures of distance:

Euclidean distance

This is perhaps the most commonly used distance metric: $d(X,Y) = \sqrt{(X_0-Y_0)^2 + (X_1-Y_1)^2}$.


In [33]:
import numpy as np
import math as ma
import matplotlib.pyplot as plt
%matplotlib inline

In [28]:
X = np.array([3.3, 1.2])
Y = np.array([2.1, -1.8])

plt.arrow(0,0,*X, head_width=0.2);
plt.arrow(0,0,*Y, head_width=0.2);
plt.xlim([0, 4]);
plt.ylim([-2,2]);
plt.show();



In [18]:
# Euclidean distance manually:
ma.sqrt(np.sum((X-Y)**2))


Out[18]:
3.2310988842807022

In [15]:
# numpy norm:
np.linalg.norm(X-Y)


Out[15]:
3.2310988842807022

More general Minkowski distance

In a d-dimensional vector space, the Minkowski distance of order $p$ is defined as:

$d_p(X,Y) = \left(\sum_{i=1}^{d} \left|X_i - Y_i\right|^p \right)^{1/p}$

The Euclidean distance is a special case of the Minkowski distance with $p=2$.

Some other common cases include:

  • The Manhattan distance: $p = 1$
  • The Chebyshev distance: $p = \infty$, where $d_\infty(X,Y) = \max_{i = 0,\ldots,n}\left| X_i - Y_i \right|$

In [34]:
import scipy.spatial.distance as dst

In [25]:
# Manhattan distance
dst.cdist(np.expand_dims(X, axis=0),np.expand_dims(Y, axis=0),'cityblock')


Out[25]:
array([[ 4.2]])

In [26]:
# Chebyshev distance
dst.cdist(np.expand_dims(X, axis=0),np.expand_dims(Y, axis=0),'chebyshev')


Out[26]:
array([[ 3.]])

Scaling the Axes

The Euclidean distance can be written in (suggestive) vector notation as:

$d^2(X,Y) = (X-Y)^T I_{n \times n} (X-Y)$

Instead of the $n \times n$ identity matrix, we could use and positive definite matrix.

A positive definite matrix is defined as a matrix $M$ for which $z^T M z \geq 0$ for all real vectors $z$, with equality only if $z$ is the vector of all zeros.

We can use this matrix to appropriately rescale the axes, for example to correct for high variance along a given dimension in our feature space: this gives us the Mahalanobis metric,

$d_M(X,Y) = (X-Y)^T \Sigma^{-1} (X-Y)$,

where $\Sigma$ is the covariance matrix of your data points.

Additional reading:

Distances between words (taking into account the context):

http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/

Let's try some clustering


In [56]:
import pandas as pd
from sklearn.neighbors import NearestNeighbors

In [54]:
# read in the basketball draft dataset
df = pd.read_csv('./Table5-2.csv', names=['ID','Speed','Agility','Draft'], skiprows=[0])

df.head()


Out[54]:
ID Speed Agility Draft
0 1 2.50 6.00 no
1 2 3.75 8.00 no
2 3 2.25 5.50 no
3 4 3.25 8.25 no
4 5 2.75 7.50 no

In [53]:
fig, ax = plt.subplots()
ax.margins(0.05)
groups = df.groupby('Draft')
for name, group in groups:
    ax.plot(group.Speed, group.Agility, marker='o', linestyle='', ms=12, label=name);
ax.legend(numpoints=1, loc='lower right');


Nearest-neighbor clustering


In [60]:
# Let's fit a nearest-neighbor model to our data, using Euclidean distance...
nearest_neighbor_model = NearestNeighbors(1, metric='euclidean').fit(df[['Speed','Agility']], df['Draft'])

In [93]:
# OK, now let's find the nearest neighbors for some new data points!
samples = np.array([[7,7],[5,5]]) # samples to classify, in [speed, agility] format

In [82]:
fig, ax = plt.subplots()
ax.margins(0.05)
groups = df.groupby('Draft')
for name, group in groups:
    ax.plot(group.Speed, group.Agility, marker='o', linestyle='', ms=12, label=name);
ax.legend(numpoints=1, loc='lower right');
ax.plot(samples[:,0],samples[:,1], marker='o', linestyle='', ms=12, c='red');



In [94]:
nearest_neighbor_model.kneighbors(samples, return_distance=True)


Out[94]:
(array([[ 1.11803399],
        [ 0.5       ]]), array([[18],
        [ 5]]))

In [95]:
df.Draft.iloc[nearest_neighbor_model.kneighbors(samples, return_distance=False).ravel()] # the kneighbors method returns the index of the
                                                                                         # nearest neighbors....


Out[95]:
18      yes
5        no
Name: Draft, dtype: object

In [70]:
nearest_neighbor_model.kneighbors([[7,7],[5,4]], return_distance=False).ravel()


Out[70]:
array([18,  9])

K-Nearest Neighbors Classifier

The NearestNeighbors function helps us recover the neighbors that are closest to the desired data point; but if we're interested in using k-nearest neighbors for classification, we can use KNeighborsClassifier.


In [84]:
from sklearn.neighbors import KNeighborsClassifier

In [88]:
# define model and train it on the input data
knn_model = KNeighborsClassifier(n_neighbors=5, metric='euclidean').fit(df[['Speed','Agility']], df['Draft'])

In [96]:
# predict classes for "samples", using k nearest neighbors
knn_model.predict(samples)


Out[96]:
array(['  yes', '  no'], dtype=object)

In [100]:
from sklearn.cluster import KMeans

In [102]:
kmeans_model = KMeans(2).fit(df[['Speed','Agility']])

In [104]:
df['Clust'] = kmeans_model.predict(df[['Speed','Agility']])

In [105]:
fig, ax = plt.subplots()
ax.margins(0.05)
groups = df.groupby('Clust')
for name, group in groups:
    ax.plot(group.Speed, group.Agility, marker='o', linestyle='', ms=12, label=name);
ax.legend(numpoints=1, loc='lower right');
ax.plot(samples[:,0],samples[:,1], marker='o', linestyle='', ms=12, c='red');



In [101]:
help(KMeans)


Help on class KMeans in module sklearn.cluster.k_means_:

class KMeans(sklearn.base.BaseEstimator, sklearn.base.ClusterMixin, sklearn.base.TransformerMixin)
 |  K-Means clustering
 |  
 |  Read more in the :ref:`User Guide <k_means>`.
 |  
 |  Parameters
 |  ----------
 |  
 |  n_clusters : int, optional, default: 8
 |      The number of clusters to form as well as the number of
 |      centroids to generate.
 |  
 |  max_iter : int, default: 300
 |      Maximum number of iterations of the k-means algorithm for a
 |      single run.
 |  
 |  n_init : int, default: 10
 |      Number of time the k-means algorithm will be run with different
 |      centroid seeds. The final results will be the best output of
 |      n_init consecutive runs in terms of inertia.
 |  
 |  init : {'k-means++', 'random' or an ndarray}
 |      Method for initialization, defaults to 'k-means++':
 |  
 |      'k-means++' : selects initial cluster centers for k-mean
 |      clustering in a smart way to speed up convergence. See section
 |      Notes in k_init for more details.
 |  
 |      'random': choose k observations (rows) at random from data for
 |      the initial centroids.
 |  
 |      If an ndarray is passed, it should be of shape (n_clusters, n_features)
 |      and gives the initial centers.
 |  
 |  algorithm : "auto", "full" or "elkan", default="auto"
 |      K-means algorithm to use. The classical EM-style algorithm is "full".
 |      The "elkan" variation is more efficient by using the triangle
 |      inequality, but currently doesn't support sparse data. "auto" chooses
 |      "elkan" for dense data and "full" for sparse data.
 |  
 |  precompute_distances : {'auto', True, False}
 |      Precompute distances (faster but takes more memory).
 |  
 |      'auto' : do not precompute distances if n_samples * n_clusters > 12
 |      million. This corresponds to about 100MB overhead per job using
 |      double precision.
 |  
 |      True : always precompute distances
 |  
 |      False : never precompute distances
 |  
 |  tol : float, default: 1e-4
 |      Relative tolerance with regards to inertia to declare convergence
 |  
 |  n_jobs : int
 |      The number of jobs to use for the computation. This works by computing
 |      each of the n_init runs in parallel.
 |  
 |      If -1 all CPUs are used. If 1 is given, no parallel computing code is
 |      used at all, which is useful for debugging. For n_jobs below -1,
 |      (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
 |      are used.
 |  
 |  random_state : integer or numpy.RandomState, optional
 |      The generator used to initialize the centers. If an integer is
 |      given, it fixes the seed. Defaults to the global numpy random
 |      number generator.
 |  
 |  verbose : int, default 0
 |      Verbosity mode.
 |  
 |  copy_x : boolean, default True
 |      When pre-computing distances it is more numerically accurate to center
 |      the data first.  If copy_x is True, then the original data is not
 |      modified.  If False, the original data is modified, and put back before
 |      the function returns, but small numerical differences may be introduced
 |      by subtracting and then adding the data mean.
 |  
 |  Attributes
 |  ----------
 |  cluster_centers_ : array, [n_clusters, n_features]
 |      Coordinates of cluster centers
 |  
 |  labels_ :
 |      Labels of each point
 |  
 |  inertia_ : float
 |      Sum of distances of samples to their closest cluster center.
 |  
 |  Examples
 |  --------
 |  
 |  >>> from sklearn.cluster import KMeans
 |  >>> import numpy as np
 |  >>> X = np.array([[1, 2], [1, 4], [1, 0],
 |  ...               [4, 2], [4, 4], [4, 0]])
 |  >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
 |  >>> kmeans.labels_
 |  array([0, 0, 0, 1, 1, 1], dtype=int32)
 |  >>> kmeans.predict([[0, 0], [4, 4]])
 |  array([0, 1], dtype=int32)
 |  >>> kmeans.cluster_centers_
 |  array([[ 1.,  2.],
 |         [ 4.,  2.]])
 |  
 |  See also
 |  --------
 |  
 |  MiniBatchKMeans
 |      Alternative online implementation that does incremental updates
 |      of the centers positions using mini-batches.
 |      For large scale learning (say n_samples > 10k) MiniBatchKMeans is
 |      probably much faster than the default batch implementation.
 |  
 |  Notes
 |  ------
 |  The k-means problem is solved using Lloyd's algorithm.
 |  
 |  The average complexity is given by O(k n T), were n is the number of
 |  samples and T is the number of iteration.
 |  
 |  The worst case complexity is given by O(n^(k+2/p)) with
 |  n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii,
 |  'How slow is the k-means method?' SoCG2006)
 |  
 |  In practice, the k-means algorithm is very fast (one of the fastest
 |  clustering algorithms available), but it falls in local minima. That's why
 |  it can be useful to restart it several times.
 |  
 |  Method resolution order:
 |      KMeans
 |      sklearn.base.BaseEstimator
 |      sklearn.base.ClusterMixin
 |      sklearn.base.TransformerMixin
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1, algorithm='auto')
 |  
 |  fit(self, X, y=None)
 |      Compute k-means clustering.
 |      
 |      Parameters
 |      ----------
 |      X : array-like or sparse matrix, shape=(n_samples, n_features)
 |          Training instances to cluster.
 |  
 |  fit_predict(self, X, y=None)
 |      Compute cluster centers and predict cluster index for each sample.
 |      
 |      Convenience method; equivalent to calling fit(X) followed by
 |      predict(X).
 |  
 |  fit_transform(self, X, y=None)
 |      Compute clustering and transform X to cluster-distance space.
 |      
 |      Equivalent to fit(X).transform(X), but more efficiently implemented.
 |  
 |  predict(self, X)
 |      Predict the closest cluster each sample in X belongs to.
 |      
 |      In the vector quantization literature, `cluster_centers_` is called
 |      the code book and each value returned by `predict` is the index of
 |      the closest code in the code book.
 |      
 |      Parameters
 |      ----------
 |      X : {array-like, sparse matrix}, shape = [n_samples, n_features]
 |          New data to predict.
 |      
 |      Returns
 |      -------
 |      labels : array, shape [n_samples,]
 |          Index of the cluster each sample belongs to.
 |  
 |  score(self, X, y=None)
 |      Opposite of the value of X on the K-means objective.
 |      
 |      Parameters
 |      ----------
 |      X : {array-like, sparse matrix}, shape = [n_samples, n_features]
 |          New data.
 |      
 |      Returns
 |      -------
 |      score : float
 |          Opposite of the value of X on the K-means objective.
 |  
 |  transform(self, X, y=None)
 |      Transform X to a cluster-distance space.
 |      
 |      In the new space, each dimension is the distance to the cluster
 |      centers.  Note that even if X is sparse, the array returned by
 |      `transform` will typically be dense.
 |      
 |      Parameters
 |      ----------
 |      X : {array-like, sparse matrix}, shape = [n_samples, n_features]
 |          New data to transform.
 |      
 |      Returns
 |      -------
 |      X_new : array, shape [n_samples, k]
 |          X transformed in the new space.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from sklearn.base.BaseEstimator:
 |  
 |  __getstate__(self)
 |  
 |  __repr__(self)
 |  
 |  __setstate__(self, state)
 |  
 |  get_params(self, deep=True)
 |      Get parameters for this estimator.
 |      
 |      Parameters
 |      ----------
 |      deep : boolean, optional
 |          If True, will return the parameters for this estimator and
 |          contained subobjects that are estimators.
 |      
 |      Returns
 |      -------
 |      params : mapping of string to any
 |          Parameter names mapped to their values.
 |  
 |  set_params(self, **params)
 |      Set the parameters of this estimator.
 |      
 |      The method works on simple estimators as well as on nested objects
 |      (such as pipelines). The latter have parameters of the form
 |      ``<component>__<parameter>`` so that it's possible to update each
 |      component of a nested object.
 |      
 |      Returns
 |      -------
 |      self
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from sklearn.base.BaseEstimator:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)