orange-multitarget / _multitarget / chain.py

  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
import Orange.core as orange
import Orange
import random
import copy
from operator import add

class ClassifierChainLearner(orange.Learner):
    """
    Expands single class classification techniques into multi-target classification techniques by chaining the classification
    data. A learner is constructed for each of the class variables in a random or given order. The data for each learner are
    the features extended by all previously classified variables. This chaining passes the class informationd between
    classifiers and allows class correlations to be taken into account.
    TODO: cite weka source?

    :param learner: A single class learner that will be extended by chaining.
    :type learner: :class:`Orange.core.Learner`

    :param rand: random generator used in bootstrap sampling. If None (default), 
        then ``random.Random(42)`` is used.

    :param callback: a function to be called after every iteration of
            induction of classifier. The call returns a parameter
            (from 0.0 to 1.0) that provides an estimate
            of completion of the learning progress.

    :param name: learner name.
    :type name: string

    :rtype: :class:`Orange.ensemble.forest.RandomForestClassifier` or 
            :class:`Orange.ensemble.forest.RandomForestLearner`

    """

    def __new__(cls, data=None, weight = 0, **kwargs):
        self = Orange.classification.Learner.__new__(cls, **kwargs)
        if data:   
            self.__init__(**kwargs)
            return self(data,weight)
        else:
            return self

    def __init__(self, learner=None, name="Classifier Chain", rand=None, callback=None, class_order=None):
        self.name = name
        self.rand = rand
        self.callback = callback
        self.class_order = class_order

        if not learner:
            raise TypeError("Wrong specification, learner not defined")
        else:
            self.learner = learner

        if not self.rand:
            self.rand = random.Random(42)

        self.randstate = self.rand.getstate()
           

    def __call__(self, instances, weight=0, class_order=None):
        """
        Learn from the given table of data instances.
        
        :param instances: data for learning.
        :type instances: class:`Orange.data.Table`

        :param weight: weight.
        :type weight: int

        :param class_order: list of descriptors of class variables
        :type class_order: list of :class:`Orange.feature.Descriptor`

        :rtype: :class:`Orange.ensemble.chain.ClassifierChain`
        """

        instances = Orange.data.Table(instances.domain, instances) # bypasses ownership

        self.rand.setstate(self.randstate) 
        n = len(instances)
        m = len(instances.domain.class_vars)
        progress = 0.0

        classifiers = [None for _ in xrange(m)]
        domains = [None for _ in xrange(m)]
        orig_domain = copy.copy(instances.domain)

        if self.class_order and not class_order:
            class_order = self.class_order
        elif not class_order:
            class_order = [cv for cv in instances.domain.class_vars]
            self.rand.shuffle(class_order)
        print [cv.name for cv in class_order]
        learner = self.learner

        for i in range(m):
            # sets one of the class_vars as class_var
            instances.pick_class(class_order[i])            

            # save domains for classification
            domains[i] = Orange.data.Domain([d for d in instances.domain])

            classifiers[i] = learner(instances, weight)
            
            # updates domain to include class_var in features
            instances.change_domain(Orange.data.Domain(instances.domain, False, \
                class_vars=instances.domain.class_vars))

            if self.callback:
                progress+=1
                self.callback(progress / m)

        return ClassifierChain(classifiers=classifiers, class_order=class_order, domains=domains, name=self.name, orig_domain=orig_domain)


