[4] | 1 | /* |
---|
| 2 | * This program is free software; you can redistribute it and/or modify |
---|
| 3 | * it under the terms of the GNU General Public License as published by |
---|
| 4 | * the Free Software Foundation; either version 2 of the License, or |
---|
| 5 | * (at your option) any later version. |
---|
| 6 | * |
---|
| 7 | * This program is distributed in the hope that it will be useful, |
---|
| 8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
| 9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
| 10 | * GNU General Public License for more details. |
---|
| 11 | * |
---|
| 12 | * You should have received a copy of the GNU General Public License |
---|
| 13 | * along with this program; if not, write to the Free Software |
---|
| 14 | * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
---|
| 15 | */ |
---|
| 16 | |
---|
| 17 | /* |
---|
| 18 | * NaiveBayesMultinomialUpdateable.java |
---|
| 19 | * Copyright (C) 2003 University of Waikato, Hamilton, New Zealand |
---|
| 20 | * Copyright (C) 2007 Jiang Su (incremental version) |
---|
| 21 | */ |
---|
| 22 | |
---|
| 23 | package weka.classifiers.bayes; |
---|
| 24 | |
---|
| 25 | import weka.classifiers.UpdateableClassifier; |
---|
| 26 | import weka.core.Instance; |
---|
| 27 | import weka.core.Instances; |
---|
| 28 | import weka.core.RevisionUtils; |
---|
| 29 | import weka.core.Utils; |
---|
| 30 | |
---|
| 31 | /** |
---|
| 32 | <!-- globalinfo-start --> |
---|
| 33 | * Class for building and using a multinomial Naive Bayes classifier. For more information see,<br/> |
---|
| 34 | * <br/> |
---|
| 35 | * Andrew Mccallum, Kamal Nigam: A Comparison of Event Models for Naive Bayes Text Classification. In: AAAI-98 Workshop on 'Learning for Text Categorization', 1998.<br/> |
---|
| 36 | * <br/> |
---|
| 37 | * The core equation for this classifier:<br/> |
---|
| 38 | * <br/> |
---|
| 39 | * P[Ci|D] = (P[D|Ci] x P[Ci]) / P[D] (Bayes rule)<br/> |
---|
| 40 | * <br/> |
---|
| 41 | * where Ci is class i and D is a document.<br/> |
---|
| 42 | * <br/> |
---|
| 43 | * Incremental version of the algorithm. |
---|
| 44 | * <p/> |
---|
| 45 | <!-- globalinfo-end --> |
---|
| 46 | * |
---|
| 47 | <!-- technical-bibtex-start --> |
---|
| 48 | * BibTeX: |
---|
| 49 | * <pre> |
---|
| 50 | * @inproceedings{Mccallum1998, |
---|
| 51 | * author = {Andrew Mccallum and Kamal Nigam}, |
---|
| 52 | * booktitle = {AAAI-98 Workshop on 'Learning for Text Categorization'}, |
---|
| 53 | * title = {A Comparison of Event Models for Naive Bayes Text Classification}, |
---|
| 54 | * year = {1998} |
---|
| 55 | * } |
---|
| 56 | * </pre> |
---|
| 57 | * <p/> |
---|
| 58 | <!-- technical-bibtex-end --> |
---|
| 59 | * |
---|
| 60 | <!-- options-start --> |
---|
| 61 | * Valid options are: <p/> |
---|
| 62 | * |
---|
| 63 | * <pre> -D |
---|
| 64 | * If set, classifier is run in debug mode and |
---|
| 65 | * may output additional info to the console</pre> |
---|
| 66 | * |
---|
| 67 | <!-- options-end --> |
---|
| 68 | * |
---|
| 69 | * @author Andrew Golightly (acg4@cs.waikato.ac.nz) |
---|
| 70 | * @author Bernhard Pfahringer (bernhard@cs.waikato.ac.nz) |
---|
| 71 | * @author Jiang Su |
---|
| 72 | * @version $Revision: 1.3 $ |
---|
| 73 | */ |
---|
| 74 | public class NaiveBayesMultinomialUpdateable |
---|
| 75 | extends NaiveBayesMultinomial |
---|
| 76 | implements UpdateableClassifier { |
---|
| 77 | |
---|
| 78 | /** for serialization */ |
---|
| 79 | private static final long serialVersionUID = -7204398796974263186L; |
---|
| 80 | |
---|
| 81 | /** the word count per class */ |
---|
| 82 | protected double[] m_wordsPerClass; |
---|
| 83 | |
---|
| 84 | /** |
---|
| 85 | * Returns a string describing this classifier |
---|
| 86 | * |
---|
| 87 | * @return a description of the classifier suitable for |
---|
| 88 | * displaying in the explorer/experimenter gui |
---|
| 89 | */ |
---|
| 90 | public String globalInfo() { |
---|
| 91 | return |
---|
| 92 | super.globalInfo() + "\n\n" |
---|
| 93 | + "Incremental version of the algorithm."; |
---|
| 94 | } |
---|
| 95 | |
---|
| 96 | /** |
---|
| 97 | * Generates the classifier. |
---|
| 98 | * |
---|
| 99 | * @param instances set of instances serving as training data |
---|
| 100 | * @throws Exception if the classifier has not been generated successfully |
---|
| 101 | */ |
---|
| 102 | public void buildClassifier(Instances instances) throws Exception { |
---|
| 103 | // can classifier handle the data? |
---|
| 104 | getCapabilities().testWithFail(instances); |
---|
| 105 | |
---|
| 106 | // remove instances with missing class |
---|
| 107 | instances = new Instances(instances); |
---|
| 108 | instances.deleteWithMissingClass(); |
---|
| 109 | |
---|
| 110 | m_headerInfo = new Instances(instances, 0); |
---|
| 111 | m_numClasses = instances.numClasses(); |
---|
| 112 | m_numAttributes = instances.numAttributes(); |
---|
| 113 | m_probOfWordGivenClass = new double[m_numClasses][]; |
---|
| 114 | m_wordsPerClass = new double[m_numClasses]; |
---|
| 115 | m_probOfClass = new double[m_numClasses]; |
---|
| 116 | |
---|
| 117 | // initialising the matrix of word counts |
---|
| 118 | // NOTE: Laplace estimator introduced in case a word that does not |
---|
| 119 | // appear for a class in the training set does so for the test set |
---|
| 120 | double laplace = 1; |
---|
| 121 | for (int c = 0; c < m_numClasses; c++) { |
---|
| 122 | m_probOfWordGivenClass[c] = new double[m_numAttributes]; |
---|
| 123 | m_probOfClass[c] = laplace; |
---|
| 124 | m_wordsPerClass[c] = laplace * m_numAttributes; |
---|
| 125 | for(int att = 0; att<m_numAttributes; att++) { |
---|
| 126 | m_probOfWordGivenClass[c][att] = laplace; |
---|
| 127 | } |
---|
| 128 | } |
---|
| 129 | |
---|
| 130 | for (int i = 0; i < instances.numInstances(); i++) |
---|
| 131 | updateClassifier(instances.instance(i)); |
---|
| 132 | } |
---|
| 133 | |
---|
| 134 | /** |
---|
| 135 | * Updates the classifier with the given instance. |
---|
| 136 | * |
---|
| 137 | * @param instance the new training instance to include in the model |
---|
| 138 | * @throws Exception if the instance could not be incorporated in |
---|
| 139 | * the model. |
---|
| 140 | */ |
---|
| 141 | public void updateClassifier(Instance instance) throws Exception { |
---|
| 142 | int classIndex = (int) instance.value(instance.classIndex()); |
---|
| 143 | m_probOfClass[classIndex] += instance.weight(); |
---|
| 144 | |
---|
| 145 | for (int a = 0; a < instance.numValues(); a++) { |
---|
| 146 | if (instance.index(a) == instance.classIndex() || |
---|
| 147 | instance.isMissing(a)) |
---|
| 148 | continue; |
---|
| 149 | |
---|
| 150 | double numOccurences = instance.valueSparse(a) * instance.weight(); |
---|
| 151 | if (numOccurences < 0) |
---|
| 152 | throw new Exception( |
---|
| 153 | "Numeric attribute values must all be greater or equal to zero."); |
---|
| 154 | m_wordsPerClass[classIndex] += numOccurences; |
---|
| 155 | m_probOfWordGivenClass[classIndex][instance.index(a)] += numOccurences; |
---|
| 156 | } |
---|
| 157 | } |
---|
| 158 | |
---|
| 159 | /** |
---|
| 160 | * Calculates the class membership probabilities for the given test |
---|
| 161 | * instance. |
---|
| 162 | * |
---|
| 163 | * @param instance the instance to be classified |
---|
| 164 | * @return predicted class probability distribution |
---|
| 165 | * @throws Exception if there is a problem generating the prediction |
---|
| 166 | */ |
---|
| 167 | public double[] distributionForInstance(Instance instance) throws Exception { |
---|
| 168 | double[] probOfClassGivenDoc = new double[m_numClasses]; |
---|
| 169 | |
---|
| 170 | // calculate the array of log(Pr[D|C]) |
---|
| 171 | double[] logDocGivenClass = new double[m_numClasses]; |
---|
| 172 | for (int c = 0; c < m_numClasses; c++) { |
---|
| 173 | logDocGivenClass[c] += Math.log(m_probOfClass[c]); |
---|
| 174 | int allWords = 0; |
---|
| 175 | for (int i = 0; i < instance.numValues(); i++) { |
---|
| 176 | if (instance.index(i) == instance.classIndex()) |
---|
| 177 | continue; |
---|
| 178 | double frequencies = instance.valueSparse(i); |
---|
| 179 | allWords += frequencies; |
---|
| 180 | logDocGivenClass[c] += frequencies * |
---|
| 181 | Math.log(m_probOfWordGivenClass[c][instance.index(i)]); |
---|
| 182 | } |
---|
| 183 | logDocGivenClass[c] -= allWords * Math.log(m_wordsPerClass[c]); |
---|
| 184 | } |
---|
| 185 | |
---|
| 186 | double max = logDocGivenClass[Utils.maxIndex(logDocGivenClass)]; |
---|
| 187 | for (int i = 0; i < m_numClasses; i++) |
---|
| 188 | probOfClassGivenDoc[i] = Math.exp(logDocGivenClass[i] - max); |
---|
| 189 | |
---|
| 190 | Utils.normalize(probOfClassGivenDoc); |
---|
| 191 | |
---|
| 192 | return probOfClassGivenDoc; |
---|
| 193 | } |
---|
| 194 | |
---|
| 195 | /** |
---|
| 196 | * Returns a string representation of the classifier. |
---|
| 197 | * |
---|
| 198 | * @return a string representation of the classifier |
---|
| 199 | */ |
---|
| 200 | public String toString() { |
---|
| 201 | StringBuffer result = new StringBuffer(); |
---|
| 202 | |
---|
| 203 | result.append("The independent probability of a class\n"); |
---|
| 204 | result.append("--------------------------------------\n"); |
---|
| 205 | |
---|
| 206 | for (int c = 0; c < m_numClasses; c++) |
---|
| 207 | result.append(m_headerInfo.classAttribute().value(c)).append("\t"). |
---|
| 208 | append(Double.toString(m_probOfClass[c])).append("\n"); |
---|
| 209 | |
---|
| 210 | result.append("\nThe probability of a word given the class\n"); |
---|
| 211 | result.append("-----------------------------------------\n\t"); |
---|
| 212 | |
---|
| 213 | for (int c = 0; c < m_numClasses; c++) |
---|
| 214 | result.append(m_headerInfo.classAttribute().value(c)).append("\t"); |
---|
| 215 | |
---|
| 216 | result.append("\n"); |
---|
| 217 | |
---|
| 218 | for (int w = 0; w < m_numAttributes; w++) { |
---|
| 219 | result.append(m_headerInfo.attribute(w).name()).append("\t"); |
---|
| 220 | for (int c = 0; c < m_numClasses; c++) |
---|
| 221 | result.append( |
---|
| 222 | Double.toString(Math.exp(m_probOfWordGivenClass[c][w]))).append("\t"); |
---|
| 223 | result.append("\n"); |
---|
| 224 | } |
---|
| 225 | |
---|
| 226 | return result.toString(); |
---|
| 227 | } |
---|
| 228 | |
---|
| 229 | /** |
---|
| 230 | * Returns the revision string. |
---|
| 231 | * |
---|
| 232 | * @return the revision |
---|
| 233 | */ |
---|
| 234 | public String getRevision() { |
---|
| 235 | return RevisionUtils.extract("$Revision: 1.3 $"); |
---|
| 236 | } |
---|
| 237 | |
---|
| 238 | /** |
---|
| 239 | * Main method for testing this class. |
---|
| 240 | * |
---|
| 241 | * @param args the options |
---|
| 242 | */ |
---|
| 243 | public static void main(String[] args) { |
---|
| 244 | runClassifier(new NaiveBayesMultinomialUpdateable(), args); |
---|
| 245 | } |
---|
| 246 | } |
---|