source: orange/Orange/OrangeWidgets/Classify/OWNaiveBayes.py @ 11095:9a01e272802c

Revision 11095:9a01e272802c, 8.5 KB checked in by Ales Erjavec <ales.erjavec@…>, 19 months ago (diff)

New style widget meta descriptions.

The widget meta description using module global namespace.

Line 
1"""
2<name>Naive Bayes</name>
3<description>Naive Bayesian learner/classifier.</description>
4<icon>icons/NaiveBayes.png</icon>
5<contact>Janez Demsar (janez.demsar(@at@)fri.uni-lj.si)</contact>
6<priority>10</priority>
7"""
8
9from OWWidget import *
10import OWGUI, orange
11from orngWrap import PreprocessedLearner
12from exceptions import Exception
13
14NAME = "Naive Bayes"
15DESCRIPTION = "Naive Bayesian learner/classifier."
16
17ICON = "icons/NaiveBayes.png"
18CATEGORY = "Classify"
19PRIORITY = 10
20
21INPUTS = [("Data", ExampleTable, "setData"),
22          ("Preprocess", PreprocessedLearner, "setPreprocessor")]
23
24OUTPUTS = [("Learner", orange.Learner),
25           ("Naive Bayesian Classifier", orange.BayesClassifier)]
26
27
28import warnings
29warnings.filterwarnings("ignore", r"'BayesLearner': invalid conditional probability or no attributes \(the classifier will use apriori probabilities\)", orange.KernelWarning, ".*OWNaiveBayes", 136)
30
31
32class OWNaiveBayes(OWWidget):
33    settingsList = ["m_estimator.m", "name", "probEstimation", "condProbEstimation", "adjustThreshold", "windowProportion"]
34
35    def __init__(self, parent=None, signalManager = None, name='NaiveBayes'):
36        OWWidget.__init__(self, parent, signalManager, name, wantMainArea = 0, resizingEnabled = 0)
37        self.inputs = [("Data", ExampleTable, self.setData), ("Preprocess", PreprocessedLearner, self.setPreprocessor)]
38        self.outputs = [("Learner", orange.Learner),("Naive Bayesian Classifier", orange.BayesClassifier)]
39
40        self.m_estimator = orange.ProbabilityEstimatorConstructor_m()
41        self.estMethods=[("Relative Frequency", orange.ProbabilityEstimatorConstructor_relative()),
42                         ("Laplace", orange.ProbabilityEstimatorConstructor_Laplace()),
43                         #("m-Estimate", self.m_estimator)
44                         ]
45        self.condEstMethods=[("<same as above>", None),
46                             ("Relative Frequency", orange.ConditionalProbabilityEstimatorConstructor_ByRows(estimatorConstructor=orange.ProbabilityEstimatorConstructor_relative())),
47                             ("Laplace", orange.ConditionalProbabilityEstimatorConstructor_ByRows(estimatorConstructor=orange.ProbabilityEstimatorConstructor_Laplace())),
48                             ("m-Estimate", orange.ConditionalProbabilityEstimatorConstructor_ByRows(estimatorConstructor=self.m_estimator))]
49
50        self.m_estimator.m = 2.0
51        self.name = 'Naive Bayes'
52        self.probEstimation = 0
53        self.condProbEstimation = 0
54        self.adjustThreshold = 0
55        self.windowProportion = 0.5
56        self.loessPoints = 100
57
58        self.preprocessor = None
59        self.data = None
60        self.loadSettings()
61
62
63        OWGUI.lineEdit(self.controlArea, self, 'name', box='Learner/Classifier Name', \
64                 tooltip='Name to be used by other widgets to identify your learner/classifier.')
65        OWGUI.separator(self.controlArea)
66
67        glay = QGridLayout()
68        box = OWGUI.widgetBox(self.controlArea, 'Probability estimation', orientation = glay)
69
70        #glay.addWidget(OWGUI.separator(box, height=5), 0, 0)
71
72        glay.addWidget(OWGUI.widgetLabel(box, "Prior"), 1, 0)
73
74        glay.addWidget(OWGUI.comboBox(box, self, 'probEstimation', items=[e[0] for e in self.estMethods], tooltip='Method for estimating the prior probability.'),
75                        1, 2)
76
77        glay.addWidget(OWGUI.widgetLabel(box, "Conditional (for discrete)"), 2, 0)
78        glay.addWidget(OWGUI.comboBox(box, self, 'condProbEstimation', items=[e[0] for e in self.condEstMethods], tooltip='Conditional probability estimation method used for discrete attributes.', callback=self.refreshControls),
79                       2, 2)
80
81        glay.addWidget(OWGUI.widgetLabel(box, "     " + "Parameter for m-estimate" + " "), 3, 0)
82        mValid = QDoubleValidator(self.controlArea)
83        mValid.setRange(0,10000,1)
84        self.mwidget = OWGUI.lineEdit(box, self, 'm_estimator.m', valueType = float, validator = mValid)
85        glay.addWidget(self.mwidget, 3, 2)
86
87        glay.addWidget(OWGUI.separator(box), 4, 0)
88
89        glay.addWidget(OWGUI.widgetLabel(box, 'Size of LOESS window'), 5, 0)
90        kernelSizeValid = QDoubleValidator(self.controlArea)
91        kernelSizeValid.setRange(0,1,3)
92        glay.addWidget(OWGUI.lineEdit(box, self, 'windowProportion',
93                       tooltip='Proportion of examples used for local learning in loess.\nUse 0 to learn from few local instances (3) and 1 to learn from all in the data set (this kind of learning is not local anymore).',
94                       valueType = float, validator = kernelSizeValid),
95                       5, 2)
96
97        glay.addWidget(OWGUI.widgetLabel(box, 'LOESS sample points'), 6, 0)
98        pointsValid = QIntValidator(20, 1000, self.controlArea)
99        glay.addWidget(OWGUI.lineEdit(box, self, 'loessPoints',
100                       tooltip='Number of points in computation of LOESS (20-1000).',
101                       valueType = int, validator = pointsValid),
102                       6, 2)
103
104        OWGUI.separator(self.controlArea)
105
106        OWGUI.checkBox(self.controlArea, self, "adjustThreshold", "Adjust threshold (for binary classes)", box = "Threshold")
107
108        OWGUI.separator(self.controlArea)
109#        box = OWGUI.widgetBox(self.controlArea, "Apply", orientation=1)
110        applyButton = OWGUI.button(self.controlArea, self, "&Apply", callback=self.applyLearner, default=True)
111
112        OWGUI.rubber(self.controlArea)
113        self.refreshControls()
114        self.applyLearner()
115
116
117    def refreshControls(self, *a):
118        self.mwidget.setEnabled(self.condProbEstimation==3)
119
120    def applyLearner(self):
121        self.warning(0)
122        if float(self.m_estimator.m) < 0:
123            self.warning(0, "Parameter m should be positive")
124            self.learner = None
125
126        elif float(self.windowProportion) < 0 or float(self.windowProportion) > 1:
127            self.warning(0, "Window proportion for LOESS should be between 0.0 and 1.0")
128            self.learner = None
129
130        else:
131            self.learner = orange.BayesLearner(name = self.name, adjustThreshold = self.adjustThreshold)
132            self.learner.estimatorConstructor = self.estMethods[self.probEstimation][1]
133            if self.condProbEstimation:
134                self.learner.conditionalEstimatorConstructor = self.condEstMethods[self.condProbEstimation][1]
135                self.learner.conditionalEstimatorConstructorContinuous = orange.ConditionalProbabilityEstimatorConstructor_loess(
136                   windowProportion = self.windowProportion, nPoints = self.loessPoints)
137
138            if self.preprocessor:
139                self.learner = self.preprocessor.wrapLearner(self.learner)
140
141        self.send("Learner", self.learner)
142        self.applyData()
143        self.changed = False
144
145
146    def applyData(self):
147        self.error(1)
148        if self.data and self.learner:
149            try:
150                if self.preprocessor:
151                    classifier, data = self.learner(self.data, getData = True)
152                    classifier.setattr("data", data)
153                else:
154                    classifier = self.learner(self.data)
155                    classifier.setattr("data", self.data)
156                classifier.name = self.name
157            except Exception, (errValue):
158                classifier = None
159                self.error(1, "Naive Bayes error: " + str(errValue))
160        else:
161            classifier = None
162           
163        self.send("Naive Bayesian Classifier", classifier)
164
165
166    def setPreprocessor(self, pp):
167        self.preprocessor = pp
168        self.applyLearner()
169       
170    def setData(self,data):
171        self.data = self.isDataWithClass(data, orange.VarTypes.Discrete, checkMissing=True) and data or None
172        self.applyData()
173
174
175    def sendReport(self):
176        self.reportSettings("Learning parameters",
177                            [("Probability estimation", self.estMethods[self.probEstimation][0]),
178                             self.condProbEstimation and ("Conditional probability", self.condEstMethods[self.condProbEstimation][0]),
179                             self.condProbEstimation==3 and ("m for m-estimate", "%.1f" % self.m_estimator.m),
180                             ("LOESS window size", "%.1f" % self.windowProportion),
181                             ("Number of points in LOESS", "%i" % self.loessPoints),
182                             ("Adjust classification threshold", OWGUI.YesNo[self.adjustThreshold])
183                            ])
184        self.reportData(self.data)
185
186
187if __name__=="__main__":
188    a=QApplication(sys.argv)
189    ow=OWNaiveBayes()
190
191    ow.show()
192    a.exec_()
193    ow.saveSettings()
Note: See TracBrowser for help on using the repository browser.