Beispiel #1
0
    def updateRulesModel(self):
        table = []
        if self.classifier is not None:
            for i, r in enumerate(self.classifier.rules):
                table.append(
                    (int(r.complexity), r.quality, r.classDistribution.abs,
                     str(r.classifier.defaultValue), r.classDistribution,
                     self.ruleText(r)))

        self.rulesTableModel = PyTableModel(table, self.headers)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        self.tableView.resizeColumnsToContents()
        self.tableView.resizeRowsToContents()
        self.updateVisibleColumns(
        )  # if the widget got data for the first time
    def updateRulesModel(self):
        table = []
        if self.classifier is not None:
            for i, r in enumerate(self.classifier.rules):
                table.append((int(r.complexity),
                              r.quality,
                              r.classDistribution.abs,
                              str(r.classifier.defaultValue),
                              r.classDistribution,
                              self.ruleText(r)))

        self.rulesTableModel = PyTableModel(table, self.headers)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        self.tableView.resizeColumnsToContents()
        self.tableView.resizeRowsToContents()
        self.updateVisibleColumns() # if the widget got data for the first time
Beispiel #3
0
    def __init__(self,
                 parent=None,
                 signalManager=None,
                 name="CN2 Rules Viewer"):
        OWWidget.__init__(self, parent, signalManager, name)
        self.inputs = [("Rule Classifier", orange.RuleClassifier,
                        self.setRuleClassifier)]
        self.outputs = [("Data", ExampleTable), ("Features", AttributeList)]

        self.show_Rule_length = True
        self.show_Rule_quality = True
        self.show_Coverage = True
        self.show_Predicted_class = True
        self.show_Distribution = True
        self.show_Rule = True

        self.autoCommit = False
        self.selectedAttrsOnly = True

        self.loadSettings()

        #####
        # GUI
        #####

        box = OWGUI.widgetBox(self.controlArea, "Show Info", addSpace=True)
        box.layout().setSpacing(3)
        self.headers = [
            "Rule length", "Rule quality", "Coverage", "Predicted class",
            "Distribution", "Rule"
        ]

        for i, header in enumerate(self.headers):
            OWGUI.checkBox(box,
                           self,
                           "show_%s" % header.replace(" ", "_"),
                           header,
                           tooltip="Show %s column" % header.lower(),
                           callback=self.updateVisibleColumns)

        box = OWGUI.widgetBox(self.controlArea, "Output")
        box.layout().setSpacing(3)
        cb = OWGUI.checkBox(box,
                            self,
                            "autoCommit",
                            "Commit on any change",
                            callback=self.commitIf)

        OWGUI.checkBox(box,
                       self,
                       "selectedAttrsOnly",
                       "Selected attributes only",
                       tooltip="Send selected attributes only",
                       callback=self.commitIf)

        b = OWGUI.button(box,
                         self,
                         "Commit",
                         callback=self.commit,
                         default=True)
        OWGUI.setStopper(self, b, cb, "changedFlag", callback=self.commit)

        OWGUI.rubber(self.controlArea)

        self.tableView = QTableView()
        self.tableView.setItemDelegate(PyObjectItemDelegate(self))
        self.tableView.setItemDelegateForColumn(1, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(2, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(4,
                                                DistributionItemDelegate(self))
        self.tableView.setItemDelegateForColumn(
            5, MultiLineStringItemDelegate(self))
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QTableView.SelectRows)
        self.tableView.setAlternatingRowColors(True)

        self.rulesTableModel = PyTableModel([], self.headers)
        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.rulesTableModel)

        self.tableView.setModel(self.proxyModel)
        self.connect(
            self.tableView.selectionModel(),
            SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            lambda is1, is2: self.commitIf())
        self.connect(self.tableView.horizontalHeader(),
                     SIGNAL("sectionClicked(int)"),
                     lambda section: self.tableView.resizeRowsToContents())
        self.mainArea.layout().addWidget(self.tableView)

        self.updateVisibleColumns()

        self.changedFlag = False
        self.classifier = None
        self.rules = []
        self.resize(800, 600)
