source: orange/docs/extend-widgets/rst/OWLearningCurveA.py @ 11049:f4dd8dbc57bb

Revision 11049:f4dd8dbc57bb, 7.6 KB checked in by Miha Stajdohar <miha.stajdohar@…>, 16 months ago (diff)

From HTML to Sphinx.

Line 
1"""
2<name>Learning Curve (A)</name>
3<description>Takes a data set and a set of learners and shows a learning curve in a table</description>
4<icon>icons/LearningCurveA.png</icon>
5<priority>1000</priority>
6"""
7
8from OWWidget import *
9import OWGUI, orngTest, orngStat
10
11class OWLearningCurveA(OWWidget):
12    settingsList = ["folds", "steps", "scoringF", "commitOnChange"]
13   
14    def __init__(self, parent=None, signalManager=None):
15        OWWidget.__init__(self, parent, signalManager, 'LearningCurveA')
16
17        self.inputs = [("Data", ExampleTable, self.dataset),
18                       ("Learner", orange.Learner, self.learner, Multiple)]
19       
20        self.folds = 5     # cross validation folds
21        self.steps = 10    # points in the learning curve
22        self.scoringF = 0  # scoring function
23        self.commitOnChange = 1 # compute curve on any change of parameters
24        self.loadSettings()
25        self.setCurvePoints() # sets self.curvePoints, self.steps equidistantpoints from 1/self.steps to 1
26        self.scoring = [("Classification Accuracy", orngStat.CA), ("AUC", orngStat.AUC), ("BrierScore", orngStat.BrierScore), ("Information Score", orngStat.IS), ("Sensitivity", orngStat.sens), ("Specificity", orngStat.spec)]
27        self.learners = [] # list of current learners from input channel, tuples (id, learner)
28        self.data = None   # data on which to construct the learning curve
29        self.curves = []   # list of evaluation results (one per learning curve point)
30        self.scores = []   # list of current scores, learnerID:[learner scores]
31
32        # GUI
33        box = OWGUI.widgetBox(self.controlArea, "Info")
34        self.infoa = OWGUI.widgetLabel(box, 'No data on input.')
35        self.infob = OWGUI.widgetLabel(box, 'No learners.')
36
37        OWGUI.separator(self.controlArea)
38        box = OWGUI.widgetBox(self.controlArea, "Evaluation Scores")
39        scoringNames = [x[0] for x in self.scoring]
40        OWGUI.comboBox(box, self, "scoringF", items=scoringNames, callback=self.computeScores)
41
42        OWGUI.separator(self.controlArea)
43        box = OWGUI.widgetBox(self.controlArea, "Options")
44        OWGUI.spin(box, self, 'folds', 2, 100, step=1, label='Cross validation folds:  ',
45                   callback=lambda: self.computeCurve(self.commitOnChange))
46        OWGUI.spin(box, self, 'steps', 2, 100, step=1, label='Learning curve points:  ',
47                   callback=[self.setCurvePoints, lambda: self.computeCurve(self.commitOnChange)])
48
49        OWGUI.checkBox(box, self, 'commitOnChange', 'Apply setting on any change')
50        self.commitBtn = OWGUI.button(box, self, "Apply Setting", callback=self.computeCurve, disabled=1)
51
52        # table widget
53        self.table = OWGUI.table(self.mainArea, selectionMode=QTableWidget.NoSelection)
54               
55        self.resize(500,200)
56
57    ##############################################################################   
58    # slots: handle input signals       
59
60    def dataset(self, data):
61        if data:
62            self.infoa.setText('%d instances in input data set' % len(data))
63            self.data = data
64            if (len(self.learners)):
65                self.computeCurve()
66        else:
67            self.infoa.setText('No data on input.')
68            self.curves = []
69            self.scores = []
70        self.commitBtn.setEnabled(self.data<>None)
71
72    def learner(self, learner, id=None):
73        ids = [x[0] for x in self.learners]
74        if not learner: # remove a learner and corresponding results
75            if not ids.count(id):
76                return # no such learner, removed before
77            indx = ids.index(id)
78            for i in range(self.steps):
79                self.curves[i].remove(indx)
80            del self.scores[indx]
81            del self.learners[indx]
82            self.setTable()
83        else:
84            if ids.count(id): # update (already seen a learner from this source)
85                indx = ids.index(id)
86                self.learners[indx] = (id, learner)
87                if self.data:
88                    curve = self.getLearningCurve([learner])
89                    score = [self.scoring[self.scoringF][1](x)[0] for x in curve]
90                    self.scores[indx] = score
91                    for i in range(self.steps):
92                        self.curves[i].add(curve[i], 0, replace=indx)
93            else: # add new learner
94                self.learners.append((id, learner))
95                if self.data:
96                    curve = self.getLearningCurve([learner])
97                    score = [self.scoring[self.scoringF][1](x)[0] for x in curve]
98                    self.scores.append(score)
99                    if len(self.curves):
100                        for i in range(self.steps):
101                            self.curves[i].add(curve[i], 0)
102                    else:
103                        self.curves = curve
104        if len(self.learners):
105            self.infob.setText("%d learners on input." % len(self.learners))
106        else:
107            self.infob.setText("No learners.")
108        self.commitBtn.setEnabled(len(self.learners))
109##        if len(self.scores):
110        if self.data:
111            self.setTable()
112
113    ##############################################################################   
114    # learning curve table, callbacks
115
116    # recomputes the learning curve
117    def computeCurve(self, condition=1):
118        if condition:
119            learners = [x[1] for x in self.learners]
120            self.curves = self.getLearningCurve(learners)
121            self.computeScores()
122
123    def computeScores(self):           
124        self.scores = [[] for i in range(len(self.learners))]
125        for x in self.curves:
126            for (i,s) in enumerate(self.scoring[self.scoringF][1](x)):
127                self.scores[i].append(s)
128        self.setTable()
129
130    def getLearningCurve(self, learners):   
131        pb = OWGUI.ProgressBar(self, iterations=self.steps*self.folds)
132        curve = orngTest.learningCurveN(learners, self.data, folds=self.folds, proportions=self.curvePoints, callback=pb.advance)
133        pb.finish()
134        return curve
135
136    def setCurvePoints(self):
137        self.curvePoints = [(x+1.)/self.steps for x in range(self.steps)]
138
139    def setTable(self):
140        self.table.setColumnCount(0)
141        self.table.setColumnCount(len(self.learners))
142        self.table.setRowCount(self.steps)
143
144        # set the headers
145        self.table.setHorizontalHeaderLabels([l.name for i,l in self.learners])
146        self.table.setVerticalHeaderLabels(["%4.2f" % p for p in self.curvePoints])
147
148        # set the table contents
149        for l in range(len(self.learners)):
150            for p in range(self.steps):
151                OWGUI.tableItem(self.table, p, l, "%7.5f" % self.scores[l][p])
152
153        for i in range(len(self.learners)):
154            self.table.setColumnWidth(i, 80)
155
156##############################################################################
157# Test the widget, run from prompt
158
159if __name__=="__main__":
160    appl = QApplication(sys.argv)
161    ow = OWLearningCurveA()
162    ow.show()
163   
164    l1 = orange.BayesLearner()
165    l1.name = 'Naive Bayes'
166    ow.learner(l1, 1)
167
168    data = orange.ExampleTable('../datasets/iris.tab')
169    ow.dataset(data)
170
171    l2 = orange.BayesLearner()
172    l2.name = 'Naive Bayes (m=10)'
173    l2.estimatorConstructor = orange.ProbabilityEstimatorConstructor_m(m=10)
174    l2.conditionalEstimatorConstructor = orange.ConditionalProbabilityEstimatorConstructor_ByRows(estimatorConstructor = orange.ProbabilityEstimatorConstructor_m(m=10))
175    ow.learner(l2, 2)
176
177    import orngTree
178    l4 = orngTree.TreeLearner(minSubset=2)
179    l4.name = "Decision Tree"
180    ow.learner(l4, 4)
181
182#    ow.learner(None, 1)
183#    ow.learner(None, 2)
184#    ow.learner(None, 4)
185
186    appl.exec_()
Note: See TracBrowser for help on using the repository browser.