ReplaceMissingValuesFilter.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 7k
Category:

Windows Develop

Development Platform:

Java

  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.  *    ReplaceMissingValuesFilter.java
  18.  *    Copyright (C) 1999 Eibe Frank
  19.  *
  20.  */
  21. package weka.filters;
  22. import java.io.*;
  23. import java.util.*;
  24. import weka.core.*;
  25. /** 
  26.  * Replaces all missing values for nominal and numeric attributes in a 
  27.  * dataset with the modes and means from the training data.
  28.  *
  29.  * @author Eibe Frank (eibe@cs.waikato.ac.nz) 
  30.  * @version $Revision: 1.12 $
  31.  */
  32. public class ReplaceMissingValuesFilter extends Filter {
  33.   /** The modes and means */
  34.   private double[] m_ModesAndMeans = null;
  35.   /**
  36.    * Sets the format of the input instances.
  37.    *
  38.    * @param instanceInfo an Instances object containing the input 
  39.    * instance structure (any instances contained in the object are 
  40.    * ignored - only the structure is required).
  41.    * @return true if the outputFormat may be collected immediately
  42.    * @exception Exception if the input format can't be set 
  43.    * successfully
  44.    */
  45.   public boolean setInputFormat(Instances instanceInfo) 
  46.        throws Exception {
  47.     super.setInputFormat(instanceInfo);
  48.     setOutputFormat(instanceInfo);
  49.     m_ModesAndMeans = null;
  50.     return true;
  51.   }
  52.   /**
  53.    * Input an instance for filtering. Filter requires all
  54.    * training instances be read before producing output.
  55.    *
  56.    * @param instance the input instance
  57.    * @return true if the filtered instance may now be
  58.    * collected with output().
  59.    * @exception IllegalStateException if no input format has been set.
  60.    */
  61.   public boolean input(Instance instance) {
  62.     if (getInputFormat() == null) {
  63.       throw new IllegalStateException("No input instance format defined");
  64.     }
  65.     if (m_NewBatch) {
  66.       resetQueue();
  67.       m_NewBatch = false;
  68.     }
  69.     if (m_ModesAndMeans == null) {
  70.       bufferInput(instance);
  71.       return false;
  72.     } else {
  73.       convertInstance(instance);
  74.       return true;
  75.     }
  76.   }
  77.   /**
  78.    * Signify that this batch of input to the filter is finished. 
  79.    * If the filter requires all instances prior to filtering,
  80.    * output() may now be called to retrieve the filtered instances.
  81.    *
  82.    * @return true if there are instances pending output
  83.    * @exception IllegalStateException if no input structure has been defined
  84.    */
  85.   public boolean batchFinished() {
  86.     if (getInputFormat() == null) {
  87.       throw new IllegalStateException("No input instance format defined");
  88.     }
  89.     if (m_ModesAndMeans == null) {
  90.       // Compute modes and means
  91.       double sumOfWeights =  getInputFormat().sumOfWeights();
  92.       double[][] counts = new double[getInputFormat().numAttributes()][];
  93.       for (int i = 0; i < getInputFormat().numAttributes(); i++) {
  94. if (getInputFormat().attribute(i).isNominal()) {
  95.   counts[i] = new double[getInputFormat().attribute(i).numValues()];
  96.   counts[i][0] = sumOfWeights;
  97. }
  98.       }
  99.       double[] sums = new double[getInputFormat().numAttributes()];
  100.       for (int i = 0; i < sums.length; i++) {
  101. sums[i] = sumOfWeights;
  102.       }
  103.       double[] results = new double[getInputFormat().numAttributes()];
  104.       for (int j = 0; j < getInputFormat().numInstances(); j++) {
  105. Instance inst = getInputFormat().instance(j);
  106. for (int i = 0; i < inst.numValues(); i++) {
  107.   if (!inst.isMissingSparse(i)) {
  108.     double value = inst.valueSparse(i);
  109.     if (inst.attributeSparse(i).isNominal()) {
  110.       counts[inst.index(i)][(int)value] += inst.weight();
  111.       counts[inst.index(i)][0] -= inst.weight();
  112.     } else if (inst.attributeSparse(i).isNumeric()) {
  113.       results[inst.index(i)] += inst.weight() * inst.valueSparse(i);
  114.     }
  115.   } else {
  116.     if (inst.attributeSparse(i).isNominal()) {
  117.       counts[inst.index(i)][0] -= inst.weight();
  118.     } else if (inst.attributeSparse(i).isNumeric()) {
  119.       sums[inst.index(i)] -= inst.weight();
  120.     }
  121.   }
  122. }
  123.       }
  124.       m_ModesAndMeans = new double[getInputFormat().numAttributes()];
  125.       for (int i = 0; i < getInputFormat().numAttributes(); i++) {
  126. if (getInputFormat().attribute(i).isNominal()) {
  127.   m_ModesAndMeans[i] = (double)Utils.maxIndex(counts[i]);
  128. } else if (getInputFormat().attribute(i).isNumeric()) {
  129.   if (Utils.gr(sums[i], 0)) {
  130.     m_ModesAndMeans[i] = results[i] / sums[i];
  131.   }
  132. }
  133.       }
  134.       // Convert pending input instances
  135.       for(int i = 0; i < getInputFormat().numInstances(); i++) {
  136. convertInstance(getInputFormat().instance(i));
  137.       }
  138.     } 
  139.     // Free memory
  140.     flushInput();
  141.     m_NewBatch = true;
  142.     return (numPendingOutput() != 0);
  143.   }
  144.   /**
  145.    * Convert a single instance over. The converted instance is 
  146.    * added to the end of the output queue.
  147.    *
  148.    * @param instance the instance to convert
  149.    */
  150.   private void convertInstance(Instance instance) {
  151.   
  152.     Instance inst = null;
  153.     if (instance instanceof SparseInstance) {
  154.       double []vals = new double[instance.numValues()];
  155.       int []indices = new int[instance.numValues()];
  156.       int num = 0;
  157.       for (int j = 0; j < instance.numValues(); j++) {
  158. if (instance.isMissingSparse(j) &&
  159.     (instance.attributeSparse(j).isNominal() ||
  160.      instance.attributeSparse(j).isNumeric())) {
  161.   if (m_ModesAndMeans[instance.index(j)] != 0.0) {
  162.     vals[num] = m_ModesAndMeans[instance.index(j)];
  163.     indices[num] = instance.index(j);
  164.     num++;
  165.   } 
  166. } else {
  167.   vals[num] = instance.valueSparse(j);
  168.   indices[num] = instance.index(j);
  169.   num++;
  170. }
  171.       } 
  172.       if (num == instance.numValues()) {
  173. inst = new SparseInstance(instance.weight(), vals, indices,
  174.                                   instance.numAttributes());
  175.       } else {
  176. double []tempVals = new double[num];
  177. int []tempInd = new int[num];
  178. System.arraycopy(vals, 0, tempVals, 0, num);
  179. System.arraycopy(indices, 0, tempInd, 0, num);
  180. inst = new SparseInstance(instance.weight(), tempVals, tempInd,
  181.                                   instance.numAttributes());
  182.       }
  183.     } else {
  184.       double []vals = new double[getInputFormat().numAttributes()];
  185.       for (int j = 0; j < instance.numAttributes(); j++) {
  186. if (instance.isMissing(j) &&
  187.     (getInputFormat().attribute(j).isNominal() ||
  188.      getInputFormat().attribute(j).isNumeric())) {
  189.   vals[j] = m_ModesAndMeans[j]; 
  190. } else {
  191.   vals[j] = instance.value(j);
  192. }
  193.       } 
  194.       inst = new Instance(instance.weight(), vals);
  195.     } 
  196.     inst.setDataset(instance.dataset());
  197.     push(inst);
  198.   }
  199.   /**
  200.    * Main method for testing this class.
  201.    *
  202.    * @param argv should contain arguments to the filter: 
  203.    * use -h for help
  204.    */
  205.   public static void main(String [] argv) {
  206.     try {
  207.       if (Utils.getFlag('b', argv)) {
  208.   Filter.batchFilterFile(new ReplaceMissingValuesFilter(), argv);
  209.       } else {
  210. Filter.filterFile(new ReplaceMissingValuesFilter(), argv);
  211.       }
  212.     } catch (Exception ex) {
  213.       System.out.println(ex.getMessage());
  214.     }
  215.   }
  216. }