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
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


### Score ###
def mt_average_score(metric):
    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, regressor=False, supports_multiclass=False):
        self.model = model
        self.regressor = regressor
        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, self.regressor)

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

    def predict(self, X):
        if self.regressor:
            return self.model.predict(X)
        else:
            try:
                return self.model.predict_proba(X)
            except AttributeError:
                # treat these as probabilites (if a Regressor want's 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):
    def __init__(self, learner):
        self.supports_multiclass = True
        self.learner = learner

    def fit(self, X, Y, W):
        models = []

        for j in range(Y.shape[1]):
            m = copy.deepcopy(self.learner)

            # 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):
        max_card = max(len(c.values) for c in self.domain.class_vars)
        V = np.zeros((X.shape[0], len(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):
    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 PLSClassifierFitter(**kwargs):
    fitter = SKFitter(sklearn.cross_decomposition.PLSRegression(**kwargs), supports_multiclass=True)
    fitter.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.Ridge(), supports_multiclass=True, regressor=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 CurdsWhey2ClassifierFitter(Orange.classification.Fitter):
    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 CurdsWhey2ClassifierModel(args)

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

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


class CurdsWheyClassifierFitter(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 CurdsWheyClassifierModel(B.dot(A))

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

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

# MT Stacking #
class MTStackFitter(Orange.classification.Fitter):
    def __init__(self, model, stacker, cv=Orange.evaluation.KFold(5)):
        self.supports_multiclass = True
        self.model = model
        self.stacker = stacker
        self.cv = cv

    def fit(self, X, Y, W=None):
        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.model(data[tr])
            XX[te] = cls(X[te], cls.Probs)[:,:,1]
            YY[te] = Y[te]
        cls = self.model(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):
        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):
    '''R package cca function'''
    #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 ReducedRankClassifierFitter(Orange.classification.Fitter):
    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 ReducedRankClassifierModel(args)

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

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

# Filtered Canonical y-variate Regression #
class FICYREGClassifierFitter(Orange.classification.Fitter):
    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 FICYREGClassifierModel(args)

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

    def predict(self, X):
        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

    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')



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


    #model = BRFitter(SKFitter(sklearn.linear_model.Ridge()))
    #model = PLSClassifierFitter(n_components=2)
    #model = CurdsWheyClassifierFitter()
    #model = CurdsWhey2ClassifierFitter(lambda1=0.1)
    #model = ReducedRankClassifierFitter(rank=5, lambda1=0.1, lambda2=0.1)
    #model = FICYREGClassifierFitter()


    #model = MTStackFitter(
    #    BRFitter(SKFitter(sklearn.linear_model.LogisticRegression())),
    #    BRFitter(SKFitter(sklearn.linear_model.LogisticRegression()))
    #)

    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))