RemoveUseless.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 8k
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.  *    RemoveUseless.java
  18.  *    Copyright (C) 2002 Richard Kirkby
  19.  *
  20.  */
  21. package weka.filters.unsupervised.attribute;
  22. import weka.filters.*;
  23. import weka.core.*;
  24. import java.util.Enumeration;
  25. import java.util.Vector;
  26. /** 
  27.  * This filter removes attributes that do not vary at all or that vary too much.
  28.  * All constant attributes are deleted automatically, along with any that exceed
  29.  * the maximum percentage of variance parameter.<p>
  30.  *
  31.  * Valid filter-specific options are: <p>
  32.  *
  33.  * -M percentage <br>
  34.  * The maximum variance allowed before an attribute will be deleted (default 100).<p>
  35.  *
  36.  * @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
  37.  * @version $Revision: 1.1 $
  38.  */
  39. public class RemoveUseless extends Filter implements UnsupervisedFilter,
  40.      OptionHandler {
  41.   /** The type of attribute to delete */
  42.   protected double m_maxVariancePercentage = 100;
  43.   /**
  44.    * Sets the format of the input instances.
  45.    *
  46.    * @param instanceInfo an Instances object containing the input instance
  47.    * structure (any instances contained in the object are ignored - only the
  48.    * structure is required).
  49.    * @return true if the outputFormat may be collected immediately
  50.    * @exception Exception if the inputFormat can't be set successfully 
  51.    */ 
  52.   public boolean setInputFormat(Instances instanceInfo) throws Exception {
  53.     super.setInputFormat(instanceInfo);
  54.     return false;
  55.   }
  56.   /**
  57.    * Input an instance for filtering.
  58.    *
  59.    * @param instance the input instance
  60.    * @return true if the filtered instance may now be
  61.    * collected with output().
  62.    */
  63.   public boolean input(Instance instance) {
  64.     if (getInputFormat() == null) {
  65.       throw new IllegalStateException("No input instance format defined");
  66.     }
  67.     if (m_NewBatch) {
  68.       resetQueue();
  69.       m_NewBatch = false;
  70.     }
  71.     bufferInput(instance);
  72.     return false;
  73.   }
  74.   /**
  75.    * Signify that this batch of input to the filter is finished.
  76.    *
  77.    * @return true if there are instances pending output
  78.    */  
  79.   public boolean batchFinished() throws Exception {
  80.     if (getInputFormat() == null) {
  81.       throw new IllegalStateException("No input instance format defined");
  82.     }
  83.     // do filtering here
  84.     Instances toFilter = getInputFormat();
  85.     int[] attsToDelete = new int[toFilter.numAttributes()];
  86.     int numToDelete = 0;
  87.     for(int i = 0; i < toFilter.numAttributes(); i++) {
  88.       AttributeStats stats = toFilter.attributeStats(i);
  89.       if (stats.distinctCount < 2) {
  90. // remove constant attributes
  91. attsToDelete[numToDelete++] = i;
  92.       } else {
  93. // remove attributes that vary too much
  94. double variancePercent = (double) stats.distinctCount
  95.   / (double) stats.totalCount * 100.0;
  96. if (variancePercent > m_maxVariancePercentage) attsToDelete[numToDelete++] = i;
  97.       }
  98.     }
  99.     int[] finalAttsToDelete = new int[numToDelete];
  100.     System.arraycopy(attsToDelete, 0, finalAttsToDelete, 0, numToDelete);
  101.     
  102.     Remove attributeFilter = new Remove();
  103.     attributeFilter.setAttributeIndicesArray(finalAttsToDelete);
  104.     attributeFilter.setInvertSelection(false);
  105.     attributeFilter.setInputFormat(toFilter);
  106.     
  107.     for (int i = 0; i < toFilter.numInstances(); i++) {
  108.       attributeFilter.input(toFilter.instance(i));
  109.     }
  110.     attributeFilter.batchFinished();
  111.     Instance processed;
  112.     Instances outputDataset = attributeFilter.getOutputFormat();
  113.     
  114.     // restore old relation name to hide attribute filter stamp
  115.     outputDataset.setRelationName(toFilter.relationName());
  116.     
  117.     setOutputFormat(outputDataset);
  118.     while ((processed = attributeFilter.output()) != null) {
  119.       processed.setDataset(outputDataset);
  120.       push(processed);
  121.     }
  122.     flushInput();
  123.     m_NewBatch = true;
  124.     return (numPendingOutput() != 0);
  125.   }
  126.   /**
  127.    * Returns an enumeration describing the available options.
  128.    *
  129.    * @return an enumeration of all the available options.
  130.    */
  131.   public Enumeration listOptions() {
  132.     Vector newVector = new Vector(1);
  133.     newVector.addElement(new Option(
  134.     "tMaximum variance percentage allowed (default 100)",
  135.     "M", 1, "-M <max variance %>"));
  136.     return newVector.elements();
  137.   }
  138.   /**
  139.    * Parses the options for this object. Valid options are: <p>
  140.    *
  141.    * -M percentage <br>
  142.    * The maximum variance allowed before an attribute will be deleted (default 100).
  143.    *
  144.    * @param options the list of options as an array of strings
  145.    * @exception Exception if an option is not supported
  146.    */
  147.   public void setOptions(String[] options) throws Exception {
  148.     
  149.     String mString = Utils.getOption('M', options);
  150.     if (mString.length() != 0) {
  151.       setMaximumVariancePercentageAllowed((int) Double.valueOf(mString).doubleValue());
  152.     } else {
  153.       setMaximumVariancePercentageAllowed(100.0);
  154.     }
  155.     if (getInputFormat() != null) {
  156.       setInputFormat(getInputFormat());
  157.     }
  158.   }
  159.   /**
  160.    * Gets the current settings of the filter.
  161.    *
  162.    * @return an array of strings suitable for passing to setOptions
  163.    */
  164.   public String [] getOptions() {
  165.     String [] options = new String [2];
  166.     int current = 0;
  167.     options[current++] = "-M";
  168.     options[current++] = "" + getMaximumVariancePercentageAllowed();
  169.     
  170.     while (current < options.length) {
  171.       options[current++] = "";
  172.     }
  173.     return options;
  174.   }
  175.   /**
  176.    * Returns a string describing this filter
  177.    *
  178.    * @return a description of the filter suitable for
  179.    * displaying in the explorer/experimenter gui
  180.    */
  181.   public String globalInfo() {
  182.     return "Removes constant attributes, along with attributes to vary too much.";
  183.   }
  184.   /**
  185.    * Returns the tip text for this property
  186.    *
  187.    * @return tip text for this property suitable for
  188.    * displaying in the explorer/experimenter gui
  189.    */
  190.   public String maximumVariancePercentageAllowedTipText() {
  191.     return "Set the threshold for the highest variance allowed before an attribute will be deleted."
  192.       + "Specifically, if (number_of_distinct_values / total_number_of_values * 100)"
  193.       + " is greater than this value then the attribute will be removed.";
  194.   }
  195.   /**
  196.    * Sets the maximum variance attributes are allowed to have before they are
  197.    * deleted by the filter.
  198.    *
  199.    * @param maxVariance the maximum variance allowed, specified as a percentage
  200.    */
  201.   public void setMaximumVariancePercentageAllowed(double maxVariance) {
  202.     
  203.     m_maxVariancePercentage = maxVariance;
  204.   }
  205.   /**
  206.    * Gets the maximum variance attributes are allowed to have before they are
  207.    * deleted by the filter.
  208.    *
  209.    * @return the maximum variance allowed, specified as a percentage
  210.    */
  211.   public double getMaximumVariancePercentageAllowed() {
  212.     return m_maxVariancePercentage;
  213.   }
  214.   /**
  215.    * Main method for testing this class.
  216.    *
  217.    * @param argv should contain arguments to the filter: use -h for help
  218.    */
  219.   public static void main(String [] argv) {
  220.     try {
  221.       if (Utils.getFlag('b', argv)) {
  222.   Filter.batchFilterFile(new RemoveUseless(), argv); 
  223.       } else {
  224. Filter.filterFile(new RemoveUseless(), argv);
  225.       }
  226.     } catch (Exception ex) {
  227.       System.out.println(ex.getMessage());
  228.     }
  229.   }
  230. }