Source

mtc / mtc.py

Full commit
  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
import copy
import numpy as np
import bottleneck

try:
    import theano
    import theano.tensor as T
except ImportError:
    pass

import Orange.data
import Orange.classification
import Orange.evaluation

import sklearn.cross_decomposition
import sklearn.linear_model

def is_regression(domain):
    all_disc = all(isinstance(v, Orange.data.variable.DiscreteVariable) for v in domain.class_vars)
    all_cont = all(isinstance(v, Orange.data.variable.ContinuousVariable) for v in domain.class_vars)
    assert all_disc or all_cont
    return all_cont

### Score ###
def mt_average_score(metric):
    '''
    Construct a multitarget metric. Evaluate each target separately and return the average score.

    :param metric: Metric function for a single target (e.g. `Orange.evaluation.ca`, `Orange.evaluation.auc`).

    **Examples**

	>>> import numpy as np
	>>> import mtc
	>>> import Orange
	>>> import Orange.classification.logistic_regression
	>>> def my_metric(actual, predicted):
	...     # predicted is a tuple of predicted values and predicted probabilites
	...     return np.mean(actual == predicted[0])
        ...
	>>> data = Orange.data.Table('emotions')
	>>> fitter = mtc.BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner())
	>>> model = fitter(data)
	>>> predicted = model(data, model.ValueProbs)
	>>> my_mtc_metric = mtc.mt_average_score(my_metric)
	>>> my_mtc_metric(data.Y, predicted)
        0.815626756605
    '''
    def f(Y, Y_hat):
        scores = []
        for j in range(Y.shape[1]):
            scores.append(metric(Y[:,j], (Y_hat[0][:,j], Y_hat[1][:,j])))
        return bottleneck.nanmean(scores)
    return f

ca_mt = mt_average_score(Orange.evaluation.ca)
auc_mt = mt_average_score(Orange.evaluation.auc)


### Wrappers ###
class SKFitter(Orange.classification.Fitter):
    def __init__(self, model, supports_multiclass=False):
        self.model = model
        self.supports_multiclass = supports_multiclass

    def fit(self, X, Y, W):
        if not self.supports_multiclass:
            Y = Y.ravel()
        self.model.fit(X, Y)
        return SKModel(self.model)

class SKModel(Orange.classification.Model):
    def __init__(self, model):
        self.model = model

    def predict(self, X):
        if is_regression(self.domain):
            return self.model.predict(X)
        else:
            try:
                return self.model.predict_proba(X)
            except AttributeError:
                # treat these as probabilites (if a Regressor wants to behave like a classifier)
                P = np.clip(self.model.predict(X), 0, 1)
                tup = 1 - P, P

                if P.ndim == 1:
                    return np.column_stack(tup)
                elif P.ndim == 2:
                    return np.dstack(tup)


### Methods ###

# Binary Relevacne #
class BRFitter(Orange.classification.Fitter):
    '''Binary relevance method.

    For a multitarget problem with `n` classes, train `n` independent models, one for each class.

    :param fitter: A single-target Orange fitter (e.q. `Orange.classification.logisti_regression.LogisticRegressionLearner()`).
    :type fitter: Orange.classification.Fitter

    **Examples**

        >>> import mtc
        >>> import Orange.classification.logistic_regression
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner())
        >>> model = fitter(data)
        >>> model(data)
        [[ 0.  0.  1.  0.  1.  0.]
         [ 1.  0.  0.  0.  0.  1.]
         [ 0.  0.  0.  0.  0.  1.]
         ..., 
         [ 0.  0.  1.  1.  1.  0.]
         [ 0.  0.  0.  0.  0.  1.]
         [ 0.  1.  1.  0.  0.  0.]]
    '''

    def __init__(self, fitter):
        self.supports_multiclass = True
        self.fitter = fitter

    def fit(self, X, Y, W):
        models = []
        for j in range(Y.shape[1]):
            m = copy.deepcopy(self.fitter)

            # Optimization -- building a Table from numpy is slow if not given a domain
            domain = Orange.data.Domain(self.domain.attributes, self.domain.class_vars[j])
            data = Orange.data.Table(domain, X, Y[:,j][:,None])

            models.append(m(data))
        return BRModel(models)

class BRModel(Orange.classification.Model):
    def __init__(self, models):
        self.models = models

    def predict(self, X):
        V = np.zeros((X.shape[0], len(self.domain.class_vars)))
        if is_regression(self.domain):
            for j, model in enumerate(self.models):
                V[:,j] = model(X, self.Value)
            return V
        else:
            max_card = max(len(c.values) for c in self.domain.class_vars)
            P = np.zeros((X.shape[0], len(self.domain.class_vars), max_card))
            for j, model in enumerate(self.models):
                V[:,j], P[:,j,:] = model(X, self.ValueProbs)
            return V, P


# Multilayer perceptron #
def rectified_linear(x):
    return T.maximum(0.0, x)

class NeuralNetwork:
    def __init__(self, input, scale, dropout=None):
        self.output = self.output_test = input
        self.scale = scale
        self.srng = T.shared_randomstreams.RandomStreams(seed=42)
        self.params = []
        self.params_init = []
        self.L2 = 0

        if dropout is not None:
            self.output *= self.srng.binomial(p=dropout, size=self.output.shape)
            self.output_test *= dropout

    def full(self, n_in, n_out, dropout, activation):
        W_init = np.random.normal(scale=self.scale, size=(n_in, n_out))
        b_init = np.zeros(n_out)
        self.params_init.extend([W_init, b_init])

        W = theano.shared(W_init, borrow=True)
        b = theano.shared(b_init, borrow=True)
        self.params.extend([W, b])

        self.L2 += (W**2).sum()

        self.output = activation(self.output.dot(W) + b)
        self.output_test = activation(self.output_test.dot(W) + b)
        if dropout is not None:
            self.output *= self.srng.binomial(p=dropout, size=self.output.shape)
            self.output_test *= dropout

class MLPFitter(Orange.classification.Fitter):
    '''Multilayer Perceptron

    Implements multilayer perceptrions with dropout, L2 regularization
    and sigmoid activation function. The weights are trained using
    mini-batch stochastic gradient descent. Requires 
    `Theano 0.6 <http://deeplearning.net/software/theano/>`_.

    Please make sure the features are on the same scale.

    :param layers: The number of units on each layer (including the number the number of units on the input and output layers). This parameter determines the number of hidden layers.
    :type layers: list
    :param dropout: The amount of dropout used per layer. A value of 0 implies no dropout and 1 implies we drop everything.
    :type dropout: list
    :param L2_reg: The amount of L2 regularization.
    :type L2_reg: float
    :param learning_rate: Learning rate in stochastic gradient descent.
    :type learning_rate: float
    :param iterations: Number of iterations of stochastic gradient descent. No other stopping mechanism is implemented at this time.
    :type iterations: int
    :param scale: Use normal distribution N(0, scale) to randomly initialize the weights.
    :type scale: float
    :param batch_size: Size of a batch in stochastic gradient descent.
    :type batch_size: int

    **Examples**

        >>> import numpy as np
        >>> import mtc
        >>> import Orange
        >>> data = Orange.data.Table('emotions')
        >>> data.X = (data.X - np.mean(data.X, axis=0)) / np.mean(data.X, axis=0)  # Don't forget to normalize your data
        >>> fitter = mtc.MLPFitter([data.X.shape[1], 50, data.Y.shape[1]], [0.8, 0.5, 1], 0.0001, 0.5, 500, 0.1, 10)
        >>> model = fitter(data)
        >>> model(data)
        [[0 0 1 0 0 0]
         [1 0 0 0 0 1]
         [0 0 0 0 0 1]
         ..., 
         [0 0 1 1 1 0]
         [0 0 0 0 0 1]
         [0 1 1 0 0 0]]
    '''

    def __init__(self, layers, dropout, L2_reg, learning_rate, iterations, scale, batch_size):
        self.supports_multiclass = True
        self.iterations = iterations
        self.batch_size = batch_size

        x = T.matrix()
        y = T.matrix()

        self.model = NeuralNetwork(input=x, scale=scale, dropout=dropout[0])

        for prev, next, drop in zip(layers, layers[1:], dropout[1:]):
            self.model.full(prev, next, drop, T.nnet.sigmoid)

        out_clipped = T.clip(self.model.output, 1e-15, 1 - 1e-15)
        cost = T.mean(T.nnet.binary_crossentropy(out_clipped, y)) + L2_reg * self.model.L2 / x.shape[0]

        updates = []
        for p in self.model.params:
            updates.append((p, p - learning_rate * T.grad(cost, p)))
        self.train_model = theano.function(inputs=[x, y], updates=updates)
        self.get_output = theano.function(inputs=[x], outputs=self.model.output_test)

    def fit(self, X_tr, y_tr, W):
        # reset params
        for p, v in zip(self.model.params, self.model.params_init):
            p.set_value(v)

        epoch = 0
        while epoch < self.iterations:
            epoch += 1
            for i in range(0, X_tr.shape[0] - self.batch_size + 1, self.batch_size):
                self.train_model(X_tr[i:i + self.batch_size], y_tr[i:i + self.batch_size])
        return MLPModel(self.get_output)


