Resample.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.  *    Resample.java
  18.  *    Copyright (C) 1999 Intelligenesis Corp.
  19.  *
  20.  */
  21. package weka.filters.unsupervised.instance;
  22. import weka.filters.*;
  23. import weka.core.Instance;
  24. import weka.core.Instances;
  25. import weka.core.OptionHandler;
  26. import weka.core.Option;
  27. import weka.core.Utils;
  28. import java.util.Random;
  29. import java.util.Enumeration;
  30. import java.util.Vector;
  31. /** 
  32.  * Produces a random subsample of a dataset. The original dataset must
  33.  * fit entirely in memory. The number of instances in the generated
  34.  * dataset may be specified. When used in batch mode, subsequent batches
  35.  * are <b>not</b> resampled.
  36.  *
  37.  * Valid options are:<p>
  38.  *
  39.  * -S num <br>
  40.  * Specify the random number seed (default 1).<p>
  41.  *
  42.  * -Z percent <br>
  43.  * Specify the size of the output dataset, as a percentage of the input
  44.  * dataset (default 100). <p>
  45.  *
  46.  * @author Len Trigg (len@intelligenesis.net)
  47.  * @version $Revision: 1.1 $ 
  48.  **/
  49. public class Resample extends Filter implements UnsupervisedFilter,
  50. OptionHandler {
  51.   /** The subsample size, percent of original set, default 100% */
  52.   private double m_SampleSizePercent = 100;
  53.   
  54.   /** The random number generator seed */
  55.   private int m_RandomSeed = 1;
  56.   /** True if the first batch has been done */
  57.   private boolean m_FirstBatchDone = false;
  58.   /**
  59.    * Returns an enumeration describing the available options.
  60.    *
  61.    * @return an enumeration of all the available options.
  62.    */
  63.   public Enumeration listOptions() {
  64.     Vector newVector = new Vector(1);
  65.     newVector.addElement(new Option(
  66.               "tSpecify the random number seed (default 1)",
  67.               "S", 1, "-S <num>"));
  68.     newVector.addElement(new Option(
  69.               "tThe size of the output dataset, as a percentage ofn"
  70.               +"tthe input dataset (default 100)",
  71.               "Z", 1, "-Z <num>"));
  72.     return newVector.elements();
  73.   }
  74.   /**
  75.    * Parses a list of options for this object. Valid options are:<p>
  76.    *
  77.    * -S num <br>
  78.    * Specify the random number seed (default 1).<p>
  79.    *
  80.    * -Z percent <br>
  81.    * Specify the size of the output dataset, as a percentage of the input
  82.    * dataset (default 100). <p>
  83.    *
  84.    * @param options the list of options as an array of strings
  85.    * @exception Exception if an option is not supported
  86.    */
  87.   public void setOptions(String[] options) throws Exception {
  88.     
  89.     String seedString = Utils.getOption('S', options);
  90.     if (seedString.length() != 0) {
  91.       setRandomSeed(Integer.parseInt(seedString));
  92.     } else {
  93.       setRandomSeed(1);
  94.     }
  95.     String sizeString = Utils.getOption('Z', options);
  96.     if (sizeString.length() != 0) {
  97.       setSampleSizePercent(Double.valueOf(sizeString).doubleValue());
  98.     } else {
  99.       setSampleSizePercent(100);
  100.     }
  101.     if (getInputFormat() != null) {
  102.       setInputFormat(getInputFormat());
  103.     }
  104.   }
  105.   /**
  106.    * Gets the current settings of the filter.
  107.    *
  108.    * @return an array of strings suitable for passing to setOptions
  109.    */
  110.   public String [] getOptions() {
  111.     String [] options = new String [6];
  112.     int current = 0;
  113.     options[current++] = "-S"; options[current++] = "" + getRandomSeed();
  114.     options[current++] = "-Z"; options[current++] = "" + getSampleSizePercent();
  115.     while (current < options.length) {
  116.       options[current++] = "";
  117.     }
  118.     return options;
  119.   }
  120.   
  121.   /**
  122.    * Gets the random number seed.
  123.    *
  124.    * @return the random number seed.
  125.    */
  126.   public int getRandomSeed() {
  127.     return m_RandomSeed;
  128.   }
  129.   
  130.   /**
  131.    * Sets the random number seed.
  132.    *
  133.    * @param newSeed the new random number seed.
  134.    */
  135.   public void setRandomSeed(int newSeed) {
  136.     m_RandomSeed = newSeed;
  137.   }
  138.   
  139.   /**
  140.    * Gets the subsample size as a percentage of the original set.
  141.    *
  142.    * @return the subsample size
  143.    */
  144.   public double getSampleSizePercent() {
  145.     return m_SampleSizePercent;
  146.   }
  147.   
  148.   /**
  149.    * Sets the size of the subsample, as a percentage of the original set.
  150.    *
  151.    * @param newSampleSizePercent the subsample set size, between 0 and 100.
  152.    */
  153.   public void setSampleSizePercent(double newSampleSizePercent) {
  154.     m_SampleSizePercent = newSampleSizePercent;
  155.   }
  156.   
  157.   /**
  158.    * Sets the format of the input instances.
  159.    *
  160.    * @param instanceInfo an Instances object containing the input 
  161.    * instance structure (any instances contained in the object are 
  162.    * ignored - only the structure is required).
  163.    * @return true if the outputFormat may be collected immediately
  164.    * @exception Exception if the input format can't be set 
  165.    * successfully
  166.    */
  167.   public boolean setInputFormat(Instances instanceInfo) 
  168.        throws Exception {
  169.     super.setInputFormat(instanceInfo);
  170.     setOutputFormat(instanceInfo);
  171.     m_FirstBatchDone = false;
  172.     return true;
  173.   }
  174.   /**
  175.    * Input an instance for filtering. Filter requires all
  176.    * training instances be read before producing output.
  177.    *
  178.    * @param instance the input instance
  179.    * @return true if the filtered instance may now be
  180.    * collected with output().
  181.    * @exception IllegalStateException if no input structure has been defined
  182.    */
  183.   public boolean input(Instance instance) {
  184.     if (getInputFormat() == null) {
  185.       throw new IllegalStateException("No input instance format defined");
  186.     }
  187.     if (m_NewBatch) {
  188.       resetQueue();
  189.       m_NewBatch = false;
  190.     }
  191.     if (m_FirstBatchDone) {
  192.       push(instance);
  193.       return true;
  194.     } else {
  195.       bufferInput(instance);
  196.       return false;
  197.     }
  198.   }
  199.   /**
  200.    * Signify that this batch of input to the filter is finished. 
  201.    * If the filter requires all instances prior to filtering,
  202.    * output() may now be called to retrieve the filtered instances.
  203.    *
  204.    * @return true if there are instances pending output
  205.    * @exception IllegalStateException if no input structure has been defined
  206.    */
  207.   public boolean batchFinished() {
  208.     if (getInputFormat() == null) {
  209.       throw new IllegalStateException("No input instance format defined");
  210.     }
  211.     if (!m_FirstBatchDone) {
  212.       // Do the subsample, and clear the input instances.
  213.       createSubsample();
  214.     }
  215.     flushInput();
  216.     m_NewBatch = true;
  217.     m_FirstBatchDone = true;
  218.     return (numPendingOutput() != 0);
  219.   }
  220.   /**
  221.    * Creates a subsample of the current set of input instances. The output
  222.    * instances are pushed onto the output queue for collection.
  223.    */
  224.   private void createSubsample() {
  225.     int origSize = getInputFormat().numInstances();
  226.     int sampleSize = (int) (origSize * m_SampleSizePercent / 100);
  227.     
  228.     // Simple subsample
  229.     
  230.     Random random = new Random(m_RandomSeed);
  231.     // Convert pending input instances
  232.     for(int i = 0; i < sampleSize; i++) {
  233.       int index = (int) (random.nextDouble() * origSize);
  234.       push((Instance)getInputFormat().instance(index).copy());
  235.     }
  236.   }
  237.   
  238.   /**
  239.    * Main method for testing this class.
  240.    *
  241.    * @param argv should contain arguments to the filter: 
  242.    * use -h for help
  243.    */
  244.   public static void main(String [] argv) {
  245.     try {
  246.       if (Utils.getFlag('b', argv)) {
  247.   Filter.batchFilterFile(new Resample(), argv);
  248.       } else {
  249. Filter.filterFile(new Resample(), argv);
  250.       }
  251.     } catch (Exception ex) {
  252.       System.out.println(ex.getMessage());
  253.     }
  254.   }
  255. }