1
2
3
4
5 """
6 This module provides code for doing k-nearest-neighbors classification.
7
8 k Nearest Neighbors is a supervised learning algorithm that classifies
9 a new observation based the classes in its surrounding neighborhood.
10
11 Glossary:
12 distance The distance between two points in the feature space.
13 weight The importance given to each point for classification.
14
15
16 Classes:
17 kNN Holds information for a nearest neighbors classifier.
18
19
20 Functions:
21 train Train a new kNN classifier.
22 calculate Calculate the probabilities of each class, given an observation.
23 classify Classify an observation into a class.
24
25 Weighting Functions:
26 equal_weight Every example is given a weight of 1.
27
28 """
29
30 import numpy
31
33 """Holds information necessary to do nearest neighbors classification.
34
35 Members:
36 classes Set of the possible classes.
37 xs List of the neighbors.
38 ys List of the classes that the neighbors belong to.
39 k Number of neighbors to look at.
40
41 """
43 """kNN()"""
44 self.classes = set()
45 self.xs = []
46 self.ys = []
47 self.k = None
48
50 """equal_weight(x, y) -> 1"""
51
52 return 1
53
54 -def train(xs, ys, k, typecode=None):
55 """train(xs, ys, k) -> kNN
56
57 Train a k nearest neighbors classifier on a training set. xs is a
58 list of observations and ys is a list of the class assignments.
59 Thus, xs and ys should contain the same number of elements. k is
60 the number of neighbors that should be examined when doing the
61 classification.
62
63 """
64 knn = kNN()
65 knn.classes = set(ys)
66 knn.xs = numpy.asarray(xs, typecode)
67 knn.ys = ys
68 knn.k = k
69 return knn
70
72 """calculate(knn, x[, weight_fn][, distance_fn]) -> weight dict
73
74 Calculate the probability for each class. knn is a kNN object. x
75 is the observed data. weight_fn is an optional function that
76 takes x and a training example, and returns a weight. distance_fn
77 is an optional function that takes two points and returns the
78 distance between them. If distance_fn is None (the default), the
79 Euclidean distance is used. Returns a dictionary of the class to
80 the weight given to the class.
81
82 """
83 x = numpy.asarray(x)
84
85 order = []
86 if distance_fn:
87 for i in range(len(knn.xs)):
88 dist = distance_fn(x, knn.xs[i])
89 order.append((dist, i))
90 else:
91
92 temp = numpy.zeros(len(x))
93
94
95 for i in range(len(knn.xs)):
96 temp[:] = x - knn.xs[i]
97 dist = numpy.sqrt(numpy.dot(temp,temp))
98 order.append((dist, i))
99 order.sort()
100
101
102 weights = {}
103 for k in knn.classes:
104 weights[k] = 0.0
105 for dist, i in order[:knn.k]:
106 klass = knn.ys[i]
107 weights[klass] = weights[klass] + weight_fn(x, knn.xs[i])
108
109 return weights
110
112 """classify(knn, x[, weight_fn][, distance_fn]) -> class
113
114 Classify an observation into a class. If not specified, weight_fn will
115 give all neighbors equal weight. distance_fn is an optional function
116 that takes two points and returns the distance between them. If
117 distance_fn is None (the default), the Euclidean distance is used.
118 """
119 weights = calculate(
120 knn, x, weight_fn=weight_fn, distance_fn=distance_fn)
121
122 most_class = None
123 most_weight = None
124 for klass, weight in weights.items():
125 if most_class is None or weight > most_weight:
126 most_class = klass
127 most_weight = weight
128 return most_class
129