source: orange/docs/extend-widgets/rst/OWLearningCurveC.py @ 11881:99bec0d8a70d

Revision 11881:99bec0d8a70d, 12.4 KB checked in by Ales Erjavec <ales.erjavec@…>, 5 weeks ago (diff)

More fixes to widget development manual code snippets.

Line 
1"""
2<name>Learning Curve (C)</name>
3<description>Takes a data set and a set of learners and plots a learning curve in a table</description>
4<icon>icons/LearningCurveC.png</icon>
5<priority>1020</priority>
6"""
7
8import Orange
9
10from OWWidget import *
11from OWColorPalette import ColorPixmap
12from OWGraph import *
13
14import OWGUI
15
16import warnings
17
18class OWLearningCurveC(OWWidget):
19    settingsList = ["folds", "steps", "scoringF", "commitOnChange",
20                    "graphPointSize", "graphDrawLines", "graphShowGrid"]
21
22    def __init__(self, parent=None, signalManager=None):
23        OWWidget.__init__(self, parent, signalManager, 'LearningCurveC')
24
25        self.inputs = [("Data", Orange.data.Table, self.dataset),
26                       ("Learner", Orange.classification.Learner,
27                        self.learner, Multiple)]
28
29        self.folds = 5     # cross validation folds
30        self.steps = 10    # points in the learning curve
31        self.scoringF = 0  # scoring function
32        self.commitOnChange = 1 # compute curve on any change of parameters
33        self.graphPointSize = 5 # size of points in the graphs
34        self.graphDrawLines = 1 # draw lines between points in the graph
35        self.graphShowGrid = 1  # show gridlines in the graph
36        self.selectedLearners = []
37
38        self.loadSettings()
39
40        warnings.filterwarnings("ignore", ".*builtin attribute.*", Orange.core.AttributeWarning)
41
42        self.updateCurvePoints() # sets self.curvePoints, self.steps equidistant points from 1/self.steps to 1
43        self.scoring = [("Classification Accuracy",
44                         Orange.evaluation.scoring.CA),
45                        ("AUC", Orange.evaluation.scoring.AUC),
46                        ("BrierScore", Orange.evaluation.scoring.Brier_score),
47                        ("Information Score", Orange.evaluation.scoring.IS),
48                        ("Sensitivity", Orange.evaluation.scoring.sens),
49                        ("Specificity", Orange.evaluation.scoring.spec)]
50        self.learners = [] # list of current learners from input channel, tuples (id, learner)
51        self.data = None   # data on which to construct the learning curve
52        self.curves = []   # list of evaluation results (one per learning curve point)
53        self.scores = []   # list of current scores, learnerID:[learner scores]
54
55        # GUI
56        box = OWGUI.widgetBox(self.controlArea, "Info")
57        self.infoa = OWGUI.widgetLabel(box, 'No data on input.')
58        self.infob = OWGUI.widgetLabel(box, 'No learners.')
59
60        ## class selection (classQLB)
61        OWGUI.separator(self.controlArea)
62
63        # ~SPHINX start color cb~
64        self.cbox = OWGUI.widgetBox(self.controlArea, "Learners")
65        self.llb = OWGUI.listBox(self.cbox, self, "selectedLearners",
66                                 selectionMode=QListWidget.MultiSelection,
67                                 callback=self.learnerSelectionChanged)
68       
69        self.llb.setMinimumHeight(50)
70        self.blockSelectionChanges = 0
71        # ~SPHINX end color cb~
72
73        OWGUI.separator(self.controlArea)
74
75        box = OWGUI.widgetBox(self.controlArea, "Evaluation Scores")
76        scoringNames = [x[0] for x in self.scoring]
77        OWGUI.comboBox(box, self, "scoringF", items=scoringNames,
78                       callback=self.computeScores)
79
80        OWGUI.separator(self.controlArea)
81
82        box = OWGUI.widgetBox(self.controlArea, "Options")
83        OWGUI.spin(box, self, 'folds', 2, 100, step=1,
84                   label='Cross validation folds:  ',
85                   callback=lambda: self.computeCurve() if self.commitOnChange else None)
86        OWGUI.spin(box, self, 'steps', 2, 100, step=1,
87                   label='Learning curve points:  ',
88                   callback=[self.updateCurvePoints,
89                             lambda: self.computeCurve() if self.commitOnChange else None])
90
91        OWGUI.checkBox(box, self, 'commitOnChange', 'Apply setting on any change')
92        self.commitBtn = OWGUI.button(box, self, "Apply Setting",
93                                      callback=self.computeCurve, disabled=1)
94
95        # ~SPHINX start main area tabs~
96        # start of content (right) area
97        tabs = OWGUI.tabWidget(self.mainArea)
98
99        # graph tab
100        tab = OWGUI.createTabPage(tabs, "Graph")
101        self.graph = OWGraph(tab)
102        self.graph.setAxisAutoScale(QwtPlot.xBottom)
103        self.graph.setAxisAutoScale(QwtPlot.yLeft)
104        tab.layout().addWidget(self.graph)
105        self.setGraphGrid()
106
107        # table tab
108        tab = OWGUI.createTabPage(tabs, "Table")
109        self.table = OWGUI.table(tab, selectionMode=QTableWidget.NoSelection)
110        # ~SPHINX end main area tabs~
111
112        self.resize(550,200)
113
114    ##############################################################################
115    # slots: handle input signals
116
117    def dataset(self, data):
118        if data is not None:
119            self.infoa.setText('%d instances in input data set' % len(data))
120            self.data = data
121            if len(self.learners):
122                self.computeCurve()
123            self.replotGraph()
124        else:
125            self.infoa.setText('No data on input.')
126            self.curves = []
127            self.scores = []
128            self.graph.removeDrawingCurves()
129            self.graph.replot()
130        self.commitBtn.setEnabled(self.data<>None)
131
132    # manage learner signal
133    # we use following additional attributes for learner:
134    # - isSelected, learner is selected (display the learning curve)
135    # - curve, learning curve for the learner
136    # - score, evaluation score for the learning
137    def learner(self, learner, id=None):
138        ids = [x[0] for x in self.learners]
139        if learner is None: # remove a learner and corresponding results
140            if not ids.count(id):
141                return # no such learner, removed before
142            indx = ids.index(id)
143            for i in range(self.steps):
144                self.curves[i].remove(indx)
145            del self.scores[indx]
146            self.learners[indx][1].curve.detach()
147            del self.learners[indx]
148            self.updateTable()
149            self.updatellb()
150        else:
151            if ids.count(id): # update (already seen a learner from this source)
152                indx = ids.index(id)
153                prevLearner = self.learners[indx][1]
154                learner.isSelected = prevLearner.isSelected
155                self.learners[indx] = (id, learner)
156                if self.data:
157                    curve = self.getLearningCurve([learner])
158                    score = [self.scoring[self.scoringF][1](x)[0] for x in curve]
159                    self.scores[indx] = score
160                    for i in range(self.steps):
161                        self.curves[i].add(curve[i], 0, replace=indx)
162                    learner.score = score
163                    prevLearner.curve.detach()
164                    self.drawLearningCurve(learner)
165                self.updatellb()
166            else: # add new learner
167                learner.isSelected = 1
168                self.learners.append((id, learner))
169                if self.data:
170                    curve = self.getLearningCurve([learner])
171                    score = [self.scoring[self.scoringF][1](x)[0] for x in curve]
172                    self.scores.append(score)
173                    if len(self.curves):
174                        for i in range(self.steps):
175                            self.curves[i].add(curve[i], 0)
176                    else:
177                        self.curves = curve
178                    learner.score = score
179                self.updatellb()
180                self.drawLearningCurve(learner)
181        if len(self.learners):
182            self.infob.setText("%d learners on input." % len(self.learners))
183        else:
184            self.infob.setText("No learners.")
185        self.commitBtn.setEnabled(len(self.learners))
186        if self.data:
187            self.updateTable()
188
189    ##############################################################################
190    # learning curve table, callbacks
191
192    # recomputes the learning curve
193    def computeCurve(self):
194        learners = [x[1] for x in self.learners]
195        self.curves = self.getLearningCurve(learners)
196        self.computeScores()
197
198    def computeScores(self):
199        self.scores = [[] for i in range(len(self.learners))]
200        for x in self.curves:
201            for (i,s) in enumerate(self.scoring[self.scoringF][1](x)):
202                self.scores[i].append(s)
203        for (i,l) in enumerate(self.learners):
204            l[1].score = self.scores[i]
205        self.updateTable()
206        self.replotGraph()
207
208    def getLearningCurve(self, learners):
209        pb = OWGUI.ProgressBar(self, iterations=self.steps*self.folds)
210        curve = Orange.evaluation.testing.learning_curve_n(
211            learners, self.data, folds=self.folds,
212            proportions=self.curvePoints,
213            callback=pb.advance)
214
215        pb.finish()
216        return curve
217
218    def updateCurvePoints(self):
219        self.curvePoints = [(x+1.)/self.steps for x in range(self.steps)]
220
221    def updateTable(self):
222        self.table.setColumnCount(0)
223        self.table.setColumnCount(len(self.learners))
224        self.table.setRowCount(self.steps)
225
226        # set the headers
227        self.table.setHorizontalHeaderLabels([l.name for i,l in self.learners])
228        self.table.setVerticalHeaderLabels(["%4.2f" % p for p in self.curvePoints])
229
230        # set the table contents
231        for l in range(len(self.learners)):
232            for p in range(self.steps):
233                OWGUI.tableItem(self.table, p, l, "%7.5f" % self.scores[l][p])
234
235        for i in range(len(self.learners)):
236            self.table.setColumnWidth(i, 80)
237
238
239    # management of learner selection
240
241    def updatellb(self):
242        self.blockSelectionChanges = 1
243        self.llb.clear()
244        colors = ColorPaletteHSV(len(self.learners))
245        for (i,lt) in enumerate(self.learners):
246            l = lt[1]
247            item = QListWidgetItem(ColorPixmap(colors[i]), l.name)
248            self.llb.addItem(item)
249            item.setSelected(l.isSelected)
250            l.color = colors[i]
251        self.blockSelectionChanges = 0
252
253    def learnerSelectionChanged(self):
254        if self.blockSelectionChanges: return
255        for (i,lt) in enumerate(self.learners):
256            l = lt[1]
257            if l.isSelected != (i in self.selectedLearners):
258                if l.isSelected: # learner was deselected
259                    l.curve.detach()
260                else: # learner was selected
261                    self.drawLearningCurve(l)
262                self.graph.replot()
263            l.isSelected = i in self.selectedLearners
264
265    # Graph specific methods
266
267    def setGraphGrid(self):
268        self.graph.enableGridYL(self.graphShowGrid)
269        self.graph.enableGridXB(self.graphShowGrid)
270
271    def setGraphStyle(self, learner):
272        curve = learner.curve
273        if self.graphDrawLines:
274            curve.setStyle(QwtPlotCurve.Lines)
275        else:
276            curve.setStyle(QwtPlotCurve.NoCurve)
277
278        curve.setSymbol(
279            QwtSymbol(QwtSymbol.Ellipse,
280                      QBrush(QColor(0,0,0)), QPen(QColor(0,0,0)),
281                      QSize(self.graphPointSize, self.graphPointSize)))
282
283        curve.setPen(QPen(learner.color, 5))
284
285    def drawLearningCurve(self, learner):
286        if not self.data:
287            return
288        curve = self.graph.addCurve(
289            learner.name,
290            xData=self.curvePoints,
291            yData=learner.score,
292            autoScale=True)
293       
294        learner.curve = curve
295        self.setGraphStyle(learner)
296        self.graph.replot()
297
298    def replotGraph(self):
299        self.graph.removeDrawingCurves()
300        for l in self.learners:
301            self.drawLearningCurve(l[1])
302
303
304if __name__=="__main__":
305    appl = QApplication(sys.argv)
306    ow = OWLearningCurveC()
307    ow.show()
308
309    l1 = Orange.classification.bayes.NaiveLearner()
310    l1.name = 'Naive Bayes'
311    ow.learner(l1, 1)
312
313    data = Orange.data.Table('iris.tab')
314    ow.dataset(data)
315
316    l2 = Orange.classification.bayes.NaiveLearner()
317    l2.name = 'Naive Bayes (m=10)'
318    l2.estimatorConstructor = Orange.statistics.estimate.M(m=10)
319    l2.conditionalEstimatorConstructor = Orange.statistics.estimate.ConditionalByRows(estimatorConstructor = Orange.statistics.estimate.M(m=10))
320
321    l3 = Orange.classification.knn.kNNLearner(name="k-NN")
322    ow.learner(l3, 3)
323
324    l4 = Orange.classification.tree.TreeLearner(minSubset=2)
325    l4.name = "Decision Tree"
326    ow.learner(l4, 4)
327
328#    ow.learner(None, 1)
329#    ow.learner(None, 2)
330#    ow.learner(None, 4)
331
332    appl.exec_()
Note: See TracBrowser for help on using the repository browser.