/usr/share/pyshared/mvpa/clfs/plr.py is in python-mvpa 0.4.8-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Penalized logistic regression classifier."""
__docformat__ = 'restructuredtext'
import numpy as N
from mvpa.misc.exceptions import ConvergenceError
from mvpa.clfs.base import Classifier, FailedToTrainError
if __debug__:
from mvpa.base import debug
class PLR(Classifier):
"""Penalized logistic regression `Classifier`.
"""
_clf_internals = [ 'plr', 'binary', 'linear' ]
def __init__(self, lm=1, criterion=1, reduced=0.0, maxiter=20, **kwargs):
"""
Initialize a penalized logistic regression analysis
:Parameters:
lm : int
the penalty term lambda.
criterion : int
the criterion applied to judge convergence.
reduced : float
if not 0, the rank of the data is reduced before
performing the calculations. In that case, reduce is taken
as the fraction of the first singular value, at which a
dimension is not considered significant anymore. A
reasonable criterion is reduced=0.01
maxiter : int
maximum number of iterations. If no convergence occurs
after this number of iterations, an exception is raised.
"""
# init base class first
Classifier.__init__(self, **kwargs)
self.__lm = lm
self.__criterion = criterion
self.__reduced = reduced
self.__maxiter = maxiter
def __repr__(self):
"""String summary over the object
"""
return """PLR(lm=%f, criterion=%d, reduced=%s, maxiter=%d, enable_states=%s)""" % \
(self.__lm, self.__criterion, self.__reduced, self.__maxiter,
str(self.states.enabled))
def _train(self, data):
"""Train the classifier using `data` (`Dataset`).
"""
# Set up the environment for fitting the data
X = data.samples.T
d = data.labels
if set(d) != set([0, 1]):
raise ValueError, \
"Regressors for logistic regression should be [0,1]. Got %s" \
%(set(d),)
if self.__reduced != 0 :
# Data have reduced rank
from scipy.linalg import svd
# Compensate for reduced rank:
# Select only the n largest eigenvectors
U, S, V = svd(X.T)
if S[0] == 0:
raise FailedToTrainError(
"Data provided to PLR seems to be degenerate -- "
"0-th singular value is 0")
S /= S[0]
V = N.matrix(V[:, :N.max(N.where(S > self.__reduced)) + 1])
# Map Data to the subspace spanned by the eigenvectors
X = (X.T * V).T
nfeatures, npatterns = X.shape
# Weighting vector
w = N.matrix(N.zeros( (nfeatures + 1, 1), 'd'))
# Error for convergence criterion
dw = N.matrix(N.ones( (nfeatures + 1, 1), 'd'))
# Patterns of interest in the columns
X = N.matrix( \
N.concatenate((X, N.ones((1, npatterns), 'd')), 0) \
)
p = N.matrix(N.zeros((1, npatterns), 'd'))
# Matrix implementation of penalty term
Lambda = self.__lm * N.identity(nfeatures + 1, 'd')
Lambda[nfeatures, nfeatures] = 0
# Gradient
g = N.matrix(N.zeros((nfeatures + 1, 1), 'd'))
# Fisher information matrix
H = N.matrix(N.identity(nfeatures + 1, 'd'))
# Optimize
k = 0
while N.sum(N.ravel(dw.A ** 2)) > self.__criterion:
p[:, :] = self.__f(w.T * X)
g[:, :] = X * (d - p).T - Lambda * w
H[:, :] = X * N.diag(p.A1 * (1 - p.A1)) * X.T + Lambda
dw[:, :] = H.I * g
w += dw
k += 1
if k > self.__maxiter:
raise ConvergenceError, \
"More than %d Iterations without convergence" % \
(self.__maxiter)
if __debug__:
debug("PLR", \
"PLR converged after %d steps. Error: %g" % \
(k, N.sum(N.ravel(dw.A ** 2))))
if self.__reduced:
# We have computed in rank reduced space ->
# Project to original space
self.w = V * w[:-1]
self.offset = w[-1]
else:
self.w = w[:-1]
self.offset = w[-1]
def __f(self, y):
"""This is the logistic function f, that is used for determination of
the vector w"""
return 1. / (1 + N.exp(-y))
def _predict(self, data):
"""
Predict the class labels for the provided data
Returns a list of class labels
"""
# make sure the data are in matrix form
data = N.matrix(N.asarray(data))
# get the values and then predictions
values = N.ravel(self.__f(self.offset + data * self.w))
predictions = values > 0.5
# save the state if desired, relying on State._setitem_ to
# decide if we will actually save the values
self.predictions = predictions
self.values = values
return predictions
|