class MLPModel(Orange.classification.Model):
    def __init__(self, get_output):
        self.get_output = get_output

    def predict(self, X_te):
        y = self.get_output(X_te)
        return np.dstack((1 - y, y))


# Partial Least Squares Regression #
def PLSFitter(**kwargs):
    '''Partial least squares classifier

    Wraps `sklearn.cross_decomposition.PLSRegression <http://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.PLSRegression.html>`_.

    :param n_components: Number of components to keep.
    :type n_components: int
    :param scale: whether to scale the data.
    :type scale: boolean
    :param max_iter: the maximum number of iterations of the NIPALS inner loop.
    :type max_iter: int
    :param tol: Tolerance used in the iterative algorithm default 1e-06.
    :type tol: non-negative real

    **Examples**

        >>> import numpy as np
        >>> import mtc
        >>> import Orange
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.PLSFitter(n_components=5)
        >>> model = fitter(data)
        >>> model(data)
        [[0 0 1 0 0 0]
         [1 0 0 0 0 1]
         [0 0 0 0 0 1]
         ..., 
         [0 0 1 1 1 0]
         [0 0 0 0 0 0]
         [0 1 1 0 0 0]]

    '''
    fitter = SKFitter(sklearn.cross_decomposition.PLSRegression(**kwargs), supports_multiclass=True)
    return fitter


# Curds & Whey #
def curds_whey_fit(X, Y, type='population', rank=0, lambda1=0, lambda2=0,
                   fitter=SKFitter(sklearn.linear_model.LinearRegression(), supports_multiclass=True)):
    _, _, Rmat, Rmatinv, c = rcc(X, Y, lambda1, lambda2)
    #assert np.allclose(Rmat.dot(Rmatinv), np.eye(Rmat.shape[0]))

    N, p = X.shape
    q = Y.shape[1]
    r = p / N
    c2 = c**2
    if type == 'population':
        d = c2 / (c2 + r * (1 - c2))
    elif type == 'gcv':
        d = (1 - r) * (c2 - r) / ((1 - r)**2 * c2 + r**2 * (1 - c2))
    elif type == 'reduced_rank':
        d = (np.arange(Y.shape[1]) < rank)
    elif type == 'ficyreg':
        t = (p - q - 1) / N
        d = (c2 - t) / (c2 * (1 - t))
    d[d < 0] = 0

    # TODO: optimize -- manually build domain
    data = Orange.data.Table(X, Y.dot(Rmat))
    model = fitter(data)
    return model, Rmatinv, d

def curds_whey_predict(X, model, Rmatinv, d):
    return (model(X) * d).dot(Rmatinv)

class CurdsWheyFitter(Orange.classification.Fitter):
    '''
    Curds and Whey Procedure

    Implements Breiman's and Friedman's Curds and Whey method. If 
    `lambda1 = lambda2 = 0` this is equivalent to the original method. When the
    number of features or targets is greater then the number of examples,
    the method will not be able to comput the inverse of `X' * X` or
    `Y' * Y`, in which case use the parameters `lambda1` and `lambda2`
    to set the appropriate level of regularization.

    :param type: How to compute shrinkage.
    :type type: {'population', 'gcv'}
    :param lambda1: Regularization parameter for X (:obj:`mtc.rcc`).
    :type lambda1: non-negative real
    :param lambda2: Regularization parameter for Y (:obj:`mtc.rcc`).
    :type lambda2: non-negative real

    **Examples**

        >>> import mtc
        >>> import Orange
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.CurdsWheyClassifierFitter(type='population', lambda1=0, lambda2=0)
        >>> model = fitter(data)
        >>> model(data)
        [[0 0 1 0 0 0]
         [1 0 0 0 0 1]
         [0 0 0 0 0 1]
         ..., 
         [0 0 1 1 1 0]
         [0 0 0 0 0 1]
         [0 0 0 0 0 0]]

    **References**

    - Breiman, Friedman, *"Predicting multivariate responses in multiple linear regression"*, Journal of the Royal Statistical Society: Series B (Statistical Methodology), Volume 59, Issue 1, pages 3–54, 1997.
    '''
    def __init__(self, type='population', lambda1=0, lambda2=0):
        self.supports_multiclass = True
        self.type = type
        self.lambda1 = lambda1
        self.lambda2 = lambda2

    def fit(self, X, Y, W):
        args = curds_whey_fit(X, Y, type=self.type, lambda1=self.lambda1, lambda2=self.lambda2)
        return CurdsWheyModel(args)

class CurdsWheyModel(Orange.classification.Model):
    def __init__(self, args):
        self.args = args

    def predict(self, X):
        if is_regression(self.domain):
            return curds_whey_predict(X, *self.args)
        else:
            P = np.clip(curds_whey_predict(X, *self.args), 0, 1)
            return np.dstack((1 - P, P))


class _CurdsWheyFitter(Orange.classification.Fitter):
    def __init__(self, type='population'):
        self.supports_multiclass = True
        self.type = type

    def fit(self, X, Y, W=None):
        N, p = X.shape
        r = float(p) / N

        YY_ = np.linalg.inv(Y.T.dot(Y))
        XX_ = np.linalg.inv(X.T.dot(X))
        Q = YY_.dot(Y.T).dot(X).dot(XX_).dot(X.T).dot(Y)
        c2, T = np.linalg.eig(Q)
        T = T.T

        if self.type == 'population':
            D = np.diag(c2 / (c2 + r * (1 - c2)))
        elif self.type == 'gcv':
            D = np.diag((1 - r) * (c2 - r) / ((1 - r)**2 * c2 + r**2 * (1 - c2)))
        D[D < 0] = 0

        B = np.linalg.inv(T).dot(D).dot(T)
        A = XX_.dot(X.T).dot(Y).T

        return _CurdsWheyModel(B.dot(A))

class _CurdsWheyModel(Orange.classification.Model):
    def __init__(self, T):
        self.T = T

    def predict(self, X_te):
        if is_regression(self.domain):
            return X_te.dot(self.T.T)
        else:
            P = np.clip(X_te.dot(self.T.T), 0, 1)
            return np.dstack((1 - P, P))

# MT Stacking #
class MTStackFitter(Orange.classification.Fitter):
    """Multitarget Stacking

    This method implements Wolpret's stacked generalization of a single fitter. 

    :param fitter: This fitter is used to learn the initial mapping from X to Y.
    :type fitter: Orange.classification.Fitter
    :param stacker: This fitter is used for stacking.
    :type stacker: Orange.classification.Fitter
    :param cv: The cross validation indices used for stacking.
    :type cv: function

    **Examples**

        >>> import mtc
        >>> import Orange.classification.logistic_regression
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.MTStackFitter(
        ...     fitter=mtc.BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner(1)),
        ...     stacker=mtc.BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner(0.1)),
        ...     cv=Orange.evaluation.KFold(5)
        ... )
        >>> model = fitter(data)
        >>> model(data)
        [[ 0.  0.  1.  0.  1.  0.]
         [ 1.  0.  0.  0.  0.  1.]
         [ 0.  0.  0.  0.  0.  1.]
         ..., 
         [ 0.  0.  1.  1.  1.  0.]
         [ 0.  0.  0.  0.  0.  1.]
         [ 0.  0.  1.  0.  0.  0.]]

    **References**
     - Wolpert, *"Stacked Generalization"*, Neural Networks, 5(2), pp. 241-259., 1992
    """
    def __init__(self, fitter, stacker, cv=Orange.evaluation.KFold(5)):
        self.supports_multiclass = True
        self.fitter = fitter
        self.stacker = stacker
        self.cv = cv

    def fit(self, X, Y, W=None):
        regression = is_regression(self.domain)
        XX = np.zeros_like(Y)
        YY = np.zeros_like(Y)
        data = Orange.data.Table(self.domain, X, Y)
        for tr, te in self.cv(Y):
            cls = self.fitter(data[tr])
            if regression:
                XX[te] = cls(X[te])
            else:
                XX[te] = cls(X[te], cls.Probs)[:,:,1]
            YY[te] = Y[te]
        cls = self.fitter(data)
        stack_data = Orange.data.Table(XX, YY)
        stacker_cls = self.stacker(stack_data)

        return MTStackModel(cls, stacker_cls)


class MTStackModel(Orange.classification.Model):
    def __init__(self, cls, stacker_cls):
        self.cls = cls
        self.stacker_cls = stacker_cls

    def predict(self, X):
        if is_regression(self.domain):
            return self.stacker_cls(self.cls(X))
        else:
            return self.stacker_cls(self.cls(X, self.Probs)[:,:,1], self.ValueProbs)


# Regularized Canonical Correlation #
def geigen(Amat, Bmat, Cmat):
    '''matlab geigen function'''
    p = Bmat.shape[0]
    q = Cmat.shape[0]
    Bmat = (Bmat + Bmat.T) / 2
    Cmat = (Cmat + Cmat.T) / 2
    Bfac = np.linalg.cholesky(Bmat).T
    Cfac = np.linalg.cholesky(Cmat).T
    Bfacinv = np.linalg.inv(Bfac)
    Cfacinv = np.linalg.inv(Cfac)
    Dmat = Bfacinv.T.dot(Amat).dot(Cfacinv)
    if p >= q:
        u, values, v = np.linalg.svd(Dmat)
        Lmat = Bfacinv.dot(u)
        Lmatinv = u.T.dot(Bfac)
        Mmat = Cfacinv.dot(v.T)
        Mmatinv = v.dot(Cfac)
    else:
        u, values, v = np.linalg.svd(Dmat.T)
        Lmat = Bfacinv.dot(v.T)
        Lmatinv = v.dot(Bfac)
        Mmat = Cfacinv.dot(u)
        Mmatinv = u.T.dot(Cfac)
    return Lmat, Lmatinv, Mmat, Mmatinv, values

def rcc(X, Y, lambda1, lambda2):
    '''Regularized Canonical Correlation Analysis

    Rewrite of the `rcc` function in `CCA package <http://cran.r-project.org/web/packages/CCA/index.html>`_ for R.

    :param X: matrix containing the X coordinates
    :type X: array-like, shape = [n_samples, n_features]
    :param Y: matrix containing the Y coordinates
    :type Y: array-like, shape = [n_samples, n_responses]
    :param lambda1: Regularization parameter for X
    :type lambda1: non-negative real
    :param lambda2: Regularization parameter for Y
    :type lambda2: non-negative real
    :returns: (X_weights, X_weights_inv, Y_score, Y_score_inv, correlations)

    **Examples**

        >>> import mtc
        >>> import Orange
        >>> data = Orange.data.Table('emotions')
        >>> X_weights, _, Y_weights, _, _ = mtc.rcc(data.X, data.Y, 0.1, 0.1)
    '''
    #xcenter = X.mean(axis=0)
    #ycenter = Y.mean(axis=0)
    #X = X - xcenter
    #Y = Y - ycenter

    assert X.shape[0] == Y.shape[0]
    Cxx = X.T.dot(X) / (X.shape[0] - 1) + lambda1 * np.eye(X.shape[1])
    Cyy = Y.T.dot(Y) / (X.shape[0] - 1) + lambda2 * np.eye(Y.shape[1])
    Cxy = X.T.dot(Y) / (X.shape[0] - 1)
    return geigen(Cxy, Cxx, Cyy)

# Reduced-rank regression #
class ReducedRankFitter(Orange.classification.Fitter):
    '''Reduced-Rank classification

    If `lambda1 = lambda2 = 0` this is equivalent to the original
    method. When the number of features or targets is greater then the
    number of examples, the method will not be able to comput the inverse
    of `X' * X` or `Y' * Y`, in which case use the parameters `lambda1`
    and `lambda2` to set the appropriate level of regularization.

    :param rank: Use this many CCA dimensions.
    :type rank: non-negative int
    :param lambda1: Regularization parameter for X.
    :type lambda1: non-negative real
    :param lambda2: Regularization parameter for Y.
    :type lambda2: non-negative real

    **Examples**

        >>> import mtc
        >>> import Orange.classification.logistic_regression
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.ReducedRankClassifierFitter(rank=5)
        >>> model = fitter(data)
        >>> model(data)
        [[0 0 1 0 1 0]
         [0 0 0 0 0 1]
         [1 0 0 0 0 1]
         ..., 
         [0 0 1 1 1 0]
         [0 0 0 0 0 1]
         [0 0 1 0 0 0]]

    **References**

    - Izenman, *"Reduced-Rank Regression for the Multivariate Linear Model"*, Journal of Multivariate Analysis, 5, 248-262, 1975.
    - Hastie, Tibshirani, Friedman, *"Elements of Statistical Learning Ed. 2"*, Springer, 2009
    '''

    def __init__(self, rank=2, lambda1=0, lambda2=0):
        self.supports_multiclass = True
        self.rank = rank
        self.lambda1 = lambda1
        self.lambda2 = lambda2

    def fit(self, X, Y, W):
        args = curds_whey_fit(X, Y, type='reduced_rank', rank=self.rank, lambda1=self.lambda1, lambda2=self.lambda2)
        return ReducedRankModel(args)

class ReducedRankModel(Orange.classification.Model):
    def __init__(self, args):
        self.args = args

    def predict(self, X):
        if is_regression(self.domain):
            return curds_whey_predict(X, *self.args)
        else:
            P = np.clip(curds_whey_predict(X, *self.args), 0, 1)
            return np.dstack((1 - P, P))

