MetaCost.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 16k
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.  *    MetaCost.java
  18.  *    Copyright (C) 1999 Intelligenesis Corp.
  19.  *
  20.  */
  21. package weka.classifiers;
  22. import java.io.*;
  23. import java.util.*;
  24. import weka.core.*;
  25. import weka.filters.Filter;
  26. /**
  27.  * This metaclassifier makes its base classifier cost-sensitive using the
  28.  * method specified in <p>
  29.  *
  30.  * Pedro Domingos (1999). <i>MetaCost: A general method for making classifiers
  31.  * cost-sensitive</i>, Proceedings of the Fifth International Conference on 
  32.  * Knowledge Discovery and Data Mining, pp. 155-164. Also available online at
  33.  * <a href="http://www.cs.washington.edu/homes/pedrod/kdd99.ps.gz">
  34.  * http://www.cs.washington.edu/homes/pedrod/kdd99.ps.gz</a>. <p>
  35.  *
  36.  * This classifier should produce similar results to one created by
  37.  * passing the base learner to Bagging, which is in turn passed to a
  38.  * CostSensitiveClassifier operating on minimum expected cost. The difference
  39.  * is that MetaCost produces a single cost-sensitive classifier of the
  40.  * base learner, giving the benefits of fast classification and interpretable
  41.  * output (if the base learner itself is interpretable). This implementation 
  42.  * uses all bagging iterations when reclassifying training data (the MetaCost
  43.  * paper reports a marginal improvement when only those iterations containing
  44.  * each training instance are used in reclassifying that instance). <p>
  45.  *
  46.  * Valid options are:<p>
  47.  *
  48.  * -W classname <br>
  49.  * Specify the full class name of a classifier (required).<p>
  50.  *
  51.  * -C cost file <br>
  52.  * File name of a cost matrix to use. If this is not supplied, a cost
  53.  * matrix will be loaded on demand. The name of the on-demand file
  54.  * is the relation name of the training data plus ".cost", and the
  55.  * path to the on-demand file is specified with the -D option.<p>
  56.  *
  57.  * -D directory <br>
  58.  * Name of a directory to search for cost files when loading costs on demand
  59.  * (default current directory). <p>
  60.  *
  61.  * -I num <br>
  62.  * Set the number of bagging iterations (default 10). <p>
  63.  *
  64.  * -S seed <br>
  65.  * Random number seed used when reweighting by resampling (default 1).<p>
  66.  *
  67.  * -P num <br>
  68.  * Size of each bag, as a percentage of the training size (default 100). <p>
  69.  *
  70.  * Options after -- are passed to the designated classifier.<p>
  71.  *
  72.  * @author Len Trigg (len@intelligenesis.net)
  73.  * @version $Revision: 1.7 $ 
  74.  */
  75. public class MetaCost extends Classifier
  76.   implements OptionHandler {
  77.   /* Specify possible sources of the cost matrix */
  78.   public static final int MATRIX_ON_DEMAND = 1;
  79.   public static final int MATRIX_SUPPLIED = 2;
  80.   public static final Tag [] TAGS_MATRIX_SOURCE = {
  81.     new Tag(MATRIX_ON_DEMAND, "Load cost matrix on demand"),
  82.     new Tag(MATRIX_SUPPLIED, "Use explicit cost matrix")
  83.   };
  84.   /** Indicates the current cost matrix source */
  85.   protected int m_MatrixSource = MATRIX_ON_DEMAND;
  86.   /** 
  87.    * The directory used when loading cost files on demand, null indicates
  88.    * current directory 
  89.    */
  90.   protected File m_OnDemandDirectory = new File(System.getProperty("user.dir"));
  91.   /** The name of the cost file, for command line options */
  92.   protected String m_CostFile;
  93.   /** The classifier */
  94.   protected Classifier m_Classifier = new weka.classifiers.ZeroR();
  95.   /** The cost matrix */
  96.   protected CostMatrix m_CostMatrix = new CostMatrix(1);
  97.   /** The number of iterations. */
  98.   protected int m_NumIterations = 10;
  99.   /** Seed for reweighting using resampling. */
  100.   protected int m_Seed = 1;
  101.   /** The size of each bag sample, as a percentage of the training size */
  102.   protected int m_BagSizePercent = 100;
  103.   /**
  104.    * Returns an enumeration describing the available options
  105.    *
  106.    * @return an enumeration of all the available options
  107.    */
  108.   public Enumeration listOptions() {
  109.     Vector newVector = new Vector(6);
  110.     newVector.addElement(new Option(
  111.       "tNumber of bagging iterations.n"
  112.       + "t(default 10)",
  113.       "I", 1, "-I <num>"));
  114.     newVector.addElement(new Option(
  115.       "tFull class name of classifier to use. (required)n"
  116.       + "teg: weka.classifiers.NaiveBayes",
  117.       "W", 1, "-W <class name>"));
  118.     newVector.addElement(new Option(
  119.       "tFile name of a cost matrix to use. If this is not supplied,n"
  120.               +"ta cost matrix will be loaded on demand. The name of then"
  121.               +"ton-demand file is the relation name of the training datan"
  122.               +"tplus ".cost", and the path to the on-demand file isn"
  123.               +"tspecified with the -D option.",
  124.       "C", 1, "-C <cost file name>"));
  125.     newVector.addElement(new Option(
  126.               "tName of a directory to search for cost files when loadingn"
  127.               +"tcosts on demand (default current directory).",
  128.               "D", 1, "-D <directory>"));
  129.     newVector.addElement(new Option(
  130.       "tSeed used when reweighting via resampling. (Default 1)",
  131.       "S", 1, "-S <num>"));
  132.     newVector.addElement(new Option(
  133.               "tSize of each bag, as a percentage of then" 
  134.               + "ttraining set size. (default 100)",
  135.               "P", 1, "-P"));
  136.     return newVector.elements();
  137.   }
  138.   /**
  139.    * Parses a given list of options. Valid options are:<p>
  140.    *
  141.    * -W classname <br>
  142.    * Specify the full class name of a classifier (required).<p>
  143.    *
  144.    * -C cost file <br>
  145.    * File name of a cost matrix to use. If this is not supplied, a cost
  146.    * matrix will be loaded on demand. The name of the on-demand file
  147.    * is the relation name of the training data plus ".cost", and the
  148.    * path to the on-demand file is specified with the -D option.<p>
  149.    *
  150.    * -D directory <br>
  151.    * Name of a directory to search for cost files when loading costs on demand
  152.    * (default current directory). <p>
  153.    *
  154.    * -I num <br>
  155.    * Set the number of bagging iterations (default 10). <p>
  156.    *
  157.    * -S seed <br>
  158.    * Random number seed used when reweighting by resampling (default 1).<p>
  159.    *
  160.    * -P num <br>
  161.    * Size of each bag, as a percentage of the training size (default 100). <p>
  162.    *
  163.    * Options after -- are passed to the designated classifier.<p>
  164.    *
  165.    * @param options the list of options as an array of strings
  166.    * @exception Exception if an option is not supported
  167.    */
  168.   public void setOptions(String[] options) throws Exception {
  169.     String bagIterations = Utils.getOption('I', options);
  170.     if (bagIterations.length() != 0) {
  171.       setNumIterations(Integer.parseInt(bagIterations));
  172.     } else {
  173.       setNumIterations(10);
  174.     }
  175.     String seedString = Utils.getOption('S', options);
  176.     if (seedString.length() != 0) {
  177.       setSeed(Integer.parseInt(seedString));
  178.     } else {
  179.       setSeed(1);
  180.     }
  181.     String bagSize = Utils.getOption('P', options);
  182.     if (bagSize.length() != 0) {
  183.       setBagSizePercent(Integer.parseInt(bagSize));
  184.     } else {
  185.       setBagSizePercent(100);
  186.     }
  187.     String classifierName = Utils.getOption('W', options);
  188.     if (classifierName.length() == 0) {
  189.       throw new Exception("A classifier must be specified with"
  190.   + " the -W option.");
  191.     }
  192.     setClassifier(Classifier.forName(classifierName,
  193.      Utils.partitionOptions(options)));
  194.     String costFile = Utils.getOption('C', options);
  195.     if (costFile.length() != 0) {
  196.       setCostMatrix(new CostMatrix(new BufferedReader(
  197.                                    new FileReader(costFile))));
  198.       setCostMatrixSource(new SelectedTag(MATRIX_SUPPLIED,
  199.                                           TAGS_MATRIX_SOURCE));
  200.       m_CostFile = costFile;
  201.     } else {
  202.       setCostMatrixSource(new SelectedTag(MATRIX_ON_DEMAND, 
  203.                                           TAGS_MATRIX_SOURCE));
  204.     }
  205.     
  206.     String demandDir = Utils.getOption('D', options);
  207.     if (demandDir.length() != 0) {
  208.       setOnDemandDirectory(new File(demandDir));
  209.     }
  210.   }
  211.   /**
  212.    * Gets the current settings of the Classifier.
  213.    *
  214.    * @return an array of strings suitable for passing to setOptions
  215.    */
  216.   public String [] getOptions() {
  217.     String [] classifierOptions = new String [0];
  218.     if ((m_Classifier != null) && 
  219. (m_Classifier instanceof OptionHandler)) {
  220.       classifierOptions = ((OptionHandler)m_Classifier).getOptions();
  221.     }
  222.     String [] options = new String [classifierOptions.length + 12];
  223.     int current = 0;
  224.     if (m_MatrixSource == MATRIX_SUPPLIED) {
  225.       if (m_CostFile != null) {
  226.         options[current++] = "-C";
  227.         options[current++] = "" + m_CostFile;
  228.       }
  229.     } else {
  230.       options[current++] = "-D";
  231.       options[current++] = "" + getOnDemandDirectory();
  232.     }
  233.     options[current++] = "-I"; options[current++] = "" + getNumIterations();
  234.     options[current++] = "-S"; options[current++] = "" + getSeed();
  235.     options[current++] = "-P"; options[current++] = "" + getBagSizePercent();
  236.     if (getClassifier() != null) {
  237.       options[current++] = "-W";
  238.       options[current++] = getClassifier().getClass().getName();
  239.     }
  240.     options[current++] = "--";
  241.     System.arraycopy(classifierOptions, 0, options, current, 
  242.      classifierOptions.length);
  243.     current += classifierOptions.length;
  244.     while (current < options.length) {
  245.       options[current++] = "";
  246.     }
  247.     return options;
  248.   }
  249.   /**
  250.    * Gets the source location method of the cost matrix. Will be one of
  251.    * MATRIX_ON_DEMAND or MATRIX_SUPPLIED.
  252.    *
  253.    * @return the cost matrix source.
  254.    */
  255.   public SelectedTag getCostMatrixSource() {
  256.     return new SelectedTag(m_MatrixSource, TAGS_MATRIX_SOURCE);
  257.   }
  258.   
  259.   /**
  260.    * Sets the source location of the cost matrix. Values other than
  261.    * MATRIX_ON_DEMAND or MATRIX_SUPPLIED will be ignored.
  262.    *
  263.    * @param newMethod the cost matrix location method.
  264.    */
  265.   public void setCostMatrixSource(SelectedTag newMethod) {
  266.     
  267.     if (newMethod.getTags() == TAGS_MATRIX_SOURCE) {
  268.       m_MatrixSource = newMethod.getSelectedTag().getID();
  269.     }
  270.   }
  271.   /**
  272.    * Returns the directory that will be searched for cost files when
  273.    * loading on demand.
  274.    *
  275.    * @return The cost file search directory.
  276.    */
  277.   public File getOnDemandDirectory() {
  278.     return m_OnDemandDirectory;
  279.   }
  280.   /**
  281.    * Sets the directory that will be searched for cost files when
  282.    * loading on demand.
  283.    *
  284.    * @param newDir The cost file search directory.
  285.    */
  286.   public void setOnDemandDirectory(File newDir) {
  287.     if (newDir.isDirectory()) {
  288.       m_OnDemandDirectory = newDir;
  289.     } else {
  290.       m_OnDemandDirectory = new File(newDir.getParent());
  291.     }
  292.     m_MatrixSource = MATRIX_ON_DEMAND;
  293.   }
  294.   
  295.   /**
  296.    * Sets the distribution classifier
  297.    *
  298.    * @param classifier the distribution classifier with all options set.
  299.    */
  300.   public void setClassifier(Classifier classifier) {
  301.     m_Classifier = classifier;
  302.   }
  303.   /**
  304.    * Gets the distribution classifier used.
  305.    *
  306.    * @return the classifier
  307.    */
  308.   public Classifier getClassifier() {
  309.     return m_Classifier;
  310.   }
  311.   
  312.   /**
  313.    * Gets the classifier specification string, which contains the class name of
  314.    * the classifier and any options to the classifier
  315.    *
  316.    * @return the classifier string.
  317.    */
  318.   protected String getClassifierSpec() {
  319.     
  320.     Classifier c = getClassifier();
  321.     if (c instanceof OptionHandler) {
  322.       return c.getClass().getName() + " "
  323. + Utils.joinOptions(((OptionHandler)c).getOptions());
  324.     }
  325.     return c.getClass().getName();
  326.   }
  327.   /**
  328.    * Gets the size of each bag, as a percentage of the training set size.
  329.    *
  330.    * @return the bag size, as a percentage.
  331.    */
  332.   public int getBagSizePercent() {
  333.     return m_BagSizePercent;
  334.   }
  335.   
  336.   /**
  337.    * Sets the size of each bag, as a percentage of the training set size.
  338.    *
  339.    * @param newBagSizePercent the bag size, as a percentage.
  340.    */
  341.   public void setBagSizePercent(int newBagSizePercent) {
  342.     m_BagSizePercent = newBagSizePercent;
  343.   }
  344.   
  345.   /**
  346.    * Sets the number of bagging iterations
  347.    */
  348.   public void setNumIterations(int numIterations) {
  349.     m_NumIterations = numIterations;
  350.   }
  351.   /**
  352.    * Gets the number of bagging iterations
  353.    *
  354.    * @return the maximum number of bagging iterations
  355.    */
  356.   public int getNumIterations() {
  357.     
  358.     return m_NumIterations;
  359.   }
  360.   /**
  361.    * Gets the misclassification cost matrix.
  362.    *
  363.    * @return the cost matrix
  364.    */
  365.   public CostMatrix getCostMatrix() {
  366.     
  367.     return m_CostMatrix;
  368.   }
  369.   
  370.   /**
  371.    * Sets the misclassification cost matrix.
  372.    *
  373.    * @param the cost matrix
  374.    */
  375.   public void setCostMatrix(CostMatrix newCostMatrix) {
  376.     
  377.     m_CostMatrix = newCostMatrix;
  378.     m_MatrixSource = MATRIX_SUPPLIED;
  379.   }
  380.   
  381.   /**
  382.    * Set seed for resampling.
  383.    *
  384.    * @param seed the seed for resampling
  385.    */
  386.   public void setSeed(int seed) {
  387.     m_Seed = seed;
  388.   }
  389.   /**
  390.    * Get seed for resampling.
  391.    *
  392.    * @return the seed for resampling
  393.    */
  394.   public int getSeed() {
  395.     return m_Seed;
  396.   }
  397.   /**
  398.    * Builds the model of the base learner.
  399.    *
  400.    * @param data the training data
  401.    * @exception Exception if the classifier could not be built successfully
  402.    */
  403.   public void buildClassifier(Instances data) throws Exception {
  404.     if (m_Classifier == null) {
  405.       throw new Exception("No base classifier has been set!");
  406.     }
  407.     if (!data.classAttribute().isNominal()) {
  408.       throw new Exception("Class attribute must be nominal!");
  409.     }
  410.     if (m_MatrixSource == MATRIX_ON_DEMAND) {
  411.       String costName = data.relationName() + CostMatrix.FILE_EXTENSION;
  412.       File costFile = new File(getOnDemandDirectory(), costName);
  413.       if (!costFile.exists()) {
  414.         throw new Exception("On-demand cost file doesn't exist: " + costFile);
  415.       }
  416.       setCostMatrix(new CostMatrix(new BufferedReader(
  417.                                    new FileReader(costFile))));
  418.     }
  419.     // Set up the bagger
  420.     Bagging bagger = new Bagging();
  421.     bagger.setClassifier(getClassifier());
  422.     bagger.setSeed(getSeed());
  423.     bagger.setNumIterations(getNumIterations());
  424.     bagger.setBagSizePercent(getBagSizePercent());
  425.     bagger.buildClassifier(data);
  426.     
  427.     // Use the bagger to reassign class values according to minimum expected
  428.     // cost
  429.     Instances newData = new Instances(data);
  430.     for (int i = 0; i < newData.numInstances(); i++) {
  431.       Instance current = newData.instance(i);
  432.       double [] pred = bagger.distributionForInstance(current);
  433.       int minCostPred = Utils.minIndex(m_CostMatrix.expectedCosts(pred));
  434.       current.setClassValue(minCostPred);
  435.     }
  436.     // Build a classifier using the reassigned data
  437.     m_Classifier.buildClassifier(newData);
  438.   }
  439.   /**
  440.    * Classifies a given test instance.
  441.    *
  442.    * @param instance the instance to be classified
  443.    * @exception Exception if instance could not be classified
  444.    * successfully
  445.    */
  446.   public double classifyInstance(Instance instance) throws Exception {
  447.     return m_Classifier.classifyInstance(instance);
  448.   }
  449.   /**
  450.    * Output a representation of this classifier
  451.    */
  452.   public String toString() {
  453.     if (m_Classifier == null) {
  454.       return "MetaCost: No model built yet.";
  455.     }
  456.     String result = "MetaCost cost sensitive classifier induction";
  457.     result += "nOptions: " + Utils.joinOptions(getOptions());
  458.     result += "nBase learner: " + getClassifierSpec()
  459.       + "nnClassifier Modeln"
  460.       + m_Classifier.toString()
  461.       + "nnCost Matrixn"
  462.       + m_CostMatrix.toString();
  463.     
  464.     return result;
  465.   }
  466.   /**
  467.    * Main method for testing this class.
  468.    *
  469.    * @param argv should contain the following arguments:
  470.    * -t training file [-T test file] [-c class index]
  471.    */
  472.   public static void main(String [] argv) {
  473.     try {
  474.       System.out.println(Evaluation
  475.  .evaluateModel(new MetaCost(),
  476. argv));
  477.     } catch (Exception e) {
  478.       System.err.println(e.getMessage());
  479.     }
  480.   }
  481. }