class ClassifierChain(orange.Classifier):
    """
    Uses the classifiers induced by the :obj:`ClassifierChainLearner`. An input
    instance is classified into the class with the most frequent vote.
    However, this implementation returns the averaged probabilities from
    each of the trees if class probability is requested.

    It should not be constructed manually. TODO: ask about this
    
    :param classifiers: a list of classifiers to be used.
    :type classifiers: list
    
    
    
    :param domains: the domain of the learning set.
    :type domain: :class:`Orange.data.Domain`
    
    :param class_var: the class feature.
    :type class_var: :class:`Orange.feature.Descriptor`

    :param class_vars: the multi-target class features.
    :type class_vars: list of :class:`Orange.feature.Descriptor`

    :param name: name of the resulting classifier.
    :type name: str

    """

    def __init__(self, classifiers, class_order, domains, name, orig_domain):
        self.classifiers = classifiers
        self.class_order = class_order
        self.name = name
        self.domains = domains
        self.orig_domain = orig_domain

    def __call__(self, instance, result_type = orange.GetValue):
        """
        :param instance: instance to be classified.
        :type instance: :class:`Orange.data.Instance`
        
        :param result_type: :class:`Orange.classification.Classifier.GetValue` or \
              :class:`Orange.classification.Classifier.GetProbabilities` or
              :class:`Orange.classification.Classifier.GetBoth`
        
        :rtype: :class:`Orange.data.Value`, 
              :class:`Orange.statistics.Distribution` or a tuple with both
        """

        inst = [v for v in instance]
        values = {cv:None for cv in instance.domain.class_vars}
        probs = {cv:None for cv in instance.domain.class_vars}



        for i in range(len(self.class_order)):
            # add blank class for classification

            inst = Orange.data.Instance(self.domains[i],[v for v in inst] + ['?'])
  
            res = self.classifiers[i](inst, orange.GetBoth)
            values[self.class_order[i]] = res[0]
            probs[self.class_order[i]] = res[1]
            inst[-1] = res[0] # set the classified value for chaining

        # sort values and probabilites to original order
        values = [values[cv] for cv in self.orig_domain.class_vars]
        probs = [probs[cv] for cv in self.orig_domain.class_vars]

        if result_type == orange.GetValue: return tuple(values)
        elif result_type == orange.GetProbabilities: return tuple(probs)
        else: 
            return [tuple(values),tuple(probs)]

    def __reduce__(self):
        return type(self), (self.classifiers, self.class_order, self.domains, self.name, self.orig_domain), dict(self.__dict__)


class EnsembleClassifierChainLearner(orange.Learner):
    """
    Expands single class classification techniques into multi-target classification techniques by chaining the classification
    data. A learner is constructed for each of the class variables in a random or given order. The data for each learner are
    the features extended by all previously classified variables. This chaining passes the class informationd between
    classifiers and allows class correlations to be taken into account.
    TODO: cite weka source?

    :param learner: A single class learner that will be extended by chaining.
    :type learner: :class:`Orange.core.Learner`

    :param rand: random generator used in bootstrap sampling. If None (default), 
        then ``random.Random(42)`` is used.

    :param callback: a function to be called after every iteration of
            induction of classifier. The call returns a parameter
            (from 0.0 to 1.0) that provides an estimate
            of completion of the learning progress.

    :param name: learner name.
    :type name: string

    :rtype: :class:`Orange.ensemble.forest.RandomForestClassifier` or 
            :class:`Orange.ensemble.forest.RandomForestLearner`
    """

    def __new__(cls, data=None, weight = 0, **kwargs):
        self = Orange.classification.Learner.__new__(cls, **kwargs)
        if data:   
            self.__init__(**kwargs)
            return self(data,weight)
        else:
            return self

    def __init__(self, n_chains=50, sample_size=0.25, learner=None, name="Ensemble CChain", rand=None, callback=None):
        self.n_chains = n_chains
        self.sample_size = sample_size
        self.name = name
        self.rand = rand
        self.callback = callback

        if not learner:
            raise TypeError("Wrong specification, learner not defined")
        else:
            self.learner = learner

        if not self.rand:
            self.rand = random.Random(42)

        self.randstate = self.rand.getstate()

    def __call__(self, instances, weight=0):
        """
        """

        ind = Orange.data.sample.SubsetIndices2(p0=1-self.sample_size)
        indices = ind(instances)
        class_order = [cv for cv in instances.domain.class_vars]
        classifiers = []

        for i in range(self.n_chains):
            #randomize chain ordering and subset of instances
            self.rand.shuffle(class_order)
            self.rand.shuffle(indices)
            data = instances.select_ref(indices,1)

            learner = ClassifierChainLearner(learner = self.learner, rand=self.rand) # TODO might work in one step

            classifiers.append(learner(data, weight, copy.copy(class_order)))

            if self.callback:
                self.callback((i+1.)/self.n_chains)

        return EnsembleClassifierChain(classifiers=classifiers, name=self.name)