# Filtered Canonical y-variate Regression #
class FICYREGFitter(Orange.classification.Fitter):
    '''Filtered Canonical y-variate Regression

    If `lambda1 = lambda2 = 0` this is equivalent to the original
    method. When the number of features or targets is greater then the
    number of examples, the method will not be able to comput the inverse
    of `X' * X` or `Y' * Y`, in which case use the parameters `lambda1`
    and `lambda2` to set the appropriate level of regularization.

    :param lambda1: Regularization parameter for X.
    :type lambda1: non-negative real
    :param lambda2: Regularization parameter for Y.
    :type lambda2: non-negative real

    **Examples**

        >>> import mtc
        >>> import Orange.classification.logistic_regression
        >>> data = Orange.data.Table('emotions')
        >>> fitter = mtc.FICYREGClassifierFitter()
        >>> model = fitter(data)
        >>> model(data)
        [[0 0 1 0 0 0]
         [1 0 0 0 0 1]
         [0 0 0 0 0 1]
         ..., 
         [0 0 1 1 1 0]
         [0 0 0 0 0 1]
         [0 0 1 0 0 0]]

    **References**

    - van der Merwe, Zidek, *"Multivariate regression analysis and canonical variates."* Can. J. Stat., 8:27-40, 1980.
    '''
    def __init__(self, lambda1=0, lambda2=0):
        self.supports_multiclass = True
        self.lambda1 = lambda1
        self.lambda2 = lambda2

    def fit(self, X, Y, W):
        args = curds_whey_fit(X, Y, type='ficyreg', lambda1=self.lambda1, lambda2=self.lambda2)
        return FICYREGModel(args)

class FICYREGModel(Orange.classification.Model):
    def __init__(self, args):
        self.args = args

    def predict(self, X):
        if is_regression(self.domain):
            return curds_whey_predict(X, *self.args)
        else:
            P = np.clip(curds_whey_predict(X, *self.args), 0, 1)
            return np.dstack((1 - P, P))



if __name__ == '__main__':
    import sklearn.linear_model
    import sklearn.svm
    import sklearn.cross_validation
    import Orange.classification.logistic_regression

    np.random.seed(42)

    #data = Orange.data.Table('iris')
    #data = Orange.data.Table(data.X, data.Y == 0)
    #model = SKLearner(sklearn.linear_model.LogisticRegression())
    #print(Orange.evaluation.cross_validation(model, data, Orange.evaluation.CA, Orange.evaluation.KFold()))

    #data = Orange.data.Table('emotions')
    #data.X = (data.X - np.mean(data.X, axis=0)) / np.mean(data.X, axis=0)

    #cls = model(data)
    #print(cls(data, cls.Probs)[:,:,1])

    data = Orange.data.Table(np.random.random((100, 10)), np.random.random((100, 3)))



    #model = BRFitter(SKFitter(sklearn.linear_model.LogisticRegression()))
    #model = MLPFitter([data.X.shape[1], 50, data.Y.shape[1]], [0.8, 0.5, 1], 0.0, 0.5, 500, 0.1, 5)
    model = PLSFitter(n_components=2)
    #model = CurdsWheyClassifierFitter()
    #model = CurdsWhey2ClassifierFitter(lambda1=0.1)
    #model = ReducedRankClassifierFitter(rank=5)
    #model = FICYREGClassifierFitter()


    cls = model(data)
    print(cls(data))

    #model = MTStackFitter(
    #    BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner(1)),
    #    BRFitter(Orange.classification.logistic_regression.LogisticRegressionLearner(0.1)),
    #    Orange.evaluation.KFold(5),
    #)

    #print(Orange.evaluation.cross_validation(model, data, auc_mt, Orange.evaluation.TTVSplit(n_repeats=5)))

    #model = sklearn.linear_model.LogisticRegression()
    #X = data.X
    #Y = data.Y
    #scores = []
    #for tr, te in sklearn.cross_validation.KFold(X.shape[0], 5):
    #    for j in range(Y.shape[1]):
    #        y = Y[:,j]
    #        model.fit(X[tr], y[tr])
    #        scores.append(sklearn.metrics.roc_auc_score(y[te],model.predict(X[te])))
    #print(np.mean(scores))