Beispiel #4
0
class OWCN2RulesViewer(OWWidget):
    settingsList = [
        "show_Rule_length", "show_Rule_quality", "show_Coverage",
        "show_Predicted_class", "show_Distribution", "show_Rule"
    ]

    def __init__(self,
                 parent=None,
                 signalManager=None,
                 name="CN2 Rules Viewer"):
        OWWidget.__init__(self, parent, signalManager, name)
        self.inputs = [("Rule Classifier", orange.RuleClassifier,
                        self.setRuleClassifier)]
        self.outputs = [("Data", ExampleTable), ("Features", AttributeList)]

        self.show_Rule_length = True
        self.show_Rule_quality = True
        self.show_Coverage = True
        self.show_Predicted_class = True
        self.show_Distribution = True
        self.show_Rule = True

        self.autoCommit = False
        self.selectedAttrsOnly = True

        self.loadSettings()

        #####
        # GUI
        #####

        box = OWGUI.widgetBox(self.controlArea, "Show Info", addSpace=True)
        box.layout().setSpacing(3)
        self.headers = [
            "Rule length", "Rule quality", "Coverage", "Predicted class",
            "Distribution", "Rule"
        ]

        for i, header in enumerate(self.headers):
            OWGUI.checkBox(box,
                           self,
                           "show_%s" % header.replace(" ", "_"),
                           header,
                           tooltip="Show %s column" % header.lower(),
                           callback=self.updateVisibleColumns)

        box = OWGUI.widgetBox(self.controlArea, "Output")
        box.layout().setSpacing(3)
        cb = OWGUI.checkBox(box,
                            self,
                            "autoCommit",
                            "Commit on any change",
                            callback=self.commitIf)

        OWGUI.checkBox(box,
                       self,
                       "selectedAttrsOnly",
                       "Selected attributes only",
                       tooltip="Send selected attributes only",
                       callback=self.commitIf)

        b = OWGUI.button(box,
                         self,
                         "Commit",
                         callback=self.commit,
                         default=True)
        OWGUI.setStopper(self, b, cb, "changedFlag", callback=self.commit)

        OWGUI.rubber(self.controlArea)

        self.tableView = QTableView()
        self.tableView.setItemDelegate(PyObjectItemDelegate(self))
        self.tableView.setItemDelegateForColumn(1, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(2, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(4,
                                                DistributionItemDelegate(self))
        self.tableView.setItemDelegateForColumn(
            5, MultiLineStringItemDelegate(self))
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QTableView.SelectRows)
        self.tableView.setAlternatingRowColors(True)

        self.rulesTableModel = PyTableModel([], self.headers)
        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.rulesTableModel)

        self.tableView.setModel(self.proxyModel)
        self.connect(
            self.tableView.selectionModel(),
            SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            lambda is1, is2: self.commitIf())
        self.connect(self.tableView.horizontalHeader(),
                     SIGNAL("sectionClicked(int)"),
                     lambda section: self.tableView.resizeRowsToContents())
        self.mainArea.layout().addWidget(self.tableView)

        self.updateVisibleColumns()

        self.changedFlag = False
        self.classifier = None
        self.rules = []
        self.resize(800, 600)

    def sendReport(self):
        nrules = self.rulesTableModel.rowCount()
        print nrules
        if not nrules:
            self.reportRaw("<p>No rules.</p>")
            return

        shown = [
            i for i, header in enumerate(self.headers)
            if getattr(self, "show_%s" % header.replace(" ", "_"))
        ]
        rep = '<table>\n<tr style="height: 2px"><th colspan="11"  style="border-bottom: thin solid black; height: 2px;">\n'
        rep += "<tr>" + "".join("<th>%s</th>" % self.headers[i]
                                for i in shown) + "</tr>\n"
        for row in range(nrules):
            rep += "<tr>"
            for col in shown:
                data = _toPyObject(
                    self.rulesTableModel.data(
                        self.rulesTableModel.createIndex(row, col)))
                if col == 4:
                    rep += "<td>%s</td>" % ":".join(map(str, data))
                elif col in (0, 3):
                    rep += '<td align="center">%s</td>' % data
                elif col in (1, 2):
                    rep += '<td align="right">%.3f&nbsp;</td>' % data
                else:
                    rep += '<td>%s</td>' % data
        rep += '<tr style="height: 2px"><th colspan="11"  style="border-bottom: thin solid black; height: 2px;">\n</table>\n'
        self.reportRaw(rep)

    def setRuleClassifier(self, classifier=None):
        self.classifier = classifier
        if classifier is not None:
            self.rules = classifier.rules
        else:
            self.rules = []

    def handleNewSignals(self):
        self.updateRulesModel()
        self.commit()

    def updateRulesModel(self):
        table = []
        if self.classifier is not None:
            for i, r in enumerate(self.classifier.rules):
                table.append(
                    (int(r.complexity), r.quality, r.classDistribution.abs,
                     str(r.classifier.defaultValue), r.classDistribution,
                     self.ruleText(r)))

        self.rulesTableModel = PyTableModel(table, self.headers)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        self.tableView.resizeColumnsToContents()
        self.tableView.resizeRowsToContents()
        self.updateVisibleColumns(
        )  # if the widget got data for the first time

    def ruleText(self, rule):
        text = rule_to_string(rule, show_distribution=False)
        p = re.compile(r"[0-9]\.[0-9]+")
        text = p.sub(lambda match: "%.2f" % float(match.group()[0]), text)
        text = text.replace("AND", "AND\n   ")
        text = text.replace("THEN", "\nTHEN")
        return text

    def updateVisibleColumns(self):
        anyVisible = False
        for i, header in enumerate(self.headers):
            visible = getattr(self, "show_%s" % header.replace(" ", "_"))
            self.tableView.horizontalHeader().setSectionHidden(i, not visible)
            anyVisible = anyVisible or visible

        # report button is not available if not running canvas
        if hasattr(self, "reportButton"):
            self.reportButton.setEnabled(anyVisible)

    def commitIf(self):
        if self.autoCommit:
            self.commit()
        else:
            self.changedFlag = True

    def selectedAttrsFromRules(self, rules):
        selected = []
        for rule in rules:
            for c in rule.filter.conditions:
                selected.append(rule.filter.domain[c.position])
        return set(selected)

    def selectedExamplesFromRules(self, rules, examples):
        selected = []
        for rule in rules:
            selected.extend(examples.filterref(rule.filter))
            rule.filter.negate = 1
            examples = examples.filterref(rule.filter)
            rule.filter.negate = 0
        return selected

    def commit(self):
        rows = self.tableView.selectionModel().selectedRows()
        rows = [self.proxyModel.mapToSource(index) for index in rows]
        rows = [index.row() for index in rows]
        selectedRules = [self.classifier.rules[row] for row in rows]

        if selectedRules:
            examples = self.classifier.examples
            selectedExamples = self.selectedExamplesFromRules(
                selectedRules, self.classifier.examples)
            selectedAttrs = self.selectedAttrsFromRules(selectedRules)
            selectedAttrs = [
                attr for attr in examples.domain.attributes
                if attr in selectedAttrs
            ]  # restore the order
            if self.selectedAttrsOnly:
                domain = orange.Domain(selectedAttrs, examples.domain.classVar)
                domain.addmetas(examples.domain.getmetas())
                selectedExamples = orange.ExampleTable(domain,
                                                       selectedExamples)
            else:
                selectedExamples = orange.ExampleTable(selectedExamples)

            self.send("Data", selectedExamples)
            self.send("Features", orange.VarList(list(selectedAttrs)))

        else:
            self.send("Data", None)
            self.send("Features", None)

        self.changedFlag = False
    def __init__(self, parent=None, signalManager=None, name="CN2 Rules Viewer"):
        OWWidget.__init__(self, parent, signalManager, name)
        self.inputs = [("Rule Classifier", orange.RuleClassifier, self.setRuleClassifier)]
        self.outputs = [("Data", ExampleTable), ("Features", AttributeList)]
        
        self.show_Rule_length = True
        self.show_Rule_quality = True
        self.show_Coverage = True
        self.show_Predicted_class = True
        self.show_Distribution = True
        self.show_Rule = True
        
        self.autoCommit = False
        self.selectedAttrsOnly = True
        
        
        self.loadSettings()
        
        #####
        # GUI
        #####
        
        box = OWGUI.widgetBox(self.controlArea, "Show Info", addSpace=True)
        box.layout().setSpacing(3)
        self.headers = ["Rule length",
                        "Rule quality",
                        "Coverage",
                        "Predicted class",
                        "Distribution",
                        "Rule"]
        
        for i, header in enumerate(self.headers):
            OWGUI.checkBox(box, self, "show_%s" % header.replace(" ", "_"), header,
                           tooltip="Show %s column" % header.lower(),
                           callback=self.updateVisibleColumns)
            
        box = OWGUI.widgetBox(self.controlArea, "Output")
        box.layout().setSpacing(3)
        cb = OWGUI.checkBox(box, self, "autoCommit", "Commit on any change",
                            callback=self.commitIf)
        
        OWGUI.checkBox(box, self, "selectedAttrsOnly", "Selected attributes only",
                       tooltip="Send selected attributes only",
                       callback=self.commitIf)
        
        b = OWGUI.button(box, self, "Commit", callback=self.commit, default=True)
        OWGUI.setStopper(self, b, cb, "changedFlag", callback=self.commit)
        
        OWGUI.rubber(self.controlArea)
        
        self.tableView = QTableView()
        self.tableView.setItemDelegate(PyObjectItemDelegate(self))
        self.tableView.setItemDelegateForColumn(1, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(2, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(4, DistributionItemDelegate(self))
        self.tableView.setItemDelegateForColumn(5, MultiLineStringItemDelegate(self))
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QTableView.SelectRows)
        self.tableView.setAlternatingRowColors(True)
        
        self.rulesTableModel = PyTableModel([], self.headers)
        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        
        self.tableView.setModel(self.proxyModel)
        self.connect(self.tableView.selectionModel(),
                     SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
                     lambda is1, is2: self.commitIf())
        self.connect(self.tableView.horizontalHeader(), SIGNAL("sectionClicked(int)"), lambda section: self.tableView.resizeRowsToContents())
        self.mainArea.layout().addWidget(self.tableView)

        self.updateVisibleColumns()
        
        self.changedFlag = False
        self.classifier = None
        self.rules = []
        self.resize(800, 600)
class OWCN2RulesViewer(OWWidget):
    settingsList = ["show_Rule_length", "show_Rule_quality", "show_Coverage",
                    "show_Predicted_class", "show_Distribution", "show_Rule"]
    
    def __init__(self, parent=None, signalManager=None, name="CN2 Rules Viewer"):
        OWWidget.__init__(self, parent, signalManager, name)
        self.inputs = [("Rule Classifier", orange.RuleClassifier, self.setRuleClassifier)]
        self.outputs = [("Data", ExampleTable), ("Features", AttributeList)]
        
        self.show_Rule_length = True
        self.show_Rule_quality = True
        self.show_Coverage = True
        self.show_Predicted_class = True
        self.show_Distribution = True
        self.show_Rule = True
        
        self.autoCommit = False
        self.selectedAttrsOnly = True
        
        
        self.loadSettings()
        
        #####
        # GUI
        #####
        
        box = OWGUI.widgetBox(self.controlArea, "Show Info", addSpace=True)
        box.layout().setSpacing(3)
        self.headers = ["Rule length",
                        "Rule quality",
                        "Coverage",
                        "Predicted class",
                        "Distribution",
                        "Rule"]
        
        for i, header in enumerate(self.headers):
            OWGUI.checkBox(box, self, "show_%s" % header.replace(" ", "_"), header,
                           tooltip="Show %s column" % header.lower(),
                           callback=self.updateVisibleColumns)
            
        box = OWGUI.widgetBox(self.controlArea, "Output")
        box.layout().setSpacing(3)
        cb = OWGUI.checkBox(box, self, "autoCommit", "Commit on any change",
                            callback=self.commitIf)
        
        OWGUI.checkBox(box, self, "selectedAttrsOnly", "Selected attributes only",
                       tooltip="Send selected attributes only",
                       callback=self.commitIf)
        
        b = OWGUI.button(box, self, "Commit", callback=self.commit, default=True)
        OWGUI.setStopper(self, b, cb, "changedFlag", callback=self.commit)
        
        OWGUI.rubber(self.controlArea)
        
        self.tableView = QTableView()
        self.tableView.setItemDelegate(PyObjectItemDelegate(self))
        self.tableView.setItemDelegateForColumn(1, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(2, PyFloatItemDelegate(self))
        self.tableView.setItemDelegateForColumn(4, DistributionItemDelegate(self))
        self.tableView.setItemDelegateForColumn(5, MultiLineStringItemDelegate(self))
        self.tableView.setSortingEnabled(True)
        self.tableView.setSelectionBehavior(QTableView.SelectRows)
        self.tableView.setAlternatingRowColors(True)
        
        self.rulesTableModel = PyTableModel([], self.headers)
        self.proxyModel = QSortFilterProxyModel(self)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        
        self.tableView.setModel(self.proxyModel)
        self.connect(self.tableView.selectionModel(),
                     SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
                     lambda is1, is2: self.commitIf())
        self.connect(self.tableView.horizontalHeader(), SIGNAL("sectionClicked(int)"), lambda section: self.tableView.resizeRowsToContents())
        self.mainArea.layout().addWidget(self.tableView)

        self.updateVisibleColumns()
        
        self.changedFlag = False
        self.classifier = None
        self.rules = []
        self.resize(800, 600)

    def sendReport(self):
        nrules = self.rulesTableModel.rowCount()
        print nrules
        if not nrules:
            self.reportRaw("<p>No rules.</p>")
            return
        
        shown = [i for i, header in enumerate(self.headers) if getattr(self, "show_%s" % header.replace(" ", "_"))]
        rep = '<table>\n<tr style="height: 2px"><th colspan="11"  style="border-bottom: thin solid black; height: 2px;">\n'
        rep += "<tr>"+"".join("<th>%s</th>" % self.headers[i] for i in shown)+"</tr>\n"
        for row in range(nrules):
            rep += "<tr>"
            for col in shown:
                data = _toPyObject(self.rulesTableModel.data(self.rulesTableModel.createIndex(row, col)))
                if col==4:
                    rep += "<td>%s</td>" % ":".join(map(str, data))
                elif col in (0, 3):
                    rep += '<td align="center">%s</td>' % data
                elif col in (1, 2):
                    rep += '<td align="right">%.3f&nbsp;</td>' % data
                else:
                    rep += '<td>%s</td>' % data
        rep += '<tr style="height: 2px"><th colspan="11"  style="border-bottom: thin solid black; height: 2px;">\n</table>\n'
        self.reportRaw(rep)
        
    def setRuleClassifier(self, classifier=None):
        self.classifier = classifier
        if classifier is not None:
            self.rules = classifier.rules
        else:
            self.rules = []
        
    def handleNewSignals(self):
        self.updateRulesModel()
        self.commit()
    
    def updateRulesModel(self):
        table = []
        if self.classifier is not None:
            for i, r in enumerate(self.classifier.rules):
                table.append((int(r.complexity),
                              r.quality,
                              r.classDistribution.abs,
                              str(r.classifier.defaultValue),
                              r.classDistribution,
                              self.ruleText(r)))

        self.rulesTableModel = PyTableModel(table, self.headers)
        self.proxyModel.setSourceModel(self.rulesTableModel)
        self.tableView.resizeColumnsToContents()
        self.tableView.resizeRowsToContents()
        self.updateVisibleColumns() # if the widget got data for the first time
            
    
    def ruleText(self, rule):
        text = rule_to_string(rule, show_distribution=False)
        p = re.compile(r"[0-9]\.[0-9]+")
        text = p.sub(lambda match: "%.2f" % float(match.group()[0]), text)
        text = text.replace("AND", "AND\n   ")
        text = text.replace("THEN", "\nTHEN")
        return text
    
    def updateVisibleColumns(self):
        anyVisible = False
        for i, header in enumerate(self.headers):
            visible = getattr(self, "show_%s" % header.replace(" ", "_"))
            self.tableView.horizontalHeader().setSectionHidden(i, not visible)
            anyVisible = anyVisible or visible
        
        # report button is not available if not running canvas
        if hasattr(self, "reportButton"):
            self.reportButton.setEnabled(anyVisible)

    
    def commitIf(self):
        if self.autoCommit:
            self.commit()
        else:
            self.changedFlag = True
            
    def selectedAttrsFromRules(self, rules):
        selected = []
        for rule in rules:
            for c in rule.filter.conditions:
                selected.append(rule.filter.domain[c.position])
        return set(selected)
    
    def selectedExamplesFromRules(self, rules, examples):
        selected = []
        for rule in rules:
            selected.extend(examples.filterref(rule.filter))
            rule.filter.negate=1
            examples = examples.filterref(rule.filter)
            rule.filter.negate=0
        return selected
             
    def commit(self):
        rows = self.tableView.selectionModel().selectedRows()
        rows = [self.proxyModel.mapToSource(index) for index in rows]
        rows = [index.row() for index in rows]
        selectedRules = [self.classifier.rules[row] for row in rows]
        
        if selectedRules:
            examples = self.classifier.examples
            selectedExamples = self.selectedExamplesFromRules(selectedRules, self.classifier.examples)
            selectedAttrs = self.selectedAttrsFromRules(selectedRules)
            selectedAttrs = [attr for attr in examples.domain.attributes if attr in selectedAttrs] # restore the order
            if self.selectedAttrsOnly:
                domain = orange.Domain(selectedAttrs, examples.domain.classVar)
                domain.addmetas(examples.domain.getmetas())
                selectedExamples = orange.ExampleTable(domain, selectedExamples)
            else:
                selectedExamples = orange.ExampleTable(selectedExamples)
                
            self.send("Data", selectedExamples)
            self.send("Features", orange.VarList(list(selectedAttrs)))
        
        else:
            self.send("Data", None)
            self.send("Features", None)
        
        self.changedFlag = False