Package mvpa :: Package clfs :: Package sg :: Module sens

[hide private]
[frames] | no frames]

# Source Code for Module mvpa.clfs.sg.sens

     1  # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
     2  # vi: set ft=python sts=4 ts=4 sw=4 et:
     3  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
     4  #
     5  #   See COPYING file distributed along with the PyMVPA package for the
     6  #   copyright and license terms.
     7  #
     8  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
     9  """Provide sensitivity measures for sg's SVM."""
    10
    11  __docformat__ = 'restructuredtext'
    12
    13  import numpy as N
    14
    15  from mvpa.base import externals
    16  if externals.exists('shogun', raiseException=True):
    17      import shogun.Classifier
    18
    19  from mvpa.misc.state import StateVariable
    20  from mvpa.measures.base import Sensitivity
    21
    22  if __debug__:
    23      from mvpa.base import debug
    24
    25
    26 -class LinearSVMWeights(Sensitivity):
    27      """`Sensitivity` that reports the weights of a linear SVM trained
    28      on a given `Dataset`.
    29      """
    30
    31      biases = StateVariable(enabled=True,
    32                             doc="Offsets of separating hyperplanes")
    33
    34 -    def __init__(self, clf, **kwargs):
    35          """Initialize the analyzer with the classifier it shall use.
    36
    37          :Parameters:
    38            clf: LinearSVM
    39              classifier to use. Only classifiers sub-classed from
    40              `LinearSVM` may be used.
    41          """
    42          # init base classes first
    43          Sensitivity.__init__(self, clf, **kwargs)
    44
    45
    46 -    def __sg_helper(self, svm):
    47          """Helper function to compute sensitivity for a single given SVM"""
    48          self.offsets = svm.get_bias()
    49          svcoef = N.matrix(svm.get_alphas())
    50          svnums = svm.get_support_vectors()
    51          svs = self.clf.traindataset.samples[svnums,:]
    52          res = (svcoef * svs).mean(axis=0).A1
    53          return res
    54
    55
    56 -    def _call(self, dataset):
    57          # XXX Hm... it might make sense to unify access functions
    58          # naming across our swig libsvm wrapper and sg access
    59          # functions for svm
    60          svm = self.clf.svm
    61          if isinstance(svm, shogun.Classifier.MultiClassSVM):
    62              sens = []
    63              for i in xrange(svm.get_num_svms()):
    64                  sens.append(self.__sg_helper(svm.get_svm(i)))
    65          else:
    66              sens = self.__sg_helper(svm)
    67          return N.asarray(sens)
    68