This file is indexed.

/usr/share/pyshared/mvpa2/clfs/meta.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
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
# 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.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Classes for meta classifiers -- classifiers which use other classifiers

Meta Classifiers can be grouped according to their function as

:group BoostedClassifiers: CombinedClassifier MulticlassClassifier
  SplitClassifier
:group ProxyClassifiers: ProxyClassifier BinaryClassifier MappedClassifier
  FeatureSelectionClassifier
:group PredictionsCombiners for CombinedClassifier: PredictionsCombiner
  MaximalVote MeanPrediction

"""

__docformat__ = 'restructuredtext'

import operator
import numpy as np

from mvpa2.misc.args import group_kwargs
from mvpa2.base.param import Parameter

from mvpa2.generators.splitters import Splitter
from mvpa2.generators.partition import NFoldPartitioner
from mvpa2.datasets.miscfx import get_samples_by_attr
from mvpa2.misc.attrmap import AttributeMap
from mvpa2.base.dochelpers import _str
from mvpa2.base.state import ConditionalAttribute, ClassWithCollections

from mvpa2.clfs.base import Classifier
from mvpa2.clfs.distance import cartesian_distance
from mvpa2.misc.transformers import first_axis_mean

from mvpa2.measures.base import \
    BoostedClassifierSensitivityAnalyzer, ProxyClassifierSensitivityAnalyzer, \
    MappedClassifierSensitivityAnalyzer, \
    FeatureSelectionClassifierSensitivityAnalyzer, \
    RegressionAsClassifierSensitivityAnalyzer, \
    BinaryClassifierSensitivityAnalyzer, \
    _dont_force_slaves

from mvpa2.base import warning

if __debug__:
    from mvpa2.base import debug


class BoostedClassifier(Classifier):
    """Classifier containing the farm of other classifiers.

    Should rarely be used directly. Use one of its childs instead
    """

    # should not be needed if we have prediction_estimates upstairs
    raw_predictions = ConditionalAttribute(enabled=False,
        doc="Predictions obtained from each classifier")

    raw_estimates = ConditionalAttribute(enabled=False,
        doc="Estimates obtained from each classifier")


    def __init__(self, clfs=None, propagate_ca=True,
                 **kwargs):
        """Initialize the instance.

        Parameters
        ----------
        clfs : list
          list of classifier instances to use (slave classifiers)
        propagate_ca : bool
          either to propagate enabled ca into slave classifiers.
          It is in effect only when slaves get assigned - so if state
          is enabled not during construction, it would not necessarily
          propagate into slaves
        kwargs : dict
          dict of keyworded arguments which might get used
          by State or Classifier
        """
        if clfs == None:
            clfs = []

        Classifier.__init__(self, **kwargs)

        self.__clfs = None
        """Pylint friendly definition of __clfs"""

        self.__propagate_ca = propagate_ca
        """Enable current enabled ca in slave classifiers"""

        self._set_classifiers(clfs)
        """Store the list of classifiers"""


    def __repr__(self, prefixes=[]):
        if self.__clfs is None or len(self.__clfs)==0:
            #prefix_ = "clfs=%s" % repr(self.__clfs)
            prefix_ = []
        else:
            prefix_ = ["clfs=[%s,...]" % repr(self.__clfs[0])]
        return super(BoostedClassifier, self).__repr__(prefix_ + prefixes)


    def _train(self, dataset):
        """Train `BoostedClassifier`
        """
        for clf in self.__clfs:
            clf.train(dataset)


    def _posttrain(self, dataset):
        """Custom posttrain of `BoostedClassifier`

        Harvest over the trained classifiers if it was asked to so
        """
        Classifier._posttrain(self, dataset)
        if self.params.retrainable:
            self.__changedData_isset = False


    def _get_feature_ids(self):
        """Custom _get_feature_ids for `BoostedClassifier`
        """
        # return union of all used features by slave classifiers
        feature_ids = set([])
        for clf in self.__clfs:
            feature_ids = feature_ids.union(set(clf.ca.feature_ids))
        return list(feature_ids)


    def _predict(self, dataset):
        """Predict using `BoostedClassifier`
        """
        raw_predictions = [ clf.predict(dataset) for clf in self.__clfs ]
        self.ca.raw_predictions = raw_predictions
        assert(len(self.__clfs)>0)
        if self.ca.is_enabled("estimates"):
            if np.array([x.ca.is_enabled("estimates")
                        for x in self.__clfs]).all():
                estimates = [ clf.ca.estimates for clf in self.__clfs ]
                self.ca.raw_estimates = estimates
            else:
                warning("One or more classifiers in %s has no 'estimates' state" %
                        self + "enabled, thus BoostedClassifier can't have" +
                        " 'raw_estimates' conditional attribute defined")

        return raw_predictions


    def _set_classifiers(self, clfs):
        """Set the classifiers used by the boosted classifier

        We have to allow to set list of classifiers after the object
        was actually created. It will be used by
        MulticlassClassifier
        """
        self.__clfs = clfs
        """Classifiers to use"""

        if len(clfs):
            # enable corresponding ca in the slave-classifiers
            if self.__propagate_ca:
                for clf in self.__clfs:
                    clf.ca.enable(self.ca.enabled, missingok=True)

        # adhere to their capabilities + 'multiclass'
        # XXX do intersection across all classifiers!
        # TODO: this seems to be wrong since it can be regression etc
        self.__tags__ = [ 'binary', 'multiclass', 'meta' ]
        if len(clfs)>0:
            self.__tags__ += self.__clfs[0].__tags__

    def _untrain(self):
        """Untrain `BoostedClassifier`

        Has to untrain any known classifier
        """
        if not self.trained:
            return
        for clf in self.clfs:
            clf.untrain()
        super(BoostedClassifier, self)._untrain()

    def get_sensitivity_analyzer(self, **kwargs):
        """Return an appropriate SensitivityAnalyzer"""
        return BoostedClassifierSensitivityAnalyzer(
                self,
                **kwargs)


    clfs = property(fget=lambda x:x.__clfs,
                    fset=_set_classifiers,
                    doc="Used classifiers")



class ProxyClassifier(Classifier):
    """Classifier which decorates another classifier

    Possible uses:

     - modify data somehow prior training/testing:
       * normalization
       * feature selection
       * modification

     - optimized classifier?

    """

    __sa_class__ = ProxyClassifierSensitivityAnalyzer
    """Sensitivity analyzer to use for a generic ProxyClassifier"""

    def __init__(self, clf, **kwargs):
        """Initialize the instance of ProxyClassifier

        Parameters
        ----------
        clf : Classifier
          Classifier to proxy, i.e. to use after decoration
        """

        # Is done before parents __init__ since we need
        # it for _set_retrainable called during __init__
        self.__clf = clf
        """Store the classifier to use."""

        Classifier.__init__(self, **kwargs)

        # adhere to slave classifier capabilities
        # TODO: unittest
        self.__tags__ = self.__tags__[:] + ['meta']
        if clf is not None:
            self.__tags__ += clf.__tags__


    def __repr__(self, prefixes=[]):
        return super(ProxyClassifier, self).__repr__(
            ["clf=%s" % repr(self.__clf)] + prefixes)

    def __str__(self, *args, **kwargs):
        return super(ProxyClassifier, self).__str__(
            str(self.__clf), *args, **kwargs)

    def summary(self):
        s = super(ProxyClassifier, self).summary()
        if self.trained:
            s += "\n Slave classifier summary:" + \
                 '\n + %s' % \
                 (self.__clf.summary().replace('\n', '\n |'))
        return s

    def _set_retrainable(self, value, force=False):
        # XXX Lazy implementation
        self.clf._set_retrainable(value, force=force)
        super(ProxyClassifier, self)._set_retrainable(value, force)
        if value and not (self.ca['retrained']
                          is self.clf.ca['retrained']):
            if __debug__:
                debug("CLFPRX",
                      "Rebinding conditional attributes from slave clf %s", (self.clf,))
            self.ca['retrained'] = self.clf.ca['retrained']
            self.ca['repredicted'] = self.clf.ca['repredicted']


    def _train(self, dataset):
        """Train `ProxyClassifier`
        """
        # base class does nothing much -- just proxies requests to underlying
        # classifier
        self.__clf.train(dataset)

        # for the ease of access
        # TODO: if to copy we should exclude some ca which are defined in
        #       base Classifier (such as training_time, predicting_time)
        # YOH: for now _copy_ca_ would copy only set ca variables. If
        #      anything needs to be overriden in the parent's class, it is
        #      welcome to do so
        #self.ca._copy_ca_(self.__clf, deep=False)


    def _predict(self, dataset):
        """Predict using `ProxyClassifier`
        """
        clf = self.__clf
        if self.ca.is_enabled('estimates'):
            clf.ca.enable(['estimates'])

        result = clf.predict(dataset)
        # for the ease of access
        self.ca._copy_ca_(self.__clf, ['estimates'], deep=False)
        return result


    def _untrain(self):
        """Untrain ProxyClassifier
        """
        if not self.__clf is None:
            self.__clf.untrain()
        super(ProxyClassifier, self)._untrain()


    @group_kwargs(prefixes=['slave_'], passthrough=True)
    def get_sensitivity_analyzer(self, slave_kwargs, **kwargs):
        """Return an appropriate SensitivityAnalyzer

        Parameters
        ----------
        slave_kwargs : dict
          Arguments to be passed to the proxied (slave) classifier
        **kwargs
          Specific additional arguments for the sensitivity analyzer
          for the class.  See documentation of a corresponding `.__sa_class__`.
        """
        return self.__sa_class__(
                self,
                analyzer=self.__clf.get_sensitivity_analyzer(**slave_kwargs),
                **kwargs)


    clf = property(lambda x:x.__clf, doc="Used `Classifier`")



#
# Various combiners for CombinedClassifier
#

class PredictionsCombiner(ClassWithCollections):
    """Base class for combining decisions of multiple classifiers"""

    def train(self, clfs, dataset):
        """PredictionsCombiner might need to be trained

        Parameters
        ----------
        clfs : list of Classifier
          List of classifiers to combine. Has to be classifiers (not
          pure predictions), since combiner might use some other
          conditional attributes (value's) instead of pure prediction's
        dataset : Dataset
          training data in this case
        """
        pass


    def __call__(self, clfs, dataset):
        """Call function

        Parameters
        ----------
        clfs : list of Classifier
          List of classifiers to combine. Has to be classifiers (not
          pure predictions), since combiner might use some other
          conditional attributes (value's) instead of pure prediction's
        """
        raise NotImplementedError



class MaximalVote(PredictionsCombiner):
    """Provides a decision using maximal vote rule"""

    predictions = ConditionalAttribute(enabled=True,
        doc="Voted predictions")
    estimates = ConditionalAttribute(enabled=False,
        doc="Estimates keep counts across classifiers for each label/sample")

    # TODO: Might get a parameter to use raw decision estimates if
    # voting is not unambigous (ie two classes have equal number of
    # votes

    def __init__(self, **kwargs):
        PredictionsCombiner.__init__(self, **kwargs)


    def __call__(self, clfs, dataset):
        """Actuall callable - perform voting

        Extended functionality which might not be needed actually:
        Since `BinaryClassifier` might return a list of possible
        predictions (not just a single one), we should consider all of those

        MaximalVote doesn't care about dataset itself
        """
        if len(clfs)==0:
            return []                   # to don't even bother

        all_label_counts = None
        for clf in clfs:
            # Lets check first if necessary conditional attribute is enabled
            if not clf.ca.is_enabled("predictions"):
                raise ValueError, "MaximalVote needs classifiers (such as " + \
                      "%s) with state 'predictions' enabled" % clf
            predictions = clf.ca.predictions
            if all_label_counts is None:
                all_label_counts = [ {} for i in xrange(len(predictions)) ]

            # for every sample
            for i in xrange(len(predictions)):
                prediction = predictions[i]
                # XXX fishy location due to literal labels,
                # TODO simplify assumptions and logic
                if isinstance(prediction, basestring) or \
                       not operator.isSequenceType(prediction):
                    prediction = (prediction,)
                for label in prediction: # for every label
                    # XXX we might have multiple labels assigned
                    # but might not -- don't remember now
                    if not all_label_counts[i].has_key(label):
                        all_label_counts[i][label] = 0
                    all_label_counts[i][label] += 1

        predictions = []
        # select maximal vote now for each sample
        for i in xrange(len(all_label_counts)):
            label_counts = all_label_counts[i]
            # lets do explicit search for max so we know
            # if it is unique
            maxk = []                   # labels of elements with max vote
            maxv = -1
            for k, v in label_counts.iteritems():
                if v > maxv:
                    maxk = [k]
                    maxv = v
                elif v == maxv:
                    maxk.append(k)

            assert len(maxk) >= 1, \
                   "We should have obtained at least a single key of max label"

            if len(maxk) > 1:
                warning("We got multiple labels %s which have the " % maxk +
                        "same maximal vote %d. XXX disambiguate" % maxv)
            predictions.append(maxk[0])

        ca = self.ca
        ca.estimates = all_label_counts
        ca.predictions = predictions
        return predictions



class MeanPrediction(PredictionsCombiner):
    """Provides a decision by taking mean of the results
    """

    predictions = ConditionalAttribute(enabled=True,
        doc="Mean predictions")

    estimates = ConditionalAttribute(enabled=True,
        doc="Predictions from all classifiers are stored")

    def __call__(self, clfs, dataset):
        """Actuall callable - perform meaning

        """
        if len(clfs)==0:
            return []                   # to don't even bother

        all_predictions = []
        for clf in clfs:
            # Lets check first if necessary conditional attribute is enabled
            if not clf.ca.is_enabled("predictions"):
                raise ValueError, "MeanPrediction needs learners (such " \
                      " as %s) with state 'predictions' enabled" % clf
            all_predictions.append(clf.ca.predictions)

        # compute mean
        all_predictions = np.asarray(all_predictions)
        predictions = np.mean(all_predictions, axis=0)

        ca = self.ca
        ca.estimates = all_predictions
        ca.predictions = predictions
        return predictions


class ClassifierCombiner(PredictionsCombiner):
    """Provides a decision using training a classifier on predictions/estimates

    TODO: implement
    """

    predictions = ConditionalAttribute(enabled=True,
        doc="Trained predictions")


    def __init__(self, clf, variables=None):
        """Initialize `ClassifierCombiner`

        Parameters
        ----------
        clf : Classifier
          Classifier to train on the predictions
        variables : list of str
          List of conditional attributes stored in 'combined' classifiers, which
          to use as features for training this classifier
        """
        PredictionsCombiner.__init__(self)

        self.__clf = clf
        """Classifier to train on `variables` ca of provided classifiers"""

        if variables == None:
            variables = ['predictions']
        self.__variables = variables
        """What conditional attributes of the classifiers to use"""


    def _untrain(self):
        """It might be needed to untrain used classifier"""
        if self.__clf:
            self.__clf._untrain()

    def __call__(self, clfs, dataset):
        """
        """
        if len(clfs)==0:
            return []                   # to don't even bother

        raise NotImplementedError



class CombinedClassifier(BoostedClassifier):
    """`BoostedClassifier` which combines predictions using some
    `PredictionsCombiner` functor.
    """

    def __init__(self, clfs=None, combiner=None, **kwargs):
        """Initialize the instance.

        Parameters
        ----------
        clfs : list of Classifier
          list of classifier instances to use
        combiner : PredictionsCombiner
          callable which takes care about combining multiple
          results into a single one (e.g. maximal vote for
          classification, MeanPrediction for regression))
        kwargs : dict
          dict of keyworded arguments which might get used
          by State or Classifier

        NB: `combiner` might need to operate not on 'predictions' descrete
            labels but rather on raw 'class' estimates classifiers
            estimate (which is pretty much what is stored under
            `estimates`
        """
        if clfs == None:
            clfs = []

        BoostedClassifier.__init__(self, clfs, **kwargs)

        self.__combiner = combiner
        """Functor destined to combine results of multiple classifiers"""


    def __repr__(self, prefixes=[]):
        """Literal representation of `CombinedClassifier`.
        """
        return super(CombinedClassifier, self).__repr__(
            ["combiner=%s" % repr(self.__combiner)] + prefixes)

    @property
    def combiner(self):
        # Decide either we are dealing with regressions
        # by looking at 1st learner
        if self.__combiner is None:
            self.__combiner = (
                MaximalVote,
                MeanPrediction)[int(self.clfs[0].__is_regression__)]()
        return self.__combiner


    def summary(self):
        """Provide summary for the `CombinedClassifier`.
        """
        s = super(CombinedClassifier, self).summary()
        if self.trained:
            s += "\n Slave classifiers summaries:"
            for i, clf in enumerate(self.clfs):
                s += '\n + %d clf: %s' % \
                     (i, clf.summary().replace('\n', '\n |'))
        return s


    def _untrain(self):
        """Untrain `CombinedClassifier`
        """
        try:
            self.__combiner.untrain()
        except:
            pass
        super(CombinedClassifier, self)._untrain()


    def _train(self, dataset):
        """Train `CombinedClassifier`
        """
        BoostedClassifier._train(self, dataset)

        # combiner might need to train as well
        self.combiner.train(self.clfs, dataset)


    def _predict(self, dataset):
        """Predict using `CombinedClassifier`
        """
        ca = self.ca
        cca = self.combiner.ca
        BoostedClassifier._predict(self, dataset)
        if ca.is_enabled("estimates"):
            cca.enable('estimates')
        # combiner will make use of conditional attributes instead of only predictions
        # returned from _predict
        predictions = self.combiner(self.clfs, dataset)
        ca.predictions = predictions

        if ca.is_enabled("estimates"):
            if cca.is_active("estimates"):
                # XXX or may be we could leave simply up to accessing .combiner?
                ca.estimates = cca.estimates
            else:
                if __debug__:
                    warning("Boosted classifier %s has 'estimates' state enabled,"
                            " but combiner doesn't have 'estimates' active, thus "
                            " .estimates cannot be provided directly, access .clfs"
                            % self)
        return predictions



class TreeClassifier(ProxyClassifier):
    """`TreeClassifier` which allows to create hierarchy of classifiers

    Functions by grouping some labels into a single "meta-label" and training
    classifier first to separate between meta-labels.  Then
    each group further proceeds with classification within each group.

    Possible scenarios::

      TreeClassifier(SVM(),
       {'animate':  ((1,2,3,4),
                     TreeClassifier(SVM(),
                         {'human': (('male', 'female'), SVM()),
                          'animals': (('monkey', 'dog'), SMLR())})),
        'inanimate': ((5,6,7,8), SMLR())})

    would create classifier which would first do binary classification
    to separate animate from inanimate, then for animate result it
    would separate to classify human vs animal and so on::

                                   SVM
                                 /     \
                            animate  inanimate
                             /            \
                           SVM            SMLR
                         /     \         / | \ \
                    human    animal     5  6 7  8
                     |          |
                    SVM        SVM
                   /   \       /  \
                 male female monkey dog
                  1      2    3      4

    If it is desired to have a trailing node with a single label and
    thus without any classification, such as in

                       SVM
                      /   \
                     g1   g2
                     /     \
                    1     SVM
                          /  \
                         2    3

    then just specify None as the classifier to use::

        TreeClassifier(SVM(),
           {'g1':  ((1,), None),
            'g2':  ((1,2,3,4), SVM())})

    """

    _DEV__doc = """
    Questions:
     * how to collect confusion matrices at a particular layer if such
       classifier is given to SplitClassifier or CVTE

     * What additional ca to add, something like
        clf_labels  -- store remapped labels for the dataset
        clf_estimates  ...

     * What do we store into estimates ? just estimates from the clfs[]
       for corresponding samples, or top level clf estimates as well?

     * what should be SensitivityAnalyzer?  by default it would just
       use top slave classifier (i.e. animate/inanimate)

    Problems?
     *  .clf is not actually "proxied" per se, so not sure what things
        should be taken care of yet...

    TODO:
     * Allow a group to be just a single category, so no further
        classifier is needed, it just should stay separate from the
        other groups

    Possible TODO:
     *  Add ability to provide results of clf.estimates as features into
        input of clfs[]. This way we could provide additional 'similarity'
        information to the "other" branch

    """

    def __init__(self, clf, groups, **kwargs):
        """Initialize TreeClassifier

        Parameters
        ----------
        clf : Classifier
          Classifier to separate between the groups
        groups : dict of meta-label: tuple of (tuple of labels, classifier)
          Defines the groups of labels and their classifiers.
          See :class:`~mvpa2.clfs.meta.TreeClassifier` for example
        """

        # Basic initialization
        ProxyClassifier.__init__(self, clf, **kwargs)

        # XXX RF: probably create internal structure with dictionary,
        # not just a tuple, and store all information in there
        # accordingly

        self._groups = groups
        self._index2group = groups.keys()

        # All processing of groups needs to be handled within _train
        # since labels_map is not available here and definition
        # is allowed to carry both symbolic and numeric values for
        # labels
        # XXX TODO due to abandoning of labels_map -- may be this is
        #     no longer the case?

        # We can only assign respective classifiers
        self.clfs = dict([(gk, c) for gk, (ls, c) in groups.iteritems()])
        """Dictionary of classifiers used by the groups"""


    def __repr__(self, prefixes=[]):
        """String representation of TreeClassifier
        """
        prefix = "groups=%s" % repr(self._groups)
        return super(TreeClassifier, self).__repr__([prefix] + prefixes)

    def __str__(self, *args, **kwargs):
        return super(TreeClassifier, self).__str__(
            ', '.join(['%s: %s' % i for i in self.clfs.iteritems()]),
            *args, **kwargs)

    def summary(self):
        """Provide summary for the `TreeClassifier`.
        """
        s = super(TreeClassifier, self).summary()
        if self.trained:
            s += "\n Node classifiers summaries:"
            for i, (clfname, clf) in enumerate(self.clfs.iteritems()):
                s += '\n + %d %s clf: %s' % \
                     (i, clfname, clf.summary().replace('\n', '\n |'))
        return s


    def _train(self, dataset):
        """Train TreeClassifier

        First train .clf on groupped samples, then train each of .clfs
        on a corresponding subset of samples.
        """
        # Local bindings
        targets_sa_name = self.get_space()    # name of targets sa
        targets_sa = dataset.sa[targets_sa_name] # actual targets sa
        clf, clfs, index2group = self.clf, self.clfs, self._index2group

        # Handle groups of labels
        groups = self._groups
        groups_labels = {}              # just groups with numeric indexes
        label2index = {}                # how to map old labels to new
        known = set()
        for gi, gk in enumerate(index2group):
            ls = groups[gk][0]
            known_already = known.intersection(ls)
            if len(known_already):
                raise ValueError, "Grouping of labels is not appropriate. " \
                      "Got labels %s already among known in %s. " % \
                       (known_already, known  )
            groups_labels[gk] = ls      # needed? XXX
            for l in ls :
                label2index[l] = gi
            known = known.union(ls )
        # TODO: check if different literal labels weren't mapped into
        #       same numerical but here asked to belong to different groups
        #  yoh: actually above should catch it

        # Check if none of the labels is missing from known groups
        dsul = set(targets_sa.unique)
        if known.intersection(dsul) != dsul:
            raise ValueError, \
                  "Dataset %s had some labels not defined in groups: %s. " \
                  "Known are %s" % \
                  (dataset, dsul.difference(known), known)

        # We can operate on the same dataset here 
        # Nope: doesn't work nicely with the classifier like kNN
        #      which links to the dataset used in the training,
        #      so whenever if we simply restore labels back, we
        #      would get kNN confused in _predict()
        #      Therefore we need to create a shallow copy of
        #      dataset and provide it with new labels
        ds_group = dataset.copy(deep=False)
        # assign new labels group samples into groups of labels
        ds_group.sa[targets_sa_name].value = [label2index[l]
                                              for l in targets_sa.value]

        # train primary classifier
        if __debug__:
            debug('CLFTREE', "Training primary %s on %s with targets %s",
                  (clf, ds_group, ds_group.sa[targets_sa_name].unique))
        clf.train(ds_group)

        # ??? should we obtain values for anything?
        #     may be we could training values of .clfs to be added
        #     as features to the next level -- i.e. .clfs

        # Proceed with next 'layer' and train all .clfs on corresponding
        # selection of samples
        # ??? should we may be allow additional 'the other' category, to
        #     signal contain all the other categories data? probably not
        #     since then it would lead to undetermined prediction (which
        #     might be not a bad thing altogether...)
        for gk in groups.iterkeys():
            clf = clfs[gk]
            group_labels = groups_labels[gk]
            if clf is None: # Trailing node
                if len(group_labels) != 1:
                    raise ValueError(
                        "Trailing nodes with no classifier assigned must have "
                        "only a single label associated. Got %s defined in "
                        "group %r of %s"
                        % (group_labels, gk, self))
            else:
                # select samples per each group
                ids = get_samples_by_attr(dataset, targets_sa_name, groups_labels[gk])
                ds_group = dataset[ids]
                if __debug__:
                    debug('CLFTREE', "Training %s for group %s on %s",
                          (clfs[gk], gk, ds_group))
                # and train corresponding slave clf
                clf.train(ds_group)


    def _untrain(self):
        """Untrain TreeClassifier
        """
        super(TreeClassifier, self)._untrain()
        for clf in self.clfs.values():
            if clf is not None:
                clf.untrain()


    def _predict(self, dataset):
        """
        """
        # Local bindings
        clfs, index2group, groups = self.clfs, self._index2group, self._groups
        clf_predictions = np.asanyarray(ProxyClassifier._predict(self, dataset))
        if __debug__:
                debug('CLFTREE',
                      'Predictions %s',
                      (clf_predictions))
        # assure that predictions are indexes, ie int
        clf_predictions = clf_predictions.astype(int)

        # now for predictions pointing to specific groups go into
        # corresponding one
        # defer initialization since dtype would depend on predictions
        predictions = None
        for pred_group in set(clf_predictions):
            gk = index2group[pred_group]
            clf_ = clfs[gk]
            group_indexes = (clf_predictions == pred_group)
            if __debug__:
                debug('CLFTREE',
                      'Predicting for group %s using %s on %d samples',
                      (gk, clf_, np.sum(group_indexes)))
            if clf_ is None:
                p = groups[gk][0] # our only label
            else:
                p = clf_.predict(dataset[group_indexes])

            if predictions is None:
                predictions = np.zeros((len(dataset),),
                                       dtype=np.asanyarray(p).dtype)
            predictions[group_indexes] = p
        return predictions


class BinaryClassifier(ProxyClassifier):
    """`ProxyClassifier` which maps set of two labels into +1 and -1
    """

    __sa_class__ = BinaryClassifierSensitivityAnalyzer

    def __init__(self, clf, poslabels, neglabels, **kwargs):
        """
        Parameters
        ----------
        clf : Classifier
          classifier to use
        poslabels : list
          list of labels which are treated as +1 category
        neglabels : list
          list of labels which are treated as -1 category
        """

        ProxyClassifier.__init__(self, clf, **kwargs)

        # Handle labels
        sposlabels = set(poslabels)
        sneglabels = set(neglabels)

        # TODO: move to use AttributeMap
        #self._attrmap = AttributeMap(dict([(l, -1) for l in sneglabels] +
        #                                  [(l, +1) for l in sposlabels]))

        # check if there is no overlap
        overlap = sposlabels.intersection(sneglabels)
        if len(overlap)>0:
            raise ValueError("Sets of positive and negative labels for " +
                "BinaryClassifier must not overlap. Got overlap " %
                overlap)

        self.__poslabels = list(sposlabels)
        self.__neglabels = list(sneglabels)

        # define what values will be returned by predict: if there is
        # a single label - return just it alone, otherwise - whole
        # list
        # Such approach might come useful if we use some classifiers
        # over different subsets of data with some voting later on
        # (1-vs-therest?)

        if len(self.__poslabels) > 1:
            self.__predictpos = self.__poslabels
        else:
            self.__predictpos = self.__poslabels[0]

        if len(self.__neglabels) > 1:
            self.__predictneg = self.__neglabels
        else:
            self.__predictneg = self.__neglabels[0]

    @property
    def poslabels(self):
        return self.__poslabels

    @property
    def neglabels(self):
        return self.__neglabels

    def __repr__(self, prefixes=[]):
        prefix = "poslabels=%s, neglabels=%s" % (
            repr(self.__poslabels), repr(self.__neglabels))
        return super(BinaryClassifier, self).__repr__([prefix] + prefixes)


    def _train(self, dataset):
        """Train `BinaryClassifier`
        """
        targets_sa_name = self.get_space()
        idlabels = [(x, +1) for x in get_samples_by_attr(dataset, targets_sa_name,
                                                         self.__poslabels)] + \
                    [(x, -1) for x in get_samples_by_attr(dataset, targets_sa_name,
                                                          self.__neglabels)]
        # XXX we have to sort ids since at the moment Dataset.select_samples
        #     doesn't take care about order
        idlabels.sort()

        # If we need all samples, why simply not perform on original
        # data, an just store/restore labels. But it really should be done
        # within Dataset.select_samples
        if len(idlabels) == dataset.nsamples \
            and [x[0] for x in idlabels] == range(dataset.nsamples):
            # the last condition is not even necessary... just overly
            # cautious
            datasetselected = dataset.copy(deep=False)   # no selection is needed
            if __debug__:
                debug('CLFBIN',
                      "Created shallow copy with %d samples for binary "
                      "classification among labels %s/+1 and %s/-1",
                      (dataset.nsamples, self.__poslabels, self.__neglabels))
        else:
            datasetselected = dataset[[ x[0] for x in idlabels ]]
            if __debug__:
                debug('CLFBIN',
                      "Selected %d samples out of %d samples for binary "
                      "classification among labels %s/+1 and %s/-1. Selected %s",
                      (len(idlabels), dataset.nsamples,
                       self.__poslabels, self.__neglabels, datasetselected))

        # adjust the labels
        datasetselected.sa[targets_sa_name].value = [ x[1] for x in idlabels ]

        # now we got a dataset with only 2 labels
        if __debug__:
            assert(set(datasetselected.sa[targets_sa_name].unique) ==
                   set([-1, 1]))

        self.clf.train(datasetselected)


    def _predict(self, dataset):
        """Predict the labels for a given `dataset`

        Predicts using binary classifier and spits out list (for each sample)
        where with either poslabels or neglabels as the "label" for the sample.
        If there was just a single label within pos or neg labels then it would
        return not a list but just that single label.
        """
        binary_predictions = ProxyClassifier._predict(self, dataset)
        self.ca.estimates = binary_predictions
        predictions = [ {-1: self.__predictneg,
                         +1: self.__predictpos}[x] for x in binary_predictions]
        self.ca.predictions = predictions
        return predictions



class MulticlassClassifier(CombinedClassifier):
    """`CombinedClassifier` to perform multiclass using a list of
    `BinaryClassifier`.

    such as 1-vs-1 (ie in pairs like libsvm doesn) or 1-vs-all (which
    is yet to think about)
    """

    def __init__(self, clf, bclf_type="1-vs-1", **kwargs):
        """Initialize the instance

        Parameters
        ----------
        clf : Classifier
          classifier based on which multiple classifiers are created
          for multiclass
        bclf_type
          "1-vs-1" or "1-vs-all", determines the way to generate binary
          classifiers
        """
        CombinedClassifier.__init__(self, **kwargs)

        self.__clf = clf
        """Store sample instance of basic classifier"""

        # adhere to slave classifier capabilities
        if clf is not None:
            self.__tags__ += clf.__tags__
        if not 'multiclass' in self.__tags__:
            self.__tags__ += ['multiclass']

        # Some checks on known ways to do multiclass
        if bclf_type == "1-vs-1":
            pass
        elif bclf_type == "1-vs-all": # TODO
            raise NotImplementedError
        else:
            raise ValueError, \
                  "Unknown type of classifier %s for " % bclf_type + \
                  "BoostedMulticlassClassifier"
        self.__bclf_type = bclf_type

    # XXX fix it up a bit... it seems that MulticlassClassifier should
    # be actually ProxyClassifier and use BoostedClassifier internally
    def __repr__(self, prefixes=[]):
        prefix = "bclf_type=%s, clf=%s" % (repr(self.__bclf_type),
                                            repr(self.__clf))
        return super(MulticlassClassifier, self).__repr__([prefix] + prefixes)


    def _train(self, dataset):
        """Train classifier
        """
        targets_sa_name = self.get_space()

        # construct binary classifiers
        ulabels = dataset.sa[targets_sa_name].unique
        if self.__bclf_type == "1-vs-1":
            # generate pairs and corresponding classifiers
            biclfs = []
            for i in xrange(len(ulabels)):
                for j in xrange(i+1, len(ulabels)):
                    clf = self.__clf.clone()
                    biclfs.append(
                        BinaryClassifier(
                            clf,
                            poslabels=[ulabels[i]], neglabels=[ulabels[j]]))
            if __debug__:
                debug("CLFMC", "Created %d binary classifiers for %d labels",
                      (len(biclfs), len(ulabels)))

            self.clfs = biclfs

        elif self.__bclf_type == "1-vs-all":
            raise NotImplementedError

        # perform actual training
        CombinedClassifier._train(self, dataset)



class SplitClassifier(CombinedClassifier):
    """`BoostedClassifier` to work on splits of the data

    """

    """
    TODO: SplitClassifier and MulticlassClassifier have too much in
          common -- need to refactor: just need a splitter which would
          split dataset in pairs of class labels. MulticlassClassifier
          does just a tiny bit more which might be not necessary at
          all: map sets of labels into 2 categories...
    """

    stats = ConditionalAttribute(enabled=False,
        doc="Resultant confusion whenever classifier trained " +
            "on 1 part and tested on 2nd part of each split")

    splits = ConditionalAttribute(enabled=False, doc=
       """Store the actual splits of the data. Can be memory expensive""")

    # ??? couldn't be training_stats since it has other meaning
    #     here, BUT it is named so within CrossValidatedTransferError
    #     -- unify
    #  decided to go with overriding semantics tiny bit. For split
    #     classifier training_stats would correspond to summary
    #     over training errors across all splits. Later on if need comes
    #     we might want to implement global_training_stats which would
    #     correspond to overall confusion on full training dataset as it is
    #     done in base Classifier
    #global_training_stats = ConditionalAttribute(enabled=False,
    #    doc="Summary over training confusions acquired at each split")

    def __init__(self, clf, partitioner=NFoldPartitioner(),
                 splitter=Splitter('partitions', count=2), **kwargs):
        """Initialize the instance

        Parameters
        ----------
        clf : Classifier
          classifier based on which multiple classifiers are created
          for multiclass
        splitter : Splitter
          `Splitter` to use to split the dataset prior training
        """

        CombinedClassifier.__init__(self, **kwargs)
        self.__clf = clf
        """Store sample instance of basic classifier"""

        if isinstance(splitter, type):
            raise ValueError, \
                  "Please provide an instance of a splitter, not a type." \
                  " Got %s" % splitter

        self.__partitioner = partitioner
        self.__splitter = splitter


    def _train(self, dataset):
        """Train `SplitClassifier`
        """
        targets_sa_name = self.get_space()

        # generate pairs and corresponding classifiers
        bclfs = []

        # local binding
        ca = self.ca

        clf_template = self.__clf
        if ca.is_enabled('stats'):
            ca.stats = clf_template.__summary_class__()
        if ca.is_enabled('training_stats'):
            clf_template.ca.enable(['training_stats'])
            ca.training_stats = clf_template.__summary_class__()

        clf_hastestdataset = hasattr(clf_template, 'testdataset')

        # for proper and easier debugging - first define classifiers and then
        # train them
        for split in self.__partitioner.get_partition_specs(dataset):
            if __debug__:
                debug("CLFSPL_", "Deepcopying %s for %s",
                      (clf_template, self))
            clf = clf_template.clone()
            bclfs.append(clf)
        self.clfs = bclfs

        self.ca.splits = []

        for i, pset in enumerate(self.__partitioner.generate(dataset)):
            if __debug__:
                debug("CLFSPL", "Training classifier for split %d", (i,))

            # split partitioned dataset
            split = [d for d in self.__splitter.generate(pset)]

            if ca.is_enabled("splits"):
                self.ca.splits.append(split)

            clf = self.clfs[i]

            # assign testing dataset if given classifier can digest it
            if clf_hastestdataset:
                clf.testdataset = split[1]

            clf.train(split[0])

            # unbind the testdataset from the classifier
            if clf_hastestdataset:
                clf.testdataset = None

            if ca.is_enabled("stats"):
                predictions = clf.predict(split[1])
                self.ca.stats.add(split[1].sa[targets_sa_name].value,
                                          predictions,
                                          clf.ca.get('estimates', None))
                if __debug__:
                    dact = debug.active
                    if 'CLFSPL_' in dact:
                        debug('CLFSPL_', 'Split %d:\n%s',
                              (i, self.ca.stats))
                    elif 'CLFSPL' in dact:
                        debug('CLFSPL', 'Split %d error %.2f%%',
                              (i, self.ca.stats.summaries[-1].error))

            if ca.is_enabled("training_stats"):
                # XXX this is broken, as it cannot deal with not yet set ca
                ca.training_stats += clf.ca.training_stats


    @group_kwargs(prefixes=['slave_'], passthrough=True)
    def get_sensitivity_analyzer(self, slave_kwargs={}, **kwargs):
        """Return an appropriate SensitivityAnalyzer for `SplitClassifier`

        Parameters
        ----------
        combiner
          If not provided, `first_axis_mean` is assumed
        """
        return BoostedClassifierSensitivityAnalyzer(
                self, sa_attr='splits',
                analyzer=self.__clf.get_sensitivity_analyzer(
                    **_dont_force_slaves(slave_kwargs)),
                **kwargs)

    partitioner = property(fget=lambda x:x.__partitioner,
                        doc="Partitioner used by SplitClassifier")
    splitter = property(fget=lambda x:x.__splitter,
                        doc="Splitter used by SplitClassifier")


class MappedClassifier(ProxyClassifier):
    """`ProxyClassifier` which uses some mapper prior training/testing.

    `MaskMapper` can be used just a subset of features to
    train/classify.
    Having such classifier we can easily create a set of classifiers
    for BoostedClassifier, where each classifier operates on some set
    of features, e.g. set of best spheres from SearchLight, set of
    ROIs selected elsewhere. It would be different from simply
    applying whole mask over the dataset, since here initial decision
    is made by each classifier and then later on they vote for the
    final decision across the set of classifiers.
    """

    __sa_class__ = MappedClassifierSensitivityAnalyzer

    def __init__(self, clf, mapper, **kwargs):
        """Initialize the instance

        Parameters
        ----------
        clf : Classifier
          classifier based on which mask classifiers is created
        mapper
          whatever `Mapper` comes handy
        """
        ProxyClassifier.__init__(self, clf, **kwargs)

        self.__mapper = mapper
        """mapper to help us our with prepping data to
        training/classification"""


    def _train(self, dataset):
        """Train `MappedClassifier`
        """
        # first train the mapper
        # XXX: should training be done using whole dataset or just samples
        # YYY: in some cases labels might be needed, thus better full dataset
        self.__mapper.train(dataset)

        # for train() we have to provide dataset -- not just samples to train!
        wdataset = dataset.get_mapped(self.__mapper)
        if __debug__:
            debug('CLF', "Training %s having mapped dataset into %s",
                  (self, wdataset))
        ProxyClassifier._train(self, wdataset)


    def _untrain(self):
        """Untrain `FeatureSelectionClassifier`

        Has to untrain any known classifier
        """
        # untrain the mapper
        if self.__mapper is not None:
            self.__mapper.untrain()
        # let base class untrain as well
        super(MappedClassifier, self)._untrain()


    def _predict(self, dataset):
        """Predict using `MappedClassifier`
        """
        return ProxyClassifier._predict(self, self.__mapper.forward(dataset))


    def __str__(self):
        return _str(self, '%s-%s' % (self.mapper, self.clf))


    mapper = property(lambda x:x.__mapper, doc="Used mapper")



class FeatureSelectionClassifier(MappedClassifier):
    """This is nothing but a `MappedClassifier`.

    This class is only kept for (temporary) compatibility with old code.
    """
    __tags__ = [ 'does_feature_selection', 'meta' ]


class RegressionAsClassifier(ProxyClassifier):
    """Allows to use arbitrary regression for classification.

    Possible usecases:

     Binary Classification
      Any regression could easily be extended for binary
      classification. For instance using labels -1 and +1, regression
      results are quantized into labels depending on their signs
     Multiclass Classification
      Although most of the time classes are not ordered and do not
      have a corresponding distance matrix among them it might often
      be the case that there is a hypothesis that classes could be
      well separated in a projection to single dimension (non-linear
      manifold, or just linear projection).  For such use regression
      might provide necessary means of classification
    """

    distances = ConditionalAttribute(enabled=False,
        doc="Distances obtained during prediction")

    __sa_class__ = RegressionAsClassifierSensitivityAnalyzer

    def __init__(self, clf, centroids=None, distance_measure=None, **kwargs):
        """
        Parameters
        ----------
        clf : Classifier XXX Should become learner
          Regression to be used as a classifier.  Although it would
          accept any Learner, only providing regressions would make
          sense.
        centroids : None or dict of (float or iterable)
          Hypothesis or prior information on location/distance of
          centroids for each category, provide them.  If None -- during
          training it will choose equidistant points starting from 0.0.
          If dict -- keys should be a superset of labels of dataset
          obtained during training and each value should be numeric value
          or iterable if centroids are multidimensional and regression
          can do multidimensional regression.
        distance_measure : function or None
          What distance measure to use to find closest class label
          from continuous estimates provided by regression.  If None,
          will use Cartesian distance.
        """
        ProxyClassifier.__init__(self, clf, **kwargs)
        self.centroids = centroids
        self.distance_measure = distance_measure

        # Adjust tags which were copied from slave learner
        if self.__is_regression__:
            self.__tags__.pop(self.__tags__.index('regression'))

        # We can do any number of classes, although in most of the scenarios
        # multiclass performance would suck, unless there is a strong
        # hypothesis
        self.__tags__ += ['binary', 'multiclass', 'regression_based']

        # XXX No support for retrainable in RegressionAsClassifier yet
        if 'retrainable' in self.__tags__:
            self.__tags__.remove('retrainable')

        # Pylint/user friendliness
        #self._trained_ul = None
        self._trained_attrmap = None
        self._trained_centers = None


    def __repr__(self, prefixes=[]):
        if self.centroids is not None:
            prefixes = prefixes + ['centroids=%r'
                                   % self.centroids]
        if self.distance_measure is not None:
            prefixes = prefixes + ['distance_measure=%r'
                                   % self.distance_measure]
        return super(RegressionAsClassifier, self).__repr__(prefixes)


    def _train(self, dataset):
        targets_sa_name = self.get_space()
        targets_sa = dataset.sa[targets_sa_name]

        # May be it is an advanced one needing training.
        if hasattr(self.distance_measure, 'train'):
            self.distance_measure.train(dataset)

        # Centroids
        ul = dataset.sa[targets_sa_name].unique
        if self.centroids is None:
            # setup centroids -- equidistant points
            # XXX we might preferred -1/+1 for binary...
            centers = np.arange(len(ul), dtype=float)
        else:
            # verify centroids and assign
            if not set(self.centroids.keys()).issuperset(ul):
                raise ValueError, \
                      "Provided centroids with keys %s do not cover all " \
                      "labels provided during training: %s" \
                      % (self.centroids.keys(), ul)
            # override with superset
            ul = self.centroids.keys()
            centers = np.array([self.centroids[k] for k in ul])

        #self._trained_ul = ul
        # Map labels into indexes (not centers)
        # since later on we would need to get back (see ??? below)
        self._trained_attrmap = AttributeMap(
            map=dict([(l, i) for i,l in enumerate(ul)]),
            mapnumeric=True)
        self._trained_centers = centers

        # Create a shallow copy of dataset, and override labels
        # TODO: we could just bind .a, .fa, and copy only .sa
        dataset_relabeled = dataset.copy(deep=False)
        # ???:  may be we could just craft a monster attrmap
        #       which does min distance search upon to_literal ?
        dataset_relabeled.sa[targets_sa_name].value = \
            self._trained_attrmap.to_numeric(targets_sa.value)

        ProxyClassifier._train(self, dataset_relabeled)


    def _predict(self, dataset):
        # TODO: Probably we should forwardmap labels for target
        #       dataset so slave has proper statistics attached
        self.ca.estimates = regr_predictions \
                           = ProxyClassifier._predict(self, dataset)

        # Local bindings
        #ul = self._trained_ul
        attrmap = self._trained_attrmap
        centers = self._trained_centers
        distance_measure = self.distance_measure
        if distance_measure is None:
            distance_measure = cartesian_distance

        # Compute distances
        self.ca.distances = distances \
            = np.array([[distance_measure(s, c) for c in centers]
                       for s in regr_predictions])

        predictions = attrmap.to_literal(np.argmin(distances, axis=1))
        if __debug__:
            debug("CLF_", "Converted regression distances %s "
                  "into labels %s for %s", (distances, predictions, self))

        return predictions


    def _set_retrainable(self, value, **kwargs):
        if value:
            raise NotImplementedError, \
                  "RegressionAsClassifier wrappers are not yet retrainable"
        ProxyClassifier._set_retrainable(self, value, **kwargs)