class EnsembleClassifierChain(orange.Classifier):
    """
    Uses the classifiers induced by the :obj:`EnsembleClassifierChainLearner`. An input
    instance is classified into the class with the most frequent vote.
    However, this implementation returns the averaged probabilities from
    each of the trees if class probability is requested.

    It should not be constructed manually. TODO: ask about this
    
    When constructed manually, the following parameters have to
    be passed:

    :param classifiers: a list of classifiers to be used.
    :type classifiers: list
    
    
    
    :param domains: the domain of the learning set.
    :type domain: :class:`Orange.data.Domain`
    
    :param class_var: the class feature.
    :type class_var: :class:`Orange.feature.Descriptor`

    :param class_vars: the multi-target class features.
    :type class_vars: list of :class:`Orange.feature.Descriptor`

    :param name: name of the resulting classifier.
    :type name: str

    """

    def __init__(self, classifiers, name):
        self.classifiers = classifiers
        self.name = name

    def __call__(self, instance, result_type = orange.GetValue):
        """
        :param instance: instance to be classified.
        :type instance: :class:`Orange.data.Instance`
        
        :param result_type: :class:`Orange.classification.Classifier.GetValue` or \
              :class:`Orange.classification.Classifier.GetProbabilities` or
              :class:`Orange.classification.Classifier.GetBoth`
        
        :rtype: :class:`Orange.data.Value`, 
              :class:`Orange.statistics.Distribution` or a tuple with both
        """

        class_vars = instance.domain.class_vars

        # get results to avoid multiple calls
        res_both = [c(instance, orange.GetBoth) for c in self.classifiers]

        mt_prob = []
        mt_value = []

        for varn in xrange(len(class_vars)):

            class_var = class_vars[varn]
            # handle discreete class
        
            if class_var.var_type == Orange.feature.Discrete.Discrete:

                # voting for class probabilities
                if result_type == orange.GetProbabilities or result_type == orange.GetBoth:
                    prob = [0.] * len(class_var.values)
                    for r in res_both:
                        a = [x for x in r[1][varn]]
                        prob = map(add, prob, a)
                    norm = sum(prob)
                    cprob = Orange.statistics.distribution.Discrete(class_var)
                    for i in range(len(prob)):
                        cprob[i] = prob[i]/norm
                
                # voting for crisp class membership, notice that
                # this may not be the same class as one obtaining the
                # highest probability through probability voting
                if result_type == orange.GetValue or result_type == orange.GetBoth:
                    cfreq = [0] * len(class_var.values)
                    for r in res_both:
                        cfreq[int(r[0][varn])] += 1
                    index = cfreq.index(max(cfreq))
                    cvalue = Orange.data.Value(class_var, index)
            
                if result_type == orange.GetValue: mt_value.append(cvalue)
                elif result_type == orange.GetProbabilities: mt_prob.append(cprob)
                else: 
                    mt_value.append(cvalue)
                    mt_prob.append(cprob)
        
            else:
                # Handle continuous class
        
                # voting for class probabilities
                if result_type == orange.GetProbabilities or result_type == orange.GetBoth:
                    probs = [ r for r in res_both]
                    cprob = dict()
      
                    for val,prob in probs:
                        if prob[varn] != None: #no probability output
                            a = dict(prob[varn].items())
                        else:
                            a = { val[varn].value : 1. }
                        cprob = dict( (n, a.get(n, 0)+cprob.get(n, 0)) for n in set(a)|set(cprob) )
                    cprob = Orange.statistics.distribution.Continuous(cprob)
                    cprob.normalize()
                
                # gather average class value
                if result_type == orange.GetValue or result_type == orange.GetBoth:
                    values = [r[0][varn] for r in res_both]
                    cvalue = Orange.data.Value(class_var, sum(values) / len(self.classifiers))
            
                if result_type == orange.GetValue: mt_value.append(cvalue)
                elif result_type == orange.GetProbabilities: mt_prob.append(cprob)
                else: 
                    mt_value.append(cvalue)
                    mt_prob.append(cprob)
                    
        if result_type == orange.GetValue: return tuple(mt_value)
        elif result_type == orange.GetProbabilities: return tuple(mt_prob)
        else: 
            return [tuple(mt_value),tuple(mt_prob)]

    def __reduce__(self):
        return type(self), (self.classifiers, self.class_order, self.domains, self.name), dict(self.__dict__)


