1
2
3
4
5
6
7 """ Define the class _KNNClassificationModel_, used to represent a k-nearest neighbhors classification model
8
9 Inherits from _KNNModel_
10 """
11
12 from rdkit.ML.KNN import KNNModel
13
15 """ This is used to represent a k-nearest neighbor classifier
16
17 """
18
19 - def __init__(self, k, attrs, dfunc,radius=None) :
20 self._setup(k, attrs, dfunc,radius)
21
22 self._badExamples = []
23
25 return "Classification Model"
26
28 self._badExamples = examples
30 return self._badExamples
31
34
36 """ Classify a an example by looking at its closest neighbors
37
38 The class assigned to this example is same as the class for the mojority of its
39 _k neighbors
40
41 **Arguments**
42
43 - examples: the example to be classified
44
45 - appendExamples: if this is nonzero then the example will be stored on this model
46
47 - neighborList: if provided, will be used to return the list of neighbors
48
49 **Returns**
50
51 - the classification of _example_
52 """
53 if appendExamples:
54 self._examples.append(example)
55
56
57 knnLst = self.GetNeighbors(example)
58
59
60 clsCnt = {}
61 for knn in knnLst :
62 cls = knn[1][-1]
63 if (cls in clsCnt) :
64 clsCnt[cls] += 1
65 else :
66 clsCnt[cls] = 1
67 if neighborList is not None:
68 neighborList.extend(knnLst)
69
70
71 mkey = -1
72 mcnt = -1
73 for key in clsCnt.keys() :
74 if (mcnt < clsCnt[key]) :
75 mkey = key
76 mcnt = clsCnt[key]
77
78 return mkey
79