/usr/share/pyshared/mvpa2/featsel/helpers.py is in python-mvpa2 2.1.0-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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 | # 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.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
""""""
__docformat__ = 'restructuredtext'
from math import floor
import numpy as np
from mvpa2.base.dataset import AttrDataset
from mvpa2.base.state import ClassWithCollections, ConditionalAttribute
if __debug__:
from mvpa2.base import debug
#
# Functors to be used for FeatureSelection
#
class BestDetector(object):
"""Determine whether the last value in a sequence is the best one given
some criterion.
"""
def __init__(self, func=min, lastminimum=False):
"""Initialize with number of steps
Parameters
----------
fun : functor
Functor to select the best results. Defaults to min
lastminimum : bool
Toggle whether the latest or the earliest minimum is used as
optimal value to determine the stopping criterion.
"""
self.__func = func
self.__lastminimum = lastminimum
self.__bestindex = None
"""Stores the index of the last detected best value."""
def __call__(self, errors):
"""Returns True if the last value in `errors` is the best or False
otherwise.
"""
isbest = False
# just to prevent ValueError
if len(errors)==0:
return isbest
minerror = self.__func(errors)
if self.__lastminimum:
# make sure it is an array
errors = np.array(errors)
# to find out the location of the minimum but starting from the
# end!
minindex = np.array((errors == minerror).nonzero()).max()
else:
minindex = errors.index(minerror)
self.__bestindex = minindex
# if minimal is the last one reported -- it is the best
if minindex == len(errors)-1:
isbest = True
return isbest
bestindex = property(fget=lambda self:self.__bestindex)
class StoppingCriterion(object):
"""Base class for all functors to decide when to stop RFE (or may
be general optimization... so it probably will be moved out into
some other module
"""
def __call__(self, errors):
"""Instruct when to stop.
Every implementation should return `False` when an empty list is
passed as argument.
Returns tuple `stop`.
"""
raise NotImplementedError
class MultiStopCrit(StoppingCriterion):
"""Stop computation if the latest error drops below a certain threshold.
"""
def __init__(self, crits, mode='or'):
"""
Parameters
----------
crits : list of StoppingCriterion instances
For each call to MultiStopCrit all of these criterions will
be evaluated.
mode : {'and', 'or'}
Logical function to determine the multi criterion from the set
of base criteria.
"""
if not mode in ('and', 'or'):
raise ValueError, \
"A mode %r is not supported." % (mode, )
self.__mode = mode
self.__crits = crits
def __call__(self, errors):
"""Evaluate all criteria to determine the value of the multi criterion.
"""
# evaluate all crits
crits = [ c(errors) for c in self.__crits ]
if self.__mode == 'and':
return np.all(crits)
else:
return np.any(crits)
class FixedErrorThresholdStopCrit(StoppingCriterion):
"""Stop computation if the latest error drops below a certain threshold.
"""
def __init__(self, threshold):
"""Initialize with threshold.
Parameters
----------
threshold : float [0,1]
Error threshold.
"""
StoppingCriterion.__init__(self)
if threshold > 1.0 or threshold < 0.0:
raise ValueError, \
"Threshold %f is out of a reasonable range [0,1]." \
% threshold
self.__threshold = threshold
def __call__(self, errors):
"""Nothing special."""
if len(errors)==0:
return False
if errors[-1] < self.__threshold:
return True
else:
return False
threshold = property(fget=lambda x:x.__threshold)
class NStepsStopCrit(StoppingCriterion):
"""Stop computation after a certain number of steps.
"""
def __init__(self, steps):
"""Initialize with number of steps.
Parameters
----------
steps : int
Number of steps after which to stop.
"""
StoppingCriterion.__init__(self)
if steps < 0:
raise ValueError, \
"Number of steps %i is out of a reasonable range." \
% steps
self.__steps = steps
def __call__(self, errors):
"""Nothing special."""
if len(errors) >= self.__steps:
return True
else:
return False
steps = property(fget=lambda x:x.__steps)
class NBackHistoryStopCrit(StoppingCriterion):
"""Stop computation if for a number of steps error was increasing
"""
def __init__(self, bestdetector=BestDetector(), steps=10):
"""Initialize with number of steps
Parameters
----------
bestdetector : BestDetector
used to determine where the best error is located.
steps : int
How many steps to check after optimal value.
"""
StoppingCriterion.__init__(self)
if steps < 0:
raise ValueError, \
"Number of steps (got %d) should be non-negative" % steps
self.__bestdetector = bestdetector
self.__steps = steps
def __call__(self, errors):
stop = False
# just to prevent ValueError
if len(errors)==0:
return stop
# charge best detector
self.__bestdetector(errors)
# if number of elements after the min >= len -- stop
if len(errors) - self.__bestdetector.bestindex > self.__steps:
stop = True
return stop
steps = property(fget=lambda x:x.__steps)
class ElementSelector(ClassWithCollections):
"""Base class to implement functors to select some elements based on a
sequence of values.
"""
ndiscarded = ConditionalAttribute(enabled=True,
doc="Store number of discarded elements.")
def __init__(self, mode='discard', **kwargs):
"""
Parameters
----------
mode : {'discard', 'select'}
Decides whether to `select` or to `discard` features.
"""
ClassWithCollections.__init__(self, **kwargs)
self._set_mode(mode)
"""Flag whether to select or to discard elements."""
##REF: Name was automagically refactored
def _set_mode(self, mode):
"""Choose `select` or `discard` mode."""
if not mode in ['discard', 'select']:
raise ValueError, "Unkown selection mode [%s]. Can only be one " \
"of 'select' or 'discard'." % mode
self.__mode = mode
def __call__(self, seq):
"""
Parameters
----------
seq
Sequence based on values of which to perform the selection.
If `Dataset`, then only 1st sample is taken.
"""
if isinstance(seq, AttrDataset):
if len(seq)>1:
raise ValueError(
"Feature selectors cannot handle multiple "
"sequences in a Dataset at once. We got dataset %s "
"as input."
% (seq,))
seq = seq.samples[0]
elif hasattr(seq, 'shape'):
shape = seq.shape
if len(shape) > 1:
raise ValueError(
"Feature selectors cannot handle multidimensional "
"inputs (such as ndarrays with more than a single "
"dimension. We got %s with shape %s "
"as input." % (seq.__class__, shape))
return self._call(seq)
def _call(self, seq):
"""Implementations in derived classed have to return a list of selected
element IDs based on the given sequence.
"""
raise NotImplementedError
mode = property(fget=lambda self:self.__mode, fset=_set_mode)
class RangeElementSelector(ElementSelector):
"""Select elements based on specified range of values"""
def __init__(self, lower=None, upper=None, inclusive=False,
mode='select', **kwargs):
"""Initialization `RangeElementSelector`
Parameters
----------
lower
If not None -- select elements which are above of
specified value
upper
If not None -- select elements which are lower of
specified value
inclusive
Either to include end points
mode
overrides parent's default to be 'select' since it is more
native for RangeElementSelector
XXX TODO -- unify??
`upper` could be lower than `lower` -- then selection is done
on values <= lower or >=upper (ie tails). This would produce
the same result if called with flipped values for mode and
inclusive.
If no upper no lower is set, assuming upper,lower=0, thus
outputing non-0 elements
"""
if lower is None and upper is None:
lower, upper = 0, 0
"""Lets better return non-0 values if none of bounds is set"""
# init State before registering anything
ElementSelector.__init__(self, mode=mode, **kwargs)
self.__range = (lower, upper)
"""Values on which to base selection"""
self.__inclusive = inclusive
def _call(self, seq):
"""Returns selected IDs.
"""
lower, upper = self.__range
len_seq = len(seq)
if not lower is None:
if self.__inclusive:
selected = seq >= lower
else:
selected = seq > lower
else:
selected = np.ones( (len_seq), dtype=np.bool )
if not upper is None:
if self.__inclusive:
selected_upper = seq <= upper
else:
selected_upper = seq < upper
if not lower is None:
if lower < upper:
# regular range
selected = np.logical_and(selected, selected_upper)
else:
# outside, though that would be similar to exclude
selected = np.logical_or(selected, selected_upper)
else:
selected = selected_upper
if self.mode == 'discard':
selected = np.logical_not(selected)
result = np.where(selected)[0]
if __debug__:
debug("ES", "Selected %d out of %d elements" %
(len(result), len_seq))
return result
class TailSelector(ElementSelector):
"""Select elements from a tail of a distribution.
The default behaviour is to discard the lower tail of a given distribution.
"""
# TODO: 'both' to select from both tails
def __init__(self, tail='lower', sort=True, **kwargs):
"""Initialize TailSelector
Parameters
----------
tail : ['lower', 'upper']
Choose the tail to be processed.
sort : bool
Flag whether selected IDs will be sorted. Disable if not
necessary to save some CPU cycles.
"""
# init State before registering anything
ElementSelector.__init__(self, **kwargs)
self._set_tail(tail)
"""Know which tail to select."""
self.__sort = sort
##REF: Name was automagically refactored
def _set_tail(self, tail):
"""Set the tail to be processed."""
if not tail in ['lower', 'upper']:
raise ValueError, "Unkown tail argument [%s]. Can only be one " \
"of 'lower' or 'upper'." % tail
self.__tail = tail
##REF: Name was automagically refactored
def _get_n_elements(self, seq):
"""In derived classes has to return the number of elements to be
processed given a sequence values forming the distribution.
"""
raise NotImplementedError
def _call(self, seq):
"""Returns selected IDs.
"""
# TODO: Think about selecting features which have equal values but
# some are selected and some are not
len_seq = len(seq)
# how many to select (cannot select more than available)
nelements = min(self._get_n_elements(seq), len_seq)
# make sure that data is ndarray and compute a sequence rank matrix
# lowest value is first
seqrank = np.array(seq).argsort()
if self.mode == 'discard' and self.__tail == 'upper':
good_ids = seqrank[:-1*nelements]
self.ca.ndiscarded = nelements
elif self.mode == 'discard' and self.__tail == 'lower':
good_ids = seqrank[nelements:]
self.ca.ndiscarded = nelements
elif self.mode == 'select' and self.__tail == 'upper':
good_ids = seqrank[-1*nelements:]
self.ca.ndiscarded = len_seq - nelements
else: # select lower tail
good_ids = seqrank[:nelements]
self.ca.ndiscarded = len_seq - nelements
# sort ids to keep order
# XXX should we do here are leave to other place
if self.__sort:
good_ids.sort()
# only return proper slice args: this is a list of int ids, hence return
# a list not an array
return list(good_ids)
class FixedNElementTailSelector(TailSelector):
"""Given a sequence, provide set of IDs for a fixed number of to be selected
elements.
"""
def __init__(self, nelements, **kwargs):
"""
Parameters
----------
nelements : int
Number of elements to select/discard.
"""
TailSelector.__init__(self, **kwargs)
self.__nelements = None
self._set_n_elements(nelements)
def __repr__(self):
return "%s number=%f" % (
TailSelector.__repr__(self), self.nelements)
##REF: Name was automagically refactored
def _get_n_elements(self, seq):
return self.__nelements
##REF: Name was automagically refactored
def _set_n_elements(self, nelements):
if __debug__:
if nelements <= 0:
raise ValueError, "Number of elements less or equal to zero " \
"does not make sense."
self.__nelements = nelements
nelements = property(fget=lambda x:x.__nelements,
fset=_set_n_elements)
class FractionTailSelector(TailSelector):
"""Given a sequence, provide Ids for a fraction of elements
"""
def __init__(self, felements, **kwargs):
"""
Parameters
----------
felements : float (0,1.0]
Fraction of elements to select/discard. Note: Even when 0.0 is
specified at least one element will be selected.
"""
TailSelector.__init__(self, **kwargs)
self._set_f_elements(felements)
def __repr__(self):
return "%s fraction=%f" % (
TailSelector.__repr__(self), self.__felements)
##REF: Name was automagically refactored
def _get_n_elements(self, seq):
num = int(floor(self.__felements * len(seq)))
num = max(1, num) # remove at least 1
# no need for checks as base class will do anyway
#return min(num, nselect)
return num
##REF: Name was automagically refactored
def _set_f_elements(self, felements):
"""What fraction to discard"""
if felements > 1.0 or felements < 0.0:
raise ValueError, \
"Fraction (%f) cannot be outside of [0.0,1.0]" \
% felements
self.__felements = felements
felements = property(fget=lambda x:x.__felements,
fset=_set_f_elements)
|