Package rdkit :: Package ML :: Package KNN :: Module KNNRegressionModel

[hide private]
[frames] | no frames]

# Source Code for Module rdkit.ML.KNN.KNNRegressionModel

     1  # $Id$
     2  #
     3  #  Copyright (C) 2003 Rational Discovery LLC
     4  #      All Rights Reserved
     5  #
     6
     7  """ Define the class _KNNRegressionModel_, used to represent a k-nearest neighbhors
     8  regression model
     9
    10      Inherits from _KNNModel_
    11  """
    12
    13  from rdkit.ML.KNN import KNNModel
    14
    15
    16 -class KNNRegressionModel(KNNModel.KNNModel) :
    17    """ This is used to represent a k-nearest neighbor classifier
    18
    19    """
    20
    21 -  def __init__(self, k, attrs, dfunc, radius=None) :
    22      self._setup(k, attrs, dfunc,radius)
    23
    24      self._badExamples = [] # list of examples incorrectly classified
    25
    26 -  def type(self):
    27      return "Regression Model"
    28
    29 -  def SetBadExamples(self, examples) :
    30      self._badExamples = examples
    31
    32 -  def GetBadExamples(self) :
    33      return self._badExamples
    34
    35 -  def NameModel(self, varNames) :
    36      self.SetName(self.type())
    37
    38 -  def PredictExample(self, example, appendExamples=0, weightedAverage=0,neighborList=None) :
    39      """ Generates a prediction for an example by looking at its closest 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        - weightedAverage: if provided, the neighbors' contributions to the value will be
    48                           weighed by their reciprocal square distance
    49
    50        - neighborList: if provided, will be used to return the list of neighbors
    51
    52      **Returns**
    53
    54        - the classification of _example_
    55
    56      """
    57      if appendExamples:
    58        self._examples.append(example)
    59
    60      # first find the k-closest examples in the training set
    61      knnLst = self.GetNeighbors(example)
    62
    63      accum = 0.0
    64      denom = 0.0
    65      for knn in knnLst:
    66        if knn[1] is None: continue
    67        if weightedAverage:
    68          dist = knn[0]
    69          if dist==0.0:
    70            w = 1.
    71          else:
    72            w = 1./dist
    73        else:
    74          w=1.0
    75        accum += w*knn[1][-1]
    76        denom += w
    77      if denom:
    78        accum /= denom
    79      if neighborList is not None:
    80        neighborList.extend(knnLst)
    81      return accum
    82