Package rdkit :: Package ML :: Package KNN :: Module KNNClassificationModel
[hide private]
[frames] | no frames]

Source Code for Module rdkit.ML.KNN.KNNClassificationModel

 1  # $Id$ 
 2  # 
 3  #  Copyright (C) 2003 Rational Discovery LLC 
 4  #      All Rights Reserved 
 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   
14 -class KNNClassificationModel(KNNModel.KNNModel) :
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 = [] # list of examples incorrectly classified
23
24 - def type(self):
25 return "Classification Model"
26
27 - def SetBadExamples(self, examples) :
28 self._badExamples = examples
29 - def GetBadExamples(self) :
30 return self._badExamples
31
32 - def NameModel(self, varNames) :
33 self.SetName(self.type())
34
35 - def ClassifyExample(self, example, appendExamples=0, neighborList=None) :
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 # first find the k-closest examples in the traning set 57 knnLst = self.GetNeighbors(example) 58 59 # find out how many of the neighbors belong to each of the classes 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 # now return the class with the maximum count 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