📄 discretizefilter.java
字号:
/**
*
* AgentAcademy - an open source Data Mining framework for
* training intelligent agents
*
* Copyright (C) 2001-2003 AA Consortium.
*
* This library is open source software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation;
* either version 2.0 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*/
package org.agentacademy.modules.dataminer.filters;
import java.util.Enumeration;
import java.util.Vector;
import org.agentacademy.modules.dataminer.core.Attribute;
import org.agentacademy.modules.dataminer.core.ContingencyTables;
import org.agentacademy.modules.dataminer.core.FastVector;
import org.agentacademy.modules.dataminer.core.Instance;
import org.agentacademy.modules.dataminer.core.Instances;
import org.agentacademy.modules.dataminer.core.Option;
import org.agentacademy.modules.dataminer.core.OptionHandler;
import org.agentacademy.modules.dataminer.core.Range;
import org.agentacademy.modules.dataminer.core.SparseInstance;
import org.agentacademy.modules.dataminer.core.SpecialFunctions;
import org.agentacademy.modules.dataminer.core.UnassignedClassException;
import org.agentacademy.modules.dataminer.core.UnsupportedClassTypeException;
import org.agentacademy.modules.dataminer.core.Utils;
import org.agentacademy.modules.dataminer.core.WeightedInstancesHandler;
import org.apache.log4j.Logger;
/**
* An instance filter that discretizes a range of numeric attributes in
* the dataset into nominal attributes. Discretization can be either by
* simple binning, or by Fayyad & Irani's MDL method (the default).<p>
*
* Valid filter-specific options are: <p>
*
* -B num <br>
* Specifies the (maximum) number of bins to divide numeric attributes into.
* (default: class-based discretisation).<p>
*
* -F <br>
* Use equal-frequency instead of equal-width discretization if
* class-based discretisation is turned off.<p>
*
* -O <br>
* Optimize the number of bins using a leave-one-out estimate of the
* entropy (for equal-width binning).<p>
*
* -R col1,col2-col4,... <br>
* Specifies list of columns to Discretize. First
* and last are valid indexes. (default: none) <p>
*
* -V <br>
* Invert matching sense.<p>
*
* -D <br>
* Make binary nominal attributes. <p>
*
* -E <br>
* Use better encoding of split point for MDL. <p>
*
* -K <br>
* Use Kononeko's MDL criterion. <p>
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 1.3 $
*/
public class DiscretizeFilter extends Filter
implements OptionHandler, WeightedInstancesHandler {
public static Logger log = Logger.getLogger(DiscretizeFilter.class);
/** Stores which columns to Discretize */
protected Range m_DiscretizeCols = new Range();
/** The number of bins to divide the attribute into */
protected int m_NumBins = 10;
/** Store the current cutpoints */
protected double [][] m_CutPoints = null;
/** True if discretisation will be done by MDL rather than binning */
protected boolean m_UseMDL = true;
/** Output binary attributes for discretized attributes. */
protected boolean m_MakeBinary = false;
/** Use better encoding of split point for MDL. */
protected boolean m_UseBetterEncoding = false;
/** Use Kononenko's MDL criterion instead of Fayyad et al.'s */
protected boolean m_UseKononenko = false;
/** Find the number of bins using cross-validated entropy. */
protected boolean m_FindNumBins = false;
/** Use equal-frequency binning if unsupervised discretization turned on */
protected boolean m_UseEqualFrequency = false;
/** Constructor - initialises the filter */
public DiscretizeFilter() {
setAttributeIndices("first-last");
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(7);
newVector.addElement(new Option(
"\tSpecifies the (maximum) number of bins to divide numeric"
+ " attributes into.\n"
+ "\t(default class-based discretization)",
"B", 1, "-B <num>"));
newVector.addElement(new Option(
"\tUse equal-frequency instead of equal-width with\n"+
"\tunsupervised discretization.",
"F", 0, "-F"));
newVector.addElement(new Option(
"\tOptimize number of bins using leave-one-out estimate\n"+
"\tof estimated entropy (for equal-width discretization).",
"O", 0, "-O"));
/* If we decide to implement loading and saving cutfiles like
* the C Discretizer (which is probably not necessary)
newVector.addElement(new Option(
"\tSpecify that the cutpoints should be loaded from a file.",
"L", 1, "-L <file>"));
newVector.addElement(new Option(
"\tSpecify that the chosen cutpoints should be saved to a file.",
"S", 1, "-S <file>"));
*/
newVector.addElement(new Option(
"\tSpecifies list of columns to Discretize. First"
+ " and last are valid indexes.\n"
+ "\t(default none)",
"R", 1, "-R <col1,col2-col4,...>"));
newVector.addElement(new Option(
"\tInvert matching sense of column indexes.",
"V", 0, "-V"));
newVector.addElement(new Option(
"\tOutput binary attributes for discretized attributes.",
"D", 0, "-D"));
newVector.addElement(new Option(
"\tUse better encoding of split point for MDL.",
"E", 0, "-E"));
newVector.addElement(new Option(
"\tUse Kononenko's MDL criterion.",
"K", 0, "-K"));
return newVector.elements();
}
/**
* Parses the options for this object. Valid options are: <p>
*
* -B num <br>
* Specifies the (maximum) number of bins to divide numeric attributes into.
* (default class-based discretisation).<p>
*
* -F <br>
* Use equal-frequency instead of equal-width discretization if
* class-based discretisation is turned off.<p>
*
* -O <br>
* Optimize the number of bins using a leave-one-out estimate of the
* entropy (for equal-width binning).<p>
*
* -R col1,col2-col4,... <br>
* Specifies list of columns to Discretize. First
* and last are valid indexes. (default none) <p>
*
* -V <br>
* Invert matching sense.<p>
*
* -D <br>
* Make binary nominal attributes. <p>
*
* -E <br>
* Use better encoding of split point for MDL. <p>
*
* -K <br>
* Use Kononeko's MDL criterion. <p>
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
setMakeBinary(Utils.getFlag('D', options));
setUseEqualFrequency(Utils.getFlag('F', options));
setUseBetterEncoding(Utils.getFlag('E', options));
setUseKononenko(Utils.getFlag('K', options));
setFindNumBins(Utils.getFlag('O', options));
setInvertSelection(Utils.getFlag('V', options));
setUseMDL(true);
String numBins = Utils.getOption('B', options);
if (numBins.length() != 0) {
setBins(Integer.parseInt(numBins));
setUseMDL(false);
} else {
setBins(10);
}
String convertList = Utils.getOption('R', options);
if (convertList.length() != 0) {
setAttributeIndices(convertList);
} else {
setAttributeIndices("first-last");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] options = new String [12];
int current = 0;
if (getMakeBinary()) {
options[current++] = "-D";
}
if (getUseEqualFrequency()) {
options[current++] = "-F";
}
if (getUseBetterEncoding()) {
options[current++] = "-E";
}
if (getUseKononenko()) {
options[current++] = "-K";
}
if (getFindNumBins()) {
options[current++] = "-O";
}
if (getInvertSelection()) {
options[current++] = "-V";
}
if (!getUseMDL()) {
options[current++] = "-B"; options[current++] = "" + getBins();
}
if (!getAttributeIndices().equals("")) {
options[current++] = "-R"; options[current++] = getAttributeIndices();
}
while (current < options.length) {
options[current++] = "";
}
return options;
}
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input instance
* structure (any instances contained in the object are ignored - only the
* structure is required).
* @return true if the outputFormat may be collected immediately
* @exception Exception if the input format can't be set successfully
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_DiscretizeCols.setUpper(instanceInfo.numAttributes() - 1);
m_CutPoints = null;
if (m_UseMDL) {
if (instanceInfo.classIndex() < 0) {
throw new UnassignedClassException("Cannot use class-based discretization: "
+ "no class assigned to the dataset");
}
if (!instanceInfo.classAttribute().isNominal()) {
throw new UnsupportedClassTypeException("Supervised discretization not possible:"
+ " class is not nominal!");
}
} else {
if (getFindNumBins() && getUseEqualFrequency()) {
throw new IllegalArgumentException("Bin number optimization in conjunction "+
"with equal-frequency binning not implemented.");
}
}
// If we implement loading cutfiles, then load
//them here and set the output format
return false;
}
/**
* Input an instance for filtering. Ordinarily the instance is processed
* and made available for output immediately. Some filters require all
* instances be read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @exception IllegalStateException if no input format has been defined.
*/
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (m_CutPoints != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Signifies that this batch of input to the filter is finished. If the
* filter requires all instances prior to filtering, output() may now
* be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @exception IllegalStateException if no input structure has been defined
*/
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_CutPoints == null) {
calculateCutPoints();
setOutputFormat();
// If we implement saving cutfiles, save the cuts here
// Convert pending input instances
for(int i = 0; i < getInputFormat().numInstances(); i++) {
convertInstance(getInputFormat().instance(i));
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "An instance filter that discretizes a range of numeric"
+ " attributes in the dataset into nominal attributes."
+ " Discretization can be either by simple binning, or by"
+ " Fayyad & Irani's MDL method (the default).";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String findNumBinsTipText() {
return "Optimize number of equal-width bins using leave-one-out.";
}
/**
* Get the value of FindNumBins.
*
* @return Value of FindNumBins.
*/
public boolean getFindNumBins() {
return m_FindNumBins;
}
/**
* Set the value of FindNumBins.
*
* @param newFindNumBins Value to assign to FindNumBins.
*/
public void setFindNumBins(boolean newFindNumBins) {
m_FindNumBins = newFindNumBins;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -