~ubuntu-branches/ubuntu/trusty/weka/trusty-proposed

« back to all changes in this revision

Viewing changes to weka/classifiers/bayes/WAODE.java

  • Committer: Bazaar Package Importer
  • Author(s): Soeren Sonnenburg
  • Date: 2008-02-24 09:18:45 UTC
  • Revision ID: james.westby@ubuntu.com-20080224091845-1l8zy6fm6xipbzsr
Tags: upstream-3.5.7+tut1
ImportĀ upstreamĀ versionĀ 3.5.7+tut1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 *    WAODE.java
 
19
 *    Copyright 2006 Liangxiao Jiang
 
20
 */
 
21
 
 
22
package weka.classifiers.bayes;
 
23
 
 
24
import weka.classifiers.Classifier;
 
25
import weka.core.Capabilities;
 
26
import weka.core.Instance;
 
27
import weka.core.Instances;
 
28
import weka.core.Option;
 
29
import weka.core.TechnicalInformation;
 
30
import weka.core.TechnicalInformationHandler;
 
31
import weka.core.Utils;
 
32
import weka.core.Capabilities.Capability;
 
33
import weka.core.TechnicalInformation.Field;
 
34
import weka.core.TechnicalInformation.Type;
 
35
 
 
36
import java.util.Enumeration;
 
37
import java.util.Vector;
 
38
 
 
39
/**
 
40
 <!-- globalinfo-start -->
 
41
 * WAODE contructs the model called Weightily Averaged One-Dependence Estimators.<br/>
 
42
 * <br/>
 
43
 * For more information, see<br/>
 
44
 * <br/>
 
45
 * L. Jiang, H. Zhang: Weightily Averaged One-Dependence Estimators. In: Proceedings of the 9th Biennial Pacific Rim International Conference on Artificial Intelligence, PRICAI 2006, 970-974, 2006.
 
46
 * <p/>
 
47
 <!-- globalinfo-end -->
 
48
 *
 
49
 <!-- technical-bibtex-start -->
 
50
 * BibTeX:
 
51
 * <pre>
 
52
 * &#64;inproceedings{Jiang2006,
 
53
 *    author = {L. Jiang and H. Zhang},
 
54
 *    booktitle = {Proceedings of the 9th Biennial Pacific Rim International Conference on Artificial Intelligence, PRICAI 2006},
 
55
 *    pages = {970-974},
 
56
 *    series = {LNAI},
 
57
 *    title = {Weightily Averaged One-Dependence Estimators},
 
58
 *    volume = {4099},
 
59
 *    year = {2006}
 
60
 * }
 
61
 * </pre>
 
62
 * <p/>
 
63
 <!-- technical-bibtex-end -->
 
64
 *
 
65
 <!-- options-start -->
 
66
 * Valid options are: <p/>
 
67
 * 
 
68
 * <pre> -D
 
69
 *  If set, classifier is run in debug mode and
 
70
 *  may output additional info to the console</pre>
 
71
 * 
 
72
 * <pre> -I
 
73
 *  Whether to print some more internals.
 
74
 *  (default: no)</pre>
 
75
 * 
 
76
 <!-- options-end -->
 
77
 *
 
78
 * @author  Liangxiao Jiang (ljiang@cug.edu.cn)
 
79
 * @author  H. Zhang (hzhang@unb.ca)
 
80
 * @version $Revision: 1.2 $
 
81
 */
 
82
public class WAODE 
 
83
  extends Classifier
 
84
  implements TechnicalInformationHandler {
 
85
  
 
86
  /** for serialization */
 
87
  private static final long serialVersionUID = 2170978824284697882L;
 
88
 
 
89
  /** The number of each class value occurs in the dataset */
 
90
  private double[] m_ClassCounts;
 
91
  
 
92
  /** The number of each attribute value occurs in the dataset */
 
93
  private double[] m_AttCounts;
 
94
  
 
95
  /** The number of two attributes values occurs in the dataset */
 
96
  private double[][] m_AttAttCounts;
 
97
  
 
98
  /** The number of class and two attributes values occurs in the dataset */
 
99
  private double[][][] m_ClassAttAttCounts;
 
100
  
 
101
  /** The number of values for each attribute in the dataset */
 
102
  private int[] m_NumAttValues;
 
103
  
 
104
  /** The number of values for all attributes in the dataset */
 
105
  private int m_TotalAttValues;
 
106
  
 
107
  /** The number of classes in the dataset */
 
108
  private int m_NumClasses;
 
109
  
 
110
  /** The number of attributes including class in the dataset */
 
111
  private int m_NumAttributes;
 
112
  
 
113
  /** The number of instances in the dataset */
 
114
  private int m_NumInstances;
 
115
  
 
116
  /** The index of the class attribute in the dataset */
 
117
  private int m_ClassIndex;
 
118
  
 
119
  /** The starting index of each attribute in the dataset */
 
120
  private int[] m_StartAttIndex;
 
121
  
 
122
  /** The array of mutual information between each attribute and class */
 
123
  private double[] m_mutualInformation;
 
124
  
 
125
  /** the header information of the training data */
 
126
  private Instances m_Header = null;
 
127
  
 
128
  /** whether to print more internals in the toString method
 
129
   * @see #toString() */
 
130
  private boolean m_Internals = false;
 
131
 
 
132
  /** a ZeroR model in case no model can be built from the data */
 
133
  private Classifier m_ZeroR;
 
134
  
 
135
  /**
 
136
   * Returns a string describing this classifier
 
137
   * 
 
138
   * @return            a description of the classifier suitable for
 
139
   *                    displaying in the explorer/experimenter gui
 
140
   */
 
141
  public String globalInfo() {
 
142
    return 
 
143
        "WAODE contructs the model called Weightily Averaged One-Dependence "
 
144
      + "Estimators.\n\n"
 
145
      + "For more information, see\n\n"
 
146
      + getTechnicalInformation().toString();
 
147
  }
 
148
 
 
149
  /**
 
150
   * Gets an enumeration describing the available options.
 
151
   *
 
152
   * @return an enumeration of all the available options.
 
153
   */
 
154
  public Enumeration listOptions() {
 
155
    Vector result = new Vector();
 
156
    Enumeration enm = super.listOptions();
 
157
    while (enm.hasMoreElements())
 
158
      result.add(enm.nextElement());
 
159
      
 
160
    result.addElement(new Option(
 
161
        "\tWhether to print some more internals.\n"
 
162
        + "\t(default: no)",
 
163
        "I", 0, "-I"));
 
164
 
 
165
    return result.elements();
 
166
  }
 
167
 
 
168
 
 
169
  /**
 
170
   * Parses a given list of options. <p/>
 
171
   * 
 
172
   <!-- options-start -->
 
173
   * Valid options are: <p/>
 
174
   * 
 
175
   * <pre> -D
 
176
   *  If set, classifier is run in debug mode and
 
177
   *  may output additional info to the console</pre>
 
178
   * 
 
179
   * <pre> -I
 
180
   *  Whether to print some more internals.
 
181
   *  (default: no)</pre>
 
182
   * 
 
183
   <!-- options-end -->
 
184
   *
 
185
   * @param options the list of options as an array of strings
 
186
   * @throws Exception if an option is not supported
 
187
   */
 
188
  public void setOptions(String[] options) throws Exception {
 
189
    super.setOptions(options);
 
190
 
 
191
    setInternals(Utils.getFlag('I', options));
 
192
  }
 
193
 
 
194
  /**
 
195
   * Gets the current settings of the filter.
 
196
   *
 
197
   * @return an array of strings suitable for passing to setOptions
 
198
   */
 
199
  public String[] getOptions() {
 
200
    Vector        result;
 
201
    String[]      options;
 
202
    int           i;
 
203
 
 
204
    result = new Vector();
 
205
 
 
206
    options = super.getOptions();
 
207
    for (i = 0; i < options.length; i++)
 
208
      result.add(options[i]);
 
209
 
 
210
    if (getInternals())
 
211
      result.add("-I");
 
212
 
 
213
    return (String[]) result.toArray(new String[result.size()]);
 
214
  }
 
215
  
 
216
  /**
 
217
   * Returns the tip text for this property
 
218
   *
 
219
   * @return tip text for this property suitable for
 
220
   * displaying in the explorer/experimenter gui
 
221
   */
 
222
  public String internalsTipText() {
 
223
    return "Prints more internals of the classifier.";
 
224
  }
 
225
 
 
226
  /** 
 
227
   * Sets whether internals about classifier are printed via toString().
 
228
   *
 
229
   * @param value if internals should be printed
 
230
   * @see #toString()
 
231
   */
 
232
  public void setInternals(boolean value) {
 
233
    m_Internals = value;
 
234
  }
 
235
 
 
236
  /**
 
237
   * Gets whether more internals of the classifier are printed.
 
238
   *
 
239
   * @return true if more internals are printed
 
240
   */
 
241
  public boolean getInternals() {
 
242
    return m_Internals;
 
243
  }
 
244
 
 
245
  /**
 
246
   * Returns an instance of a TechnicalInformation object, containing 
 
247
   * detailed information about the technical background of this class,
 
248
   * e.g., paper reference or book this class is based on.
 
249
   * 
 
250
   * @return the technical information about this class
 
251
   */
 
252
  public TechnicalInformation getTechnicalInformation() {
 
253
    TechnicalInformation        result;
 
254
    
 
255
    result = new TechnicalInformation(Type.INPROCEEDINGS);
 
256
    result.setValue(Field.AUTHOR, "L. Jiang and H. Zhang");
 
257
    result.setValue(Field.TITLE, "Weightily Averaged One-Dependence Estimators");
 
258
    result.setValue(Field.BOOKTITLE, "Proceedings of the 9th Biennial Pacific Rim International Conference on Artificial Intelligence, PRICAI 2006");
 
259
    result.setValue(Field.YEAR, "2006");
 
260
    result.setValue(Field.PAGES, "970-974");
 
261
    result.setValue(Field.SERIES, "LNAI");
 
262
    result.setValue(Field.VOLUME, "4099");
 
263
 
 
264
    return result;
 
265
  }
 
266
 
 
267
  /**
 
268
   * Returns default capabilities of the classifier.
 
269
   *
 
270
   * @return      the capabilities of this classifier
 
271
   */
 
272
  public Capabilities getCapabilities() {
 
273
    Capabilities result = super.getCapabilities();
 
274
 
 
275
    // attributes
 
276
    result.enable(Capability.NOMINAL_ATTRIBUTES);
 
277
 
 
278
    // class
 
279
    result.enable(Capability.NOMINAL_CLASS);
 
280
    
 
281
    return result;
 
282
  }
 
283
  
 
284
  /**
 
285
   * Generates the classifier.
 
286
   *
 
287
   * @param instances set of instances serving as training data
 
288
   * @throws Exception if the classifier has not been generated successfully
 
289
   */
 
290
  public void buildClassifier(Instances instances) throws Exception {
 
291
    
 
292
    // can classifier handle the data?
 
293
    getCapabilities().testWithFail(instances);
 
294
 
 
295
    // only class? -> build ZeroR model
 
296
    if (instances.numAttributes() == 1) {
 
297
      System.err.println(
 
298
          "Cannot build model (only class attribute present in data!), "
 
299
          + "using ZeroR model instead!");
 
300
      m_ZeroR = new weka.classifiers.rules.ZeroR();
 
301
      m_ZeroR.buildClassifier(instances);
 
302
      return;
 
303
    }
 
304
    else {
 
305
      m_ZeroR = null;
 
306
    }
 
307
 
 
308
    // reset variable
 
309
    m_NumClasses = instances.numClasses();
 
310
    m_ClassIndex = instances.classIndex();
 
311
    m_NumAttributes = instances.numAttributes();
 
312
    m_NumInstances = instances.numInstances();
 
313
    m_TotalAttValues = 0;
 
314
    
 
315
    // allocate space for attribute reference arrays
 
316
    m_StartAttIndex = new int[m_NumAttributes];
 
317
    m_NumAttValues = new int[m_NumAttributes];
 
318
    
 
319
    // set the starting index of each attribute and the number of values for
 
320
    // each attribute and the total number of values for all attributes (not including class).
 
321
    for (int i = 0; i < m_NumAttributes; i++) {
 
322
      if (i != m_ClassIndex) {
 
323
        m_StartAttIndex[i] = m_TotalAttValues;
 
324
        m_NumAttValues[i] = instances.attribute(i).numValues();
 
325
        m_TotalAttValues += m_NumAttValues[i];
 
326
      }
 
327
      else {
 
328
        m_StartAttIndex[i] = -1;
 
329
        m_NumAttValues[i] = m_NumClasses;
 
330
      }
 
331
    }
 
332
    
 
333
    // allocate space for counts and frequencies
 
334
    m_ClassCounts = new double[m_NumClasses];
 
335
    m_AttCounts = new double[m_TotalAttValues];
 
336
    m_AttAttCounts = new double[m_TotalAttValues][m_TotalAttValues];
 
337
    m_ClassAttAttCounts = new double[m_NumClasses][m_TotalAttValues][m_TotalAttValues];
 
338
    m_Header = new Instances(instances, 0);
 
339
    
 
340
    // Calculate the counts
 
341
    for (int k = 0; k < m_NumInstances; k++) {
 
342
      int classVal=(int)instances.instance(k).classValue();
 
343
      m_ClassCounts[classVal] ++;
 
344
      int[] attIndex = new int[m_NumAttributes];
 
345
      for (int i = 0; i < m_NumAttributes; i++) {
 
346
        if (i == m_ClassIndex){
 
347
          attIndex[i] = -1;
 
348
        }
 
349
        else{
 
350
          attIndex[i] = m_StartAttIndex[i] + (int)instances.instance(k).value(i);
 
351
          m_AttCounts[attIndex[i]]++;
 
352
        }
 
353
      }
 
354
      for (int Att1 = 0; Att1 < m_NumAttributes; Att1++) {
 
355
        if (attIndex[Att1] == -1) continue;
 
356
        for (int Att2 = 0; Att2 < m_NumAttributes; Att2++) {
 
357
          if ((attIndex[Att2] != -1)) {
 
358
            m_AttAttCounts[attIndex[Att1]][attIndex[Att2]] ++;
 
359
            m_ClassAttAttCounts[classVal][attIndex[Att1]][attIndex[Att2]] ++;
 
360
          }
 
361
        }
 
362
      }
 
363
    }
 
364
    
 
365
    //compute mutual information between each attribute and class
 
366
    m_mutualInformation=new double[m_NumAttributes];
 
367
    for (int att=0;att<m_NumAttributes;att++){
 
368
      if (att == m_ClassIndex) continue;
 
369
      m_mutualInformation[att]=mutualInfo(att);
 
370
    }
 
371
  }
 
372
  
 
373
  /**
 
374
   * Computes mutual information between each attribute and class attribute.
 
375
   *
 
376
   * @param att is the attribute
 
377
   * @return the conditional mutual information between son and parent given class
 
378
   */
 
379
  private double mutualInfo(int att) {
 
380
    
 
381
    double mutualInfo=0;
 
382
    int attIndex=m_StartAttIndex[att];
 
383
    double[] PriorsClass = new double[m_NumClasses];
 
384
    double[] PriorsAttribute = new double[m_NumAttValues[att]];
 
385
    double[][] PriorsClassAttribute=new double[m_NumClasses][m_NumAttValues[att]];
 
386
    
 
387
    for (int i=0;i<m_NumClasses;i++){
 
388
      PriorsClass[i]=m_ClassCounts[i]/m_NumInstances;
 
389
    }
 
390
    
 
391
    for (int j=0;j<m_NumAttValues[att];j++){
 
392
      PriorsAttribute[j]=m_AttCounts[attIndex+j]/m_NumInstances;
 
393
    }
 
394
    
 
395
    for (int i=0;i<m_NumClasses;i++){
 
396
      for (int j=0;j<m_NumAttValues[att];j++){
 
397
        PriorsClassAttribute[i][j]=m_ClassAttAttCounts[i][attIndex+j][attIndex+j]/m_NumInstances;
 
398
      }
 
399
    }
 
400
    
 
401
    for (int i=0;i<m_NumClasses;i++){
 
402
      for (int j=0;j<m_NumAttValues[att];j++){
 
403
        mutualInfo+=PriorsClassAttribute[i][j]*log2(PriorsClassAttribute[i][j],PriorsClass[i]*PriorsAttribute[j]);
 
404
      }
 
405
    }
 
406
    return mutualInfo;
 
407
  }
 
408
  
 
409
  /**
 
410
   * compute the logarithm whose base is 2.
 
411
   *
 
412
   * @param x numerator of the fraction.
 
413
   * @param y denominator of the fraction.
 
414
   * @return the natual logarithm of this fraction.
 
415
   */
 
416
  private double log2(double x,double y){
 
417
    
 
418
    if (x < Utils.SMALL || y < Utils.SMALL)
 
419
      return 0.0;
 
420
    else
 
421
      return Math.log(x/y)/Math.log(2);
 
422
  }
 
423
  
 
424
  /**
 
425
   * Calculates the class membership probabilities for the given test instance
 
426
   *
 
427
   * @param instance the instance to be classified
 
428
   * @return predicted class probability distribution
 
429
   * @throws Exception if there is a problem generating the prediction
 
430
   */
 
431
  public double[] distributionForInstance(Instance instance) throws Exception {
 
432
    
 
433
    // default model?
 
434
    if (m_ZeroR != null) {
 
435
      return m_ZeroR.distributionForInstance(instance);
 
436
    }
 
437
    
 
438
    //Definition of local variables
 
439
    double[] probs = new double[m_NumClasses];
 
440
    double prob;
 
441
    double mutualInfoSum;
 
442
    
 
443
    // store instance's att values in an int array
 
444
    int[] attIndex = new int[m_NumAttributes];
 
445
    for (int att = 0; att < m_NumAttributes; att++) {
 
446
      if (att == m_ClassIndex)
 
447
        attIndex[att] = -1;
 
448
      else
 
449
        attIndex[att] = m_StartAttIndex[att] + (int)instance.value(att);
 
450
    }
 
451
    
 
452
    // calculate probabilities for each possible class value
 
453
    for (int classVal = 0; classVal < m_NumClasses; classVal++) {
 
454
      probs[classVal] = 0;
 
455
      prob=1;
 
456
      mutualInfoSum=0.0;
 
457
      for (int parent = 0; parent < m_NumAttributes; parent++) {
 
458
        if (attIndex[parent]==-1) continue;
 
459
        prob=(m_ClassAttAttCounts[classVal][attIndex[parent]][attIndex[parent]] + 1.0/(m_NumClasses*m_NumAttValues[parent]))/(m_NumInstances + 1.0);
 
460
        for (int son = 0; son < m_NumAttributes; son++) {
 
461
          if (attIndex[son]==-1 || son == parent) continue;
 
462
          prob*=(m_ClassAttAttCounts[classVal][attIndex[parent]][attIndex[son]] + 1.0/m_NumAttValues[son])/(m_ClassAttAttCounts[classVal][attIndex[parent]][attIndex[parent]] + 1.0);
 
463
        }
 
464
        mutualInfoSum+=m_mutualInformation[parent];
 
465
        probs[classVal]+=m_mutualInformation[parent]*prob;
 
466
      }
 
467
      probs[classVal]/=mutualInfoSum;
 
468
    }
 
469
    if (!Double.isNaN(Utils.sum(probs)))
 
470
      Utils.normalize(probs);
 
471
    return probs;
 
472
  }
 
473
  
 
474
  /**
 
475
   * returns a string representation of the classifier
 
476
   * 
 
477
   * @return string representation of the classifier
 
478
   */
 
479
  public String toString() {
 
480
    StringBuffer        result;
 
481
    String              classname;
 
482
    int                 i;
 
483
    
 
484
    // only ZeroR model?
 
485
    if (m_ZeroR != null) {
 
486
      result = new StringBuffer();
 
487
      result.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
 
488
      result.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n\n");
 
489
      result.append("Warning: No model could be built, hence ZeroR model is used:\n\n");
 
490
      result.append(m_ZeroR.toString());
 
491
    }
 
492
    else {
 
493
      classname = this.getClass().getName().replaceAll(".*\\.", "");
 
494
      result    = new StringBuffer();
 
495
      result.append(classname + "\n");
 
496
      result.append(classname.replaceAll(".", "=") + "\n\n");
 
497
 
 
498
      if (m_Header == null) {
 
499
        result.append("No Model built yet.\n");
 
500
      }
 
501
      else {
 
502
        if (getInternals()) {
 
503
          result.append("Mutual information of attributes with class attribute:\n");
 
504
          for (i = 0; i < m_Header.numAttributes(); i++) {
 
505
            // skip class
 
506
            if (i == m_Header.classIndex())
 
507
              continue;
 
508
 
 
509
            result.append(
 
510
                (i+1) + ". " + m_Header.attribute(i).name() + ": " 
 
511
                + Utils.doubleToString(m_mutualInformation[i], 6) + "\n");
 
512
          }
 
513
        }
 
514
        else {
 
515
          result.append("Model built successfully.\n");
 
516
        }
 
517
      }
 
518
    }
 
519
    
 
520
    return result.toString();
 
521
  }
 
522
  
 
523
  /**
 
524
   * Main method for testing this class.
 
525
   *
 
526
   * @param argv the commandline options, use -h to list all options
 
527
   */
 
528
  public static void main(String[] argv) {
 
529
    runClassifier(new WAODE(), argv);
 
530
  }
 
531
}