source: orange/Orange/testing/regression/tests_20/reference_cb-splitconstructor.py @ 9952:986e9cd806f4

Revision 9952:986e9cd806f4, 2.3 KB checked in by Miha Stajdohar <miha.stajdohar@…>, 2 years ago (diff)

Tests moved and renamed from orange 20.

Line 
1# Description: Shows how to derive a Python class from orange.TreeSplitConstructor
2# Category:    classification, decision trees, callbacks to Python
3# Classes:     TreeSplitConstructor, Classifier, SubsetsGenerator_constSize, orngMisc.BestOnTheFly
4# Uses:        lenses
5# Referenced:  callbacks.htm
6
7import orange, orngTree, orngMisc
8tab = orange.ExampleTable(r"lenses.tab")
9
10
11class CartesianClassifier(orange.Classifier):
12    def __init__(self, var1, var2):
13        self.var1 = var1
14        self.var2 = var2
15        self.noValues2 = len(var2.values)
16        self.classVar = orange.EnumVariable("%sx%s" % (var1.name, var2.name))
17        self.classVar.values = ["%s-%s" % (v1, v2) for v1 in var1.values for v2 in var2.values]
18
19    def __call__(self, ex, what = orange.Classifier.GetValue):
20        val = ex[self.var1] * self.noValues2 + ex[self.var2]
21        if what == orange.Classifier.GetValue:
22            return orange.Value(self.classVar, val)
23        probs = orange.DiscDistribution(self.classVar)
24        probs[val] = 1.0
25        if what == orange.Classifier.GetProbabilities:
26            return probs
27        else:
28            return (orange.Value(self.classVar, val), probs)
29
30
31class SplitConstructor_CartesianMeasure(orange.TreeSplitConstructor):
32    def __init__(self, measure):
33        self.measure = measure
34       
35    def __call__(self, gen, weightID, contingencies, apriori, candidates, nodeClassifier):
36#        print "SplitConstructor_CartesianMeasure called"
37        attributes = tab.domain.attributes
38        selectBest = orngMisc.BestOnTheFly(orngMisc.compare2_firstBigger)
39        for var1, var2 in orange.SubsetsGenerator_constSize(attributes, B=2):
40            if candidates[attributes.index(var1)] and candidates[attributes.index(var2)]:
41                cc = CartesianClassifier(var1, var2)
42                cc.classVar.getValueFrom = cc
43                meas = self.measure(cc.classVar, gen)
44                selectBest.candidate((meas, cc))
45
46        if not selectBest.best:
47            return None
48
49        bestMeas, bestSelector = selectBest.winner()
50        bestSelector.classVar.getValueFrom = None
51        return (bestSelector, bestSelector.classVar.values, None, bestMeas)
52
53
54treeLearner = orange.TreeLearner()
55treeLearner.split = SplitConstructor_CartesianMeasure(orange.MeasureAttribute_gainRatio)
56tree = treeLearner(tab)
57orngTree.printTxt(tree)
Note: See TracBrowser for help on using the repository browser.