📄 discretize.java
字号:
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *//* * Discretize.java * Copyright (C) 1999 Eibe Frank,Len Trigg * */package weka.filters.unsupervised.attribute;import weka.core.Attribute;import weka.core.Capabilities;import weka.core.FastVector;import weka.core.Instance;import weka.core.Instances;import weka.core.Option;import weka.core.Range;import weka.core.SparseInstance;import weka.core.Utils;import weka.core.WeightedInstancesHandler;import weka.core.Capabilities.Capability;import weka.filters.UnsupervisedFilter;import java.util.Enumeration;import java.util.Vector;/** <!-- globalinfo-start --> * An instance filter that discretizes a range of numeric attributes in the dataset into nominal attributes. Discretization is by simple binning. Skips the class attribute if set. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -unset-class-temporarily * Unsets the class index temporarily before the filter is * applied to the data. * (default: no)</pre> * * <pre> -B <num> * Specifies the (maximum) number of bins to divide numeric attributes into. * (default = 10)</pre> * * <pre> -M <num> * Specifies the desired weight of instances per bin for * equal-frequency binning. If this is set to a positive * number then the -B option will be ignored. * (default = -1)</pre> * * <pre> -F * Use equal-frequency instead of equal-width discretization.</pre> * * <pre> -O * Optimize number of bins using leave-one-out estimate * of estimated entropy (for equal-width discretization). * If this is set then the -B option will be ignored.</pre> * * <pre> -R <col1,col2-col4,...> * Specifies list of columns to Discretize. First and last are valid indexes. * (default: first-last)</pre> * * <pre> -V * Invert matching sense of column indexes.</pre> * * <pre> -D * Output binary attributes for discretized attributes.</pre> * <!-- options-end --> * * @author Len Trigg (trigg@cs.waikato.ac.nz) * @author Eibe Frank (eibe@cs.waikato.ac.nz) * @version $Revision: 1.11 $ */public class Discretize extends PotentialClassIgnorer implements UnsupervisedFilter, WeightedInstancesHandler { /** for serialization */ static final long serialVersionUID = -1358531742174527279L; /** 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; /** The desired weight of instances per bin */ protected double m_DesiredWeightOfInstancesPerInterval = -1; /** Store the current cutpoints */ protected double [][] m_CutPoints = null; /** Output binary attributes for discretized attributes. */ protected boolean m_MakeBinary = 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; /** The default columns to discretize */ protected String m_DefaultCols; /** Constructor - initialises the filter */ public Discretize() { m_DefaultCols = "first-last"; setAttributeIndices("first-last"); } /** * Another constructor, sets the attribute indices immediately * * @param cols the attribute indices */ public Discretize(String cols) { m_DefaultCols = cols; setAttributeIndices(cols); } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector result = new Vector(); Enumeration enm = super.listOptions(); while (enm.hasMoreElements()) result.add(enm.nextElement()); result.addElement(new Option( "\tSpecifies the (maximum) number of bins to divide numeric" + " attributes into.\n" + "\t(default = 10)", "B", 1, "-B <num>")); result.addElement(new Option( "\tSpecifies the desired weight of instances per bin for\n" + "\tequal-frequency binning. If this is set to a positive\n" + "\tnumber then the -B option will be ignored.\n" + "\t(default = -1)", "M", 1, "-M <num>")); result.addElement(new Option( "\tUse equal-frequency instead of equal-width discretization.", "F", 0, "-F")); result.addElement(new Option( "\tOptimize number of bins using leave-one-out estimate\n"+ "\tof estimated entropy (for equal-width discretization).\n"+ "\tIf this is set then the -B option will be ignored.", "O", 0, "-O")); result.addElement(new Option( "\tSpecifies list of columns to Discretize. First" + " and last are valid indexes.\n" + "\t(default: first-last)", "R", 1, "-R <col1,col2-col4,...>")); result.addElement(new Option( "\tInvert matching sense of column indexes.", "V", 0, "-V")); result.addElement(new Option( "\tOutput binary attributes for discretized attributes.", "D", 0, "-D")); return result.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -unset-class-temporarily * Unsets the class index temporarily before the filter is * applied to the data. * (default: no)</pre> * * <pre> -B <num> * Specifies the (maximum) number of bins to divide numeric attributes into. * (default = 10)</pre> * * <pre> -M <num> * Specifies the desired weight of instances per bin for * equal-frequency binning. If this is set to a positive * number then the -B option will be ignored. * (default = -1)</pre> * * <pre> -F * Use equal-frequency instead of equal-width discretization.</pre> * * <pre> -O * Optimize number of bins using leave-one-out estimate * of estimated entropy (for equal-width discretization). * If this is set then the -B option will be ignored.</pre> * * <pre> -R <col1,col2-col4,...> * Specifies list of columns to Discretize. First and last are valid indexes. * (default: first-last)</pre> * * <pre> -V * Invert matching sense of column indexes.</pre> * * <pre> -D * Output binary attributes for discretized attributes.</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { super.setOptions(options); setMakeBinary(Utils.getFlag('D', options)); setUseEqualFrequency(Utils.getFlag('F', options)); setFindNumBins(Utils.getFlag('O', options)); setInvertSelection(Utils.getFlag('V', options)); String weight = Utils.getOption('M', options); if (weight.length() != 0) { setDesiredWeightOfInstancesPerInterval((new Double(weight)).doubleValue()); } else { setDesiredWeightOfInstancesPerInterval(-1); } String numBins = Utils.getOption('B', options); if (numBins.length() != 0) { setBins(Integer.parseInt(numBins)); } else { setBins(10); } String convertList = Utils.getOption('R', options); if (convertList.length() != 0) { setAttributeIndices(convertList); } else { setAttributeIndices(m_DefaultCols); } 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() { Vector result; String[] options; int i; result = new Vector(); options = super.getOptions(); for (i = 0; i < options.length; i++) result.add(options[i]); if (getMakeBinary()) result.add("-D"); if (getUseEqualFrequency()) result.add("-F"); if (getFindNumBins()) result.add("-O"); if (getInvertSelection()) result.add("-V"); result.add("-B"); result.add("" + getBins()); result.add("-M"); result.add("" + getDesiredWeightOfInstancesPerInterval()); if (!getAttributeIndices().equals("")) { result.add("-R"); result.add(getAttributeIndices()); } return (String[]) result.toArray(new String[result.size()]); } /** * Returns the Capabilities of this filter. * * @return the capabilities of this object * @see Capabilities */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); // attributes result.enableAllAttributes(); result.enable(Capability.MISSING_VALUES); // class result.enableAllClasses(); result.enable(Capability.MISSING_CLASS_VALUES); if (!getMakeBinary()) result.enable(Capability.NO_CLASS); return result; } /** * 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 * @throws Exception if the input format can't be set successfully */ public boolean setInputFormat(Instances instanceInfo) throws Exception { if (m_MakeBinary && m_IgnoreClass) { throw new IllegalArgumentException("Can't ignore class when " + "changing the number of attributes!"); } super.setInputFormat(instanceInfo); m_DiscretizeCols.setUpper(instanceInfo.numAttributes() - 1); m_CutPoints = null; 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(). * @throws 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 * @throws IllegalStateException if no input structure has been defined */ public boolean batchFinished() { 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 is by simple binning. Skips the class" + " attribute if set."; } /** * 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. Doesn't " + "work for equal-frequency binning"; } /** * 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 * displaying in the explorer/experimenter gui */ public String makeBinaryTipText() { return "Make resulting attributes binary."; } /** * Gets whether binary attributes should be made for discretized ones. * * @return true if attributes will be binarized */ public boolean getMakeBinary() { return m_MakeBinary; } /** * Sets whether binary attributes should be made for discretized ones. * * @param makeBinary if binary attributes are to be made */ public void setMakeBinary(boolean makeBinary) { m_MakeBinary = makeBinary; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String desiredWeightOfInstancesPerIntervalTipText() { return "Sets the desired weight of instances per interval for " + "equal-frequency binning."; } /** * Get the DesiredWeightOfInstancesPerInterval value. * @return the DesiredWeightOfInstancesPerInterval value. */ public double getDesiredWeightOfInstancesPerInterval() { return m_DesiredWeightOfInstancesPerInterval; } /** * Set the DesiredWeightOfInstancesPerInterval value. * @param newDesiredNumber The new DesiredNumber value. */ public void setDesiredWeightOfInstancesPerInterval(double newDesiredNumber) { m_DesiredWeightOfInstancesPerInterval = newDesiredNumber; } /** * 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 + -