if __name__ == '__main__':
    data = Orange.data.Table('test4')
    l=ClassifierChainLearner(learner = Orange.classification.tree.SimpleTreeLearner, name="CC T")
    res = Orange.evaluation.testing.cross_validation([l],data,folds=2)

    exit()

    print "STARTED"
    import time
    global_timer = time.time()
    data = Orange.data.Table('bridges.v2.nm')
    #data = Orange.data.Table('bridges.v2.nm')
    cl3 = EnsembleClassifierChainLearner(learner = Orange.classification.tree.SimpleTreeLearner, n_chains=50, sample_size=0.25, name="ECC T", rand = random.seed(time.time()))
    cl4 = EnsembleClassifierChainLearner(learner = Orange.classification.majority.MajorityLearner, n_chains=50, sample_size=0.25, name="ECC M", rand = random.seed(time.time()))
    cl1 = ClassifierChainLearner(learner = Orange.classification.tree.SimpleTreeLearner, name="CC T")
    cl2 = ClassifierChainLearner(learner = Orange.classification.majority.MajorityLearner, name="CC M")
    l1 = Orange.multitarget.tree.MultiTreeLearner()
    l2 = Orange.multitarget.pls.PLSRegressionLearner()
    l3 = Orange.ensemble.forest.RandomForestLearner(base_learner=Orange.multitarget.tree.MultiTreeLearner(), trees=50, name="RF MT" )

    #l =  EnsembleClassifierChainLearner(learner = Orange.classification.tree.SimpleTreeLearner, n_chains=3, name="ECC T")
    #l = Orange.multitarget.tree.MultiTreeLearner()
    #l = EnsembleClassifierChainLearner(learner = Orange.classification.majority.MajorityLearner, n_chains=3, name="ECC M")
    # cross_validation not working
    res = Orange.evaluation.testing.cross_validation([cl1,cl2,cl3,cl4,l1,l2,l3],data,folds=2)
    #res = Orange.evaluation.testing.cross_validation([l],data,folds=5)

    scores = Orange.evaluation.scoring.mt_average_score(res,Orange.evaluation.scoring.RMSE)
   
    print scores
    print res.classifierNames
    for i in range(len(scores)):
        print res.classifierNames[i], scores[i]

    print "CA"
    scores = Orange.evaluation.scoring.mt_average_score(res,Orange.evaluation.scoring.CA)
    print scores
    print res.classifierNames
    for i in range(len(scores)):
        print res.classifierNames[i], scores[i]


    #indices = Orange.data.sample.SubsetIndices2(data,0.25)
    #data_learn = data.select(indices,1)
    #data_test = data.select(indices,0)

    #c1=cl3(data_learn)
    #c2=l1(data_learn)
    #
    #res = Orange.evaluation.testing.test_on_data([c1, c2],data_test)
    #print Orange.evaluation.scoring.mt_average_score(res,Orange.evaluation.scoring.RMSE)

    print "--DONE %.2f --" % (time.time()-global_timer)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.