Skip to content

Instantly share code, notes, and snippets.

@Newmu
Last active August 29, 2015 13:57
Show Gist options
  • Save Newmu/9460823 to your computer and use it in GitHub Desktop.
Save Newmu/9460823 to your computer and use it in GitHub Desktop.
Given a training dataset as a 2d array where rows are examples and columns are features, values associated with those training examples, and some new examples to be predicted, return the value associated with the closest nearest neighbor using a scipy distance metric.
import numpy as np
from scipy.spatial.distance import cdist
def nearest_neighbor(samples, targets, samples_to_classify, metric='euclidean'):
return targets[np.argmin(cdist(samples_to_classify, samples, metric=metric), axis=1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment