source: orange/docs/tutorial/rst/code/bagging.py @ 11054:eca373fb96a9

Revision 11054:eca373fb96a9, 1.6 KB checked in by blaz <blaz.zupan@…>, 16 months ago (diff)

new tutorial (refresh after removal of old files)

Line 
1# Description: An implementation of bagging (only bagging class is defined here)
2# Category:    modelling
3# Referenced:  c_bagging.htm
4
5import random
6import Orange
7
8def Learner(examples=None, **kwds):
9    learner = apply(Learner_Class, (), kwds)
10    if examples:
11        return learner(examples)
12    else:
13        return learner
14
15class Learner_Class:
16    def __init__(self, learner, t=10, name='bagged classifier'):
17        self.t = t
18        self.name = name
19        self.learner = learner
20
21    def __call__(self, examples, weight=None):
22        r = random.Random()
23        r.seed(0)
24
25        n = len(examples)
26        classifiers = []
27        for i in range(self.t):
28            selection = []
29            for j in range(n):
30                selection.append(r.randrange(n))
31            data = examples.getitems(selection)
32            classifiers.append(self.learner(data))
33           
34        return Classifier(classifiers = classifiers, name=self.name, domain=examples.domain)
35
36class Classifier:
37    def __init__(self, **kwds):
38        self.__dict__.update(kwds)
39
40    def __call__(self, example, resultType = Orange.classification.Classifier.GetValue):
41        freq = [0.] * len(self.domain.classVar.values)
42        for c in self.classifiers:
43            freq[int(c(example))] += 1
44        index = freq.index(max(freq))
45        value = Orange.data.Value(self.domain.classVar, index)
46        for i in range(len(freq)):
47            freq[i] = freq[i]/len(self.classifiers)
48        if resultType == Orange.classification.Classifier.GetValue: return value
49        elif resultType == Orange.classification.Classifier.GetProbabilities: return freq
50        else: return (value, freq)
51       
Note: See TracBrowser for help on using the repository browser.