source: orange/Orange/doc/ofb/bagging.py @ 9671:a7b056375472

Revision 9671:a7b056375472, 1.6 KB checked in by anze <anze.staric@…>, 2 years ago (diff)

Moved orange to Orange (part 2)

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