⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 owclassificationtreegraph.py

📁 orange源码 数据挖掘技术
💻 PY
📖 第 1 页 / 共 2 页
字号:
        OWTreeViewer2D.__init__(self, parent, signalManager, name)
        self.settingsList=self.settingsList+["ShowPies","TargetClassIndex"]
        
        self.inputs = [("Classification Tree", orange.TreeClassifier, self.ctree)]
        self.outputs = [("Examples", ExampleTable), ("Classified Examples", ExampleTableWithClass)]
        
        self.ShowPies=1
        self.TargetClassIndex=0
        self.canvas=TreeCanvas(self)
        self.canvasView=TreeCanvasView(self, self.canvas, self.mainArea, "CView")
        layout=QVBoxLayout(self.mainArea)
        layout.addWidget(self.canvasView)
        self.canvas.resize(800,800)
        self.canvasView.bubbleConstructor=self.classificationBubbleConstructor
        self.navWidget=QWidget(None, "Navigator")
        self.navWidget.lay=QVBoxLayout(self.navWidget)
        canvas=TreeCanvas(self.navWidget)
        self.treeNav=TreeNavigator(self.canvasView,self,canvas,self.navWidget, "Nav")
        self.treeNav.setCanvas(canvas)
        self.navWidget.lay.addWidget(self.treeNav)
        self.canvasView.setNavigator(self.treeNav)
        self.navWidget.resize(400,400)
        self.navWidget.setCaption("Navigator")
        # OWGUI.button(self.TreeTab,self,"Navigator",self.toggleNavigator)
        self.setMouseTracking(True)

        nodeInfoBox = QVButtonGroup("Show Info", self.NodeTab)
        nodeInfoButtons = ['Majority class', 'Majority class probability', 'Target class probability', 'Number of instances']
        nodeInfoSettings = ['maj', 'majp', 'tarp', 'inst']
        self.NodeInfoW = []; self.dummy = 0
        for i in range(len(nodeInfoButtons)):
            setattr(self, nodeInfoSettings[i], i in self.NodeInfo)
            w = OWGUI.checkBox(nodeInfoBox, self, nodeInfoSettings[i], \
                               nodeInfoButtons[i], callback=self.setNodeInfo, getwidget=1, id=i)
            self.NodeInfoW.append(w)

        OWGUI.comboBox(self.NodeTab, self, 'NodeColorMethod', items=['Default', 'Instances in node', 'Majority class probability', 'Target class probability', 'Target class distribution'], box='Node Color',                            
                                callback=self.toggleNodeColor)

        OWGUI.checkBox(self.NodeTab, self, 'ShowPies', 'Show pies', box='Pies', tooltip='Show pie graph with class distribution?', callback=self.togglePies)
        self.targetCombo=OWGUI.comboBox(self.NodeTab,self, "TargetClassIndex",items=[],box="Target Class",callback=self.toggleTargetClass)
        OWGUI.button(self.controlArea, self, "Save As", callback=self.saveGraph, debuggingEnabled = 0)
        self.NodeInfoSorted=list(self.NodeInfo)
        self.NodeInfoSorted.sort()
        
    def setNodeInfo(self, widget=None, id=None):
        if widget:
            if widget.isChecked():
                if len(self.NodeInfo) == 2:
                    self.NodeInfoW[self.NodeInfo[0]].setChecked(0)
                self.NodeInfo.append(id)
            else:
                self.NodeInfo.remove(id)
            self.NodeInfoSorted=list(self.NodeInfo)
            self.NodeInfoSorted.sort()
            self.NodeInfoMethod=id
        #print self.NodeInfoSorted
        for n in self.canvas.nodeList:
            n.setText(self.NodeInfoSorted)
        self.canvas.update()

    def activateLoadedSettings(self):
        if not self.tree:
            return 
        OWTreeViewer2D.activateLoadedSettings(self)
        self.setNodeInfo()
        self.toggleNodeColor()
        
    def toggleNodeColor(self):
        for node in self.canvas.nodeList:
            if self.NodeColorMethod == 0:   # default
                node.setBrush(QBrush(BodyColor_Default))
            elif self.NodeColorMethod == 1: # instances in node
                light = 400 - 300*node.tree.distribution.cases/self.tree.distribution.cases
                node.setBrush(QBrush(BodyCasesColor_Default.light(light)))
            elif self.NodeColorMethod == 2: # majority class probability
                light=400- 300*node.majClassProb
                node.setBrush(QBrush(self.ClassColors[node.majClass[0]].light(light)))
            elif self.NodeColorMethod == 3: # target class probability
                light=400-300*node.dist[self.TargetClassIndex]/node.dist.cases
                node.setBrush(QBrush(self.ClassColors[self.TargetClassIndex].light(light)))
            elif self.NodeColorMethod == 4: # target class distribution
                light=200 - 100*node.dist[self.TargetClassIndex]/self.tree.distribution[self.TargetClassIndex]
                node.setBrush(QBrush(self.ClassColors[self.TargetClassIndex].light(light)))
        self.canvas.update()
        self.treeNav.leech()

    def toggleTargetClass(self):
        if self.NodeColorMethod in [3,4]:
            self.toggleNodeColor()
        for n in self.canvas.nodeList:
            n.texts[2]="%.3f" % (n.dist.items()[self.TargetClassIndex][1]/n.dist.cases)
            if 2 in self.NodeInfoSorted:
                n.setText(self.NodeInfoSorted)
        self.canvas.update()
                
    def togglePies(self):
        for n in self.canvas.nodeList:
            n.setPieVisible(self.ShowPies)
        self.canvas.update()

    def ctree(self, tree=None):
        self.targetCombo.clear()
        if tree:
            for name in tree.tree.examples.domain.classVar.values:
                self.targetCombo.insertItem(name)
        if tree and len(tree.tree.distribution)>self.TargetClassIndex:
            self.TargetClassIndex=0
        OWTreeViewer2D.ctree(self, tree)

    def walkcreate(self, tree, parent=None, level=0, attrVal=""):
        node=ClassificationNode(attrVal, tree, parent or self.canvas, self.canvas)
        if tree.branches:
            for i in range(len(tree.branches)):
                if tree.branches[i]:
                    self.walkcreate(tree.branches[i],node,level+1,tree.branchDescriptions[i])
        return node

    def classificationBubbleConstructor(self, node, pos, canvas):
        b=CanvasBubbleInfo(node, pos,canvas)
        rule=list(node.rule)
        #print node.rule, rule
        #rule.sort(lambda:a,b:a[0]<b[0])
        # merge
        if rule:
            try:
                rule=parseRules(list(rule))
            except:
                pass
            text="IF "+" AND\n  ".join([a[0].name+" = "+a[1] for a in rule])+"\nTHEN "+node.majClassName
        else:
            text="THEN "+node.majClassName
        b.addTextLine(text)
        b.addTextLine()
        text="Instances:"+str(node.numInst)+"(%.1f" % (node.numInst/self.tree.distribution.cases*100)+"%)"
        b.addTextLine(text)
        b.addTextLine()
        for i,d in enumerate(node.dist.items()):
            if d[1]!=0:
                b.addTextLine("%s: %i (%.1f" %(d[0],int(d[1]),d[1]/sum(node.dist)*100)+"%)",self.ClassColors[i])
        b.addTextLine()
        b.addTextLine((node.tree.branches and "Partition on: "+node.name) or "(leaf)")
        b.show()
        return b

    def saveGraph(self):
        qfileName = QFileDialog.getSaveFileName("tree.png","Portable Network Graphics (.PNG)\nWindows Bitmap (.BMP)\nGraphics Interchange Format (.GIF)\nDot Tree File(.DOT)", None, "Save to..")
        fileName = str(qfileName)
        if fileName == "": return
        (fil,ext) = os.path.splitext(fileName)
        ext = ext.replace(".","")
        ext = ext.upper()
        if ext=="DOT":
            orngTree.printDot(self.tree, fileName)
            return 
        dSize= self.canvas.size()
        buffer = QPixmap(dSize.width(),dSize.height()) # any size can do, now using the window size     
        painter = QPainter(buffer)
        
        painter.fillRect(buffer.rect(), QBrush(QColor(255, 255, 255))) # make background same color as the widget's background
        self.canvasView.drawContents(painter,0,0,dSize.width(), dSize.height())
        painter.end()
        buffer.save(fileName, ext)
    
if __name__=="__main__":
    a = QApplication(sys.argv)
    ow = OWClassificationTreeViewer2D()
    a.setMainWidget(ow)

    data = orange.ExampleTable('../../doc/datasets/voting.tab')
    tree = orange.TreeLearner(data, storeExamples = 1)
    ow.ctree(tree)

    # here you can test setting some stuff
    ow.show()
    a.exec_loop()
    ow.saveSettings()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -