Package rdkit :: Package ML :: Package KNN :: Module KNNModel

[hide private]
[frames] | no frames]

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

     1  # $Id$
     2  #
     3  #  Copyright (C) 2003 Rational Discovery LLC
     4  #      All Rights Reserved
     5  #
     6
     7  """ Define the class _KNNModel_, used to represent a k-nearest neighbhors model
     8
     9  """
    10  from rdkit.DataStructs.TopNContainer import TopNContainer
    11 -class KNNModel(object):
    12    """ This is a base class used by KNNClassificationModel
    13    and KNNRegressionModel to represent a k-nearest neighbor predictor. In general
    14    one of this child classes needs to be instantiated.
    15
    16    _KNNModel_s can save the following pieces of internal state, accessible via
    17      standard setter/getter functions - the child object store additional stuff:
    18
    19      1) _Examples_: a list of examples which have been predicted (either classified
    20                      or values predicted)
    21
    22      2) _TrainingExamples_: List of training examples (since this is a KNN model these examples
    23                             along with the value _k_ below define the model)
    24
    25      3) _TestExamples_: the list of examples used to test the model
    26
    27      4) _k_: the number of closest neighbors used for prediction
    28
    29    """
    30 -  def __init__(self, k, attrs, dfunc, radius=None) :
    31      self._setup(k, attrs, dfunc, radius)
    32
    33 -  def _setup(self, k, attrs, dfunc, radius) :
    34      self._examples = []
    35      self._trainingExamples = []
    36      self._testExamples = []
    37      self._k = k
    38      self._attrs = attrs
    39      self._dfunc = dfunc
    40      self._name = ""
    41      self._radius = radius
    42
    43 -  def GetName(self) :
    44      return self_name
    45
    46 -  def SetName(self, name) :
    47      self._name = name
    48
    49 -  def GetExamples(self) :
    50      return self._examples
    51
    52 -  def SetExamples(self, examples):
    53      self._examples = examples
    54
    55 -  def GetTrainingExamples(self):
    56      return self._trainingExamples
    57
    58 -  def SetTrainingExamples(self,examples):
    59      self._trainingExamples = examples
    60
    61 -  def GetTestExamples(self) :
    62      return self._testExamples
    63
    64 -  def SetTestExamples(self, examples) :
    65      self._testExamples = examples
    66
    67 -  def GetNeighbors(self,example):
    68      """ Returns the k nearest neighbors of the example
    69
    70      """
    71      nbrs = TopNContainer(self._k)
    72      for trex in self._trainingExamples:
    73        dist = self._dfunc(trex, example, self._attrs)
    74        if self._radius is None or dist<self._radius:
    75          nbrs.Insert(-dist,trex)
    76      nbrs.reverse()
    77      return [x for x in nbrs]
    78