index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/experiment/Task.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Task.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.experiment;
import java.io.Serializable;
/**
* Interface to something that can be remotely executed as a task.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Task extends Serializable {
/**
* Execute this task.
*/
void execute();
/**
* Clients should be able to call this method at any time to obtain
* information on a current task.
*
* @return a TaskStatusInfo object holding info and result (if available) for
* this task
*/
TaskStatusInfo getTaskStatus();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/experiment/TaskStatusInfo.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* TaskStatusInfo.java
* Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.experiment;
import java.io.Serializable;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
/**
* A class holding information for tasks being executed
* on RemoteEngines. Also holds an object encapsulating any returnable result
* produced by the task (Note: result object must be serializable). Task
* objects execute methods return instances of this class. RemoteEngines also
* use this class for storing progress information for tasks that they
* execute.
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision$
*/
public class TaskStatusInfo
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -6129343303703560015L;
public static final int TO_BE_RUN = 0;
public static final int PROCESSING=1;
public static final int FAILED=2;
public static final int FINISHED=3;
/**
* Holds current execution status.
*/
private int m_ExecutionStatus = TO_BE_RUN;
/**
* Holds current status message.
*/
private String m_StatusMessage = "New Task";
/**
* Holds task result. Set to null for no returnable result.
*/
private Object m_TaskResult = null;
/**
* Set the execution status of this Task.
*
* @param newStatus the new execution status code
*/
public void setExecutionStatus(int newStatus) {
m_ExecutionStatus = newStatus;
}
/**
* Get the execution status of this Task.
* @return the execution status
*/
public int getExecutionStatus() {
return m_ExecutionStatus;
}
/**
* Set the status message.
*
* @param newMessage the new status message
*/
public void setStatusMessage(String newMessage) {
m_StatusMessage = newMessage;
}
/**
* Get the status message.
*
* @return the status message
*/
public String getStatusMessage() {
return m_StatusMessage;
}
/**
* Set the returnable result for this task..
*
* @param taskResult the new returnable result for the task. null if no
* result is returnable.
*/
public void setTaskResult(Object taskResult) {
m_TaskResult = taskResult;
}
/**
* Get the returnable result of this task.
*
* @return an object encapsulating the result of executing the task. May
* be null if the task has no returnable result (eg. a remote experiment
* task that sends its results to a data base).
*/
public Object getTaskResult() {
return m_TaskResult;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/experiment/Tester.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Tester.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.experiment;
import java.io.Serializable;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Range;
/**
* Interface for different kinds of Testers in the Experimenter.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface Tester
extends Serializable {
/**
* returns the name of the testing algorithm
*/
public String getDisplayName();
/**
* returns a string that is displayed as tooltip on the "perform test"
* button in the experimenter
*/
public String getToolTipText();
/**
* retrieves all the settings from the given Tester
*
* @param tester the Tester to get the settings from
*/
public void assign(Tester tester);
/**
* Sets the matrix to use to produce the output.
* @param matrix the instance to use to produce the output
* @see ResultMatrix
*/
public void setResultMatrix(ResultMatrix matrix);
/**
* Gets the instance that produces the output.
* @return the instance to produce the output
*/
public ResultMatrix getResultMatrix();
/**
* Set whether standard deviations are displayed or not.
* @param s true if standard deviations are to be displayed
*/
public void setShowStdDevs(boolean s);
/**
* Returns true if standard deviations have been requested.
* @return true if standard deviations are to be displayed.
*/
public boolean getShowStdDevs();
/**
* Gets the number of datasets in the resultsets
*
* @return the number of datasets in the resultsets
*/
public int getNumDatasets();
/**
* Gets the number of resultsets in the data.
*
* @return the number of resultsets in the data
*/
public int getNumResultsets();
/**
* Gets a string descriptive of the specified resultset.
*
* @param index the index of the resultset
* @return a descriptive string for the resultset
*/
public String getResultsetName(int index);
/**
* Checks whether the resultset with the given index shall be displayed.
*
* @param index the index of the resultset to check whether it shall be displayed
* @return whether the specified resultset is displayed
*/
public boolean displayResultset(int index);
/**
* Computes a paired t-test comparison for a specified dataset between
* two resultsets.
*
* @param datasetSpecifier the dataset specifier
* @param resultset1Index the index of the first resultset
* @param resultset2Index the index of the second resultset
* @param comparisonColumn the column containing values to compare
* @return the results of the paired comparison
* @exception Exception if an error occurs
*/
public PairedStats calculateStatistics(Instance datasetSpecifier,
int resultset1Index,
int resultset2Index,
int comparisonColumn) throws Exception;
/**
* Creates a key that maps resultset numbers to their descriptions.
*
* @return a value of type 'String'
*/
public String resultsetKey();
/**
* Creates a "header" string describing the current resultsets.
*
* @param comparisonColumn a value of type 'int'
* @return a value of type 'String'
*/
public String header(int comparisonColumn);
/**
* Carries out a comparison between all resultsets, counting the number
* of datsets where one resultset outperforms the other.
*
* @param comparisonColumn the index of the comparison column
* @return a 2d array where element [i][j] is the number of times resultset
* j performed significantly better than resultset i.
* @exception Exception if an error occurs
*/
public int [][] multiResultsetWins(int comparisonColumn, int [][] nonSigWin)
throws Exception;
/**
* Carries out a comparison between all resultsets, counting the number
* of datsets where one resultset outperforms the other. The results
* are summarized in a table.
*
* @param comparisonColumn the index of the comparison column
* @return the results in a string
* @exception Exception if an error occurs
*/
public String multiResultsetSummary(int comparisonColumn)
throws Exception;
public String multiResultsetRanking(int comparisonColumn)
throws Exception;
/**
* Creates a comparison table where a base resultset is compared to the
* other resultsets. Results are presented for every dataset.
*
* @param baseResultset the index of the base resultset
* @param comparisonColumn the index of the column to compare over
* @return the comparison table string
* @exception Exception if an error occurs
*/
public String multiResultsetFull(int baseResultset,
int comparisonColumn) throws Exception;
/**
* Get the value of ResultsetKeyColumns.
*
* @return Value of ResultsetKeyColumns.
*/
public Range getResultsetKeyColumns();
/**
* Set the value of ResultsetKeyColumns.
*
* @param newResultsetKeyColumns Value to assign to ResultsetKeyColumns.
*/
public void setResultsetKeyColumns(Range newResultsetKeyColumns);
/**
* Gets the indices of the the datasets that are displayed (if <code>null</code>
* then all are displayed). The base is always displayed.
*
* @return the indices of the datasets to display
*/
public int[] getDisplayedResultsets();
/**
* Sets the indicies of the datasets to display (<code>null</code> means all).
* The base is always displayed.
*
* @param cols the indices of the datasets to display
*/
public void setDisplayedResultsets(int[] cols);
/**
* Get the value of SignificanceLevel.
*
* @return Value of SignificanceLevel.
*/
public double getSignificanceLevel();
/**
* Set the value of SignificanceLevel.
*
* @param newSignificanceLevel Value to assign to SignificanceLevel.
*/
public void setSignificanceLevel(double newSignificanceLevel);
/**
* Get the value of DatasetKeyColumns.
*
* @return Value of DatasetKeyColumns.
*/
public Range getDatasetKeyColumns();
/**
* Set the value of DatasetKeyColumns.
*
* @param newDatasetKeyColumns Value to assign to DatasetKeyColumns.
*/
public void setDatasetKeyColumns(Range newDatasetKeyColumns);
/**
* Get the value of RunColumn.
*
* @return Value of RunColumn.
*/
public int getRunColumn();
/**
* Set the value of RunColumn.
*
* @param newRunColumn Value to assign to RunColumn.
*/
public void setRunColumn(int newRunColumn);
/**
* Get the value of FoldColumn.
*
* @return Value of FoldColumn.
*/
public int getFoldColumn();
/**
* Set the value of FoldColumn.
*
* @param newFoldColumn Value to assign to FoldColumn.
*/
public void setFoldColumn(int newFoldColumn);
/**
* Returns the name of the column to sort on.
*
* @return the name of the column to sort on.
*/
public String getSortColumnName();
/**
* Returns the column to sort on, -1 means the default sorting.
*
* @return the column to sort on.
*/
public int getSortColumn();
/**
* Set the column to sort on, -1 means the default sorting.
*
* @param newSortColumn the new sort column.
*/
public void setSortColumn(int newSortColumn);
/**
* Get the value of Instances.
*
* @return Value of Instances.
*/
public Instances getInstances();
/**
* Set the value of Instances.
*
* @param newInstances Value to assign to Instances.
*/
public void setInstances(Instances newInstances);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/experiment
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/experiment/xml/XMLExperiment.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* XMLExperiment.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.experiment.xml;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import org.w3c.dom.Element;
import weka.core.RevisionUtils;
import weka.core.xml.XMLBasicSerialization;
import weka.core.xml.XMLDocument;
import weka.experiment.Experiment;
import weka.experiment.PropertyNode;
/**
* This class serializes and deserializes an Experiment instance to and fro XML.<br>
* It omits the <code>options</code> from the Experiment, since these are
* handled by the get/set-methods. For the <code>Classifier</code> class with
* all its derivative classes it stores only <code>debug</code> and
* <code>options</code>. For <code>SplitEvaluator</code> and
* <code>ResultProducer</code> only the options are retrieved. The
* <code>PropertyNode</code> is done manually since it has no get/set-methods
* for its public fields.<br>
* Since there's no read-method for <code>m_ClassFirst</code> we always save it
* as <code>false</code>.
*
* @see Experiment#m_ClassFirst
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class XMLExperiment extends XMLBasicSerialization {
/** the name of the classFirst property */
public final static String NAME_CLASSFIRST = "classFirst";
/** PropertyNode member */
public final static String NAME_PROPERTYNODE_VALUE = "value";
/** PropertyNode member */
public final static String NAME_PROPERTYNODE_PARENTCLASS = "parentClass";
/** PropertyNode member */
public final static String NAME_PROPERTYNODE_PROPERTY = "property";
/**
* initializes the serialization
*
* @throws Exception if initialization fails
*/
public XMLExperiment() throws Exception {
super();
}
/**
* generates internally a new XML document and clears also the IgnoreList and
* the mappings for the Read/Write-Methods
*
* @throws Exception if initializing fails
*/
@Override
public void clear() throws Exception {
super.clear();
// ignore
m_Properties.addIgnored(VAL_ROOT + ".options");
m_Properties.addIgnored(Experiment.class, "options");
// allow
m_Properties.addAllowed(weka.classifiers.Classifier.class, "debug");
m_Properties.addAllowed(weka.classifiers.Classifier.class, "options");
// we assume that classes implementing SplitEvaluator also implement
// OptionHandler
m_Properties.addAllowed(weka.experiment.SplitEvaluator.class, "options");
// we assume that classes implementing ResultProducer also implement
// OptionHandler
m_Properties.addAllowed(weka.experiment.ResultProducer.class, "options");
// read/write methods
m_CustomMethods.register(this, PropertyNode.class, "PropertyNode");
}
/**
* enables derived classes to add other properties to the DOM tree, e.g. ones
* that do not apply to the get/set convention of beans.
*
* @param o the object that is serialized into XML
* @throws Exception if post-processing fails
*/
@Override
protected void writePostProcess(Object o) throws Exception {
Element node;
// classfirst
node = addElement(m_Document.getDocument().getDocumentElement(),
NAME_CLASSFIRST, Boolean.class.getName(), false);
node.appendChild(node.getOwnerDocument().createTextNode(
new Boolean(false).toString())); // TODO: get-Method for classFirst in
// Experiment???
}
/**
* additional post-processing can happen in derived classes after reading from
* XML.
*
* @param o the object to perform some additional processing on
* @return the processed object
* @throws Exception if post-processing fails
*/
@Override
protected Object readPostProcess(Object o) throws Exception {
Element node;
Experiment exp;
int i;
Vector<Element> children;
exp = (Experiment) o;
// classfirst
children = XMLDocument.getChildTags(m_Document.getDocument()
.getDocumentElement());
for (i = 0; i < children.size(); i++) {
node = children.get(i);
if (node.getAttribute(ATT_NAME).equals(NAME_CLASSFIRST)) {
exp
.classFirst(new Boolean(XMLDocument.getContent(node)).booleanValue());
break;
}
}
return o;
}
/**
* adds the given PropertyNode to a DOM structure.
*
* @param parent the parent of this object, e.g. the class this object is a
* member of
* @param o the Object to describe in XML
* @param name the name of the object
* @return the node that was created
* @throws Exception if the DOM creation fails
*/
public Element writePropertyNode(Element parent, Object o, String name)
throws Exception {
Element node;
PropertyNode pnode;
Vector<Element> children;
int i;
Element child;
// for debugging only
if (DEBUG) {
trace(new Throwable(), name);
}
m_CurrentNode = parent;
pnode = (PropertyNode) o;
node = (Element) parent.appendChild(m_Document.getDocument().createElement(
TAG_OBJECT));
node.setAttribute(ATT_NAME, name);
node.setAttribute(ATT_CLASS, pnode.getClass().getName());
node.setAttribute(ATT_PRIMITIVE, VAL_NO);
node.setAttribute(ATT_ARRAY, VAL_NO);
if (pnode.value != null) {
invokeWriteToXML(node, pnode.value, NAME_PROPERTYNODE_VALUE);
}
if (pnode.parentClass != null) {
invokeWriteToXML(node, pnode.parentClass.getName(),
NAME_PROPERTYNODE_PARENTCLASS);
}
if (pnode.property != null) {
invokeWriteToXML(node, pnode.property.getDisplayName(),
NAME_PROPERTYNODE_PROPERTY);
}
// fix primitive values
if ((pnode.value != null) && (pnode.property != null)
&& (pnode.property.getPropertyType().isPrimitive())) {
children = XMLDocument.getChildTags(node);
for (i = 0; i < children.size(); i++) {
child = children.get(i);
if (!child.getAttribute(ATT_NAME).equals(NAME_PROPERTYNODE_VALUE)) {
continue;
}
child.setAttribute(ATT_CLASS, pnode.property.getPropertyType()
.getName());
child.setAttribute(ATT_PRIMITIVE, VAL_YES);
}
}
return node;
}
/**
* builds the PropertyNode from the given DOM node.
*
* @param node the associated XML node
* @return the instance created from the XML description
* @throws Exception if instantiation fails
* @see javax.swing.DefaultListModel
*/
public Object readPropertyNode(Element node) throws Exception {
Object result;
Object value;
String parentClass;
String property;
Vector<Element> children;
Element child;
int i;
Class<?> cls;
// for debugging only
if (DEBUG) {
trace(new Throwable(), node.getAttribute(ATT_NAME));
}
m_CurrentNode = node;
result = null;
children = XMLDocument.getChildTags(node);
value = null;
parentClass = null;
property = null;
for (i = 0; i < children.size(); i++) {
child = children.get(i);
if (child.getAttribute(ATT_NAME).equals(NAME_PROPERTYNODE_VALUE)) {
if (stringToBoolean(child.getAttribute(ATT_PRIMITIVE))) {
value = getPrimitive(child);
} else {
value = invokeReadFromXML(child);
}
}
if (child.getAttribute(ATT_NAME).equals(NAME_PROPERTYNODE_PARENTCLASS)) {
parentClass = XMLDocument.getContent(child);
}
if (child.getAttribute(ATT_NAME).equals(NAME_PROPERTYNODE_PROPERTY)) {
property = XMLDocument.getContent(child);
}
}
if (parentClass != null) {
cls = Class.forName(parentClass);
} else {
cls = null;
}
if (cls != null) {
result = new PropertyNode(value, new PropertyDescriptor(property, cls),
cls);
} else {
result = new PropertyNode(value);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* for testing only. if the first argument is a filename with ".xml" as
* extension it tries to generate an instance from the XML description and
* does a <code>toString()</code> of the generated object. Otherwise it loads
* the binary file, saves the XML representation in a file with the original
* filename appended by ".xml" and once again in a binary file with the
* original filename appended by ".exp".
*
* @param args the commandline arguments
* @throws Exception if something goes wrong, e.g., file not found
*/
public static void main(String[] args) throws Exception {
if (args.length > 0) {
// read xml and print
if (args[0].toLowerCase().endsWith(".xml")) {
System.out.println(new XMLExperiment().read(args[0]).toString());
}
// read binary and print generated XML
else {
// read
FileInputStream fi = new FileInputStream(args[0]);
ObjectInputStream oi = new ObjectInputStream(
new BufferedInputStream(fi));
Object o = oi.readObject();
oi.close();
// print to stdout
// new XMLExperiment().write(System.out, o);
// write to XML file
new XMLExperiment().write(new BufferedOutputStream(
new FileOutputStream(args[0] + ".xml")), o);
// print to binary file
FileOutputStream fo = new FileOutputStream(args[0] + ".exp");
ObjectOutputStream oo = new ObjectOutputStream(
new BufferedOutputStream(fo));
oo.writeObject(o);
oo.close();
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/AllFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AllFilter.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import weka.core.*;
import weka.core.Capabilities.Capability;
/**
* A simple instance filter that passes all instances directly
* through. Basically just for testing purposes.
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class AllFilter
extends Filter
implements Sourcable, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 5022109283147503266L;
/**
* 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 passes all instances through unmodified."
+ " Primarily for testing purposes.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 something goes wrong
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
return true;
}
/**
* 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 (instance.dataset() == null) {
push((Instance) instance.copy());
} else {
push(instance); // push() will make a copy anyway.
}
return true;
}
/**
* Returns a string that describes the filter as source. The
* filter will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain two methods with these signatures:
* <pre><code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
public String toSource(String className, Instances data) throws Exception {
StringBuffer result;
result = new StringBuffer();
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" return i;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" return i;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String [] argv) {
runFilter(new AllFilter(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/CheckSource.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* CheckSource.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters;
import java.io.File;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;
/**
* A simple class for checking the source generated from Filters implementing the <code>weka.filters.Sourcable</code> interface. It takes a filter, the classname of the generated source and the dataset the source was generated with as
* parameters and tests the output of the built filter against the output of the generated source. Use option '-h' to display all available commandline options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <classname and options>
* The filter (incl. options) that was used to generate
* the source code.
* </pre>
*
* <pre>
* -S <classname>
* The classname of the generated source code.
* </pre>
*
* <pre>
* -t <file>
* The training set with which the source code was generated.
* </pre>
*
* <pre>
* -c <index>
* The class index of the training set. 'first' and 'last' are
* valid indices.
* (default: none)
* </pre>
*
* <!-- options-end -->
*
* Options after -- are passed to the designated filter.
* <p>
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see weka.filters.Sourcable
*/
public class CheckSource implements OptionHandler, RevisionHandler {
/** the classifier used for generating the source code */
protected Filter m_Filter = null;
/** the generated source code */
protected Filter m_SourceCode = null;
/** the dataset to use for testing */
protected File m_Dataset = null;
/** the class index */
protected int m_ClassIndex = -1;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe filter (incl. options) that was used to generate\n" + "\tthe source code.", "W", 1, "-W <classname and options>"));
result.addElement(new Option("\tThe classname of the generated source code.", "S", 1, "-S <classname>"));
result.addElement(new Option("\tThe training set with which the source code was generated.", "t", 1, "-t <file>"));
result.addElement(new Option("\tThe class index of the training set. 'first' and 'last' are\n" + "\tvalid indices.\n" + "\t(default: none)", "c", 1, "-c <index>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <classname and options>
* The filter (incl. options) that was used to generate
* the source code.
* </pre>
*
* <pre>
* -S <classname>
* The classname of the generated source code.
* </pre>
*
* <pre>
* -t <file>
* The training set with which the source code was generated.
* </pre>
*
* <pre>
* -c <index>
* The class index of the training set. 'first' and 'last' are
* valid indices.
* (default: none)
* </pre>
*
* <!-- options-end -->
*
* Options after -- are passed to the designated filter.
* <p>
*
* @param options
* the list of options as an array of strings
* @throws Exception
* if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr;
String[] spec;
String classname;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() > 0) {
spec = Utils.splitOptions(tmpStr);
if (spec.length == 0) {
throw new IllegalArgumentException("Invalid filter specification string");
}
classname = spec[0];
spec[0] = "";
this.setFilter((Filter) Utils.forName(Filter.class, classname, spec));
} else {
throw new Exception("No filter (classname + options) provided!");
}
tmpStr = Utils.getOption('S', options);
if (tmpStr.length() > 0) {
spec = Utils.splitOptions(tmpStr);
if (spec.length != 1) {
throw new IllegalArgumentException("Invalid source code specification string");
}
classname = spec[0];
spec[0] = "";
this.setSourceCode((Filter) Utils.forName(Filter.class, classname, spec));
} else {
throw new Exception("No source code (classname) provided!");
}
tmpStr = Utils.getOption('t', options);
if (tmpStr.length() != 0) {
this.setDataset(new File(tmpStr));
} else {
throw new Exception("No dataset provided!");
}
tmpStr = Utils.getOption('c', options);
if (tmpStr.length() != 0) {
if (tmpStr.equals("first")) {
this.setClassIndex(0);
} else if (tmpStr.equals("last")) {
this.setClassIndex(-2);
} else {
this.setClassIndex(Integer.parseInt(tmpStr) - 1);
}
} else {
this.setClassIndex(-1);
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
if (this.getFilter() != null) {
result.add("-W");
result.add(this.getFilter().getClass().getName() + " " + Utils.joinOptions(((OptionHandler) this.getFilter()).getOptions()));
}
if (this.getSourceCode() != null) {
result.add("-S");
result.add(this.getSourceCode().getClass().getName());
}
if (this.getDataset() != null) {
result.add("-t");
result.add(this.m_Dataset.getAbsolutePath());
}
if (this.getClassIndex() != -1) {
result.add("-c");
if (this.getClassIndex() == -2) {
result.add("last");
} else if (this.getClassIndex() == 0) {
result.add("first");
} else {
result.add("" + (this.getClassIndex() + 1));
}
}
return result.toArray(new String[result.size()]);
}
/**
* Sets the filter to use for the comparison.
*
* @param value
* the filter to use
*/
public void setFilter(final Filter value) {
this.m_Filter = value;
}
/**
* Gets the filter being used for the tests, can be null.
*
* @return the currently set filter
*/
public Filter getFilter() {
return this.m_Filter;
}
/**
* Sets the class to test.
*
* @param value
* the class to test
*/
public void setSourceCode(final Filter value) {
this.m_SourceCode = value;
}
/**
* Gets the class to test.
*
* @return the currently set class, can be null.
*/
public Filter getSourceCode() {
return this.m_SourceCode;
}
/**
* Sets the dataset to use for testing.
*
* @param value
* the dataset to use.
*/
public void setDataset(final File value) {
if (!value.exists()) {
throw new IllegalArgumentException("Dataset '" + value.getAbsolutePath() + "' does not exist!");
} else {
this.m_Dataset = value;
}
}
/**
* Gets the dataset to use for testing, can be null.
*
* @return the dataset to use.
*/
public File getDataset() {
return this.m_Dataset;
}
/**
* Sets the class index of the dataset.
*
* @param value
* the class index of the dataset.
*/
public void setClassIndex(final int value) {
this.m_ClassIndex = value;
}
/**
* Gets the class index of the dataset.
*
* @return the current class index.
*/
public int getClassIndex() {
return this.m_ClassIndex;
}
/**
* compares two Instance
*
* @param inst1
* the first Instance object to compare
* @param inst2
* the second Instance object to compare
* @return true if both are the same
*/
protected boolean compare(final Instance inst1, final Instance inst2) {
boolean result;
int i;
// check dimension
result = (inst1.numAttributes() == inst2.numAttributes());
// check content
if (result) {
for (i = 0; i < inst1.numAttributes(); i++) {
if (Double.isNaN(inst1.value(i)) && (Double.isNaN(inst2.value(i)))) {
continue;
}
if (inst1.value(i) != inst2.value(i)) {
result = false;
break;
}
}
}
return result;
}
/**
* compares the two Instances objects
*
* @param inst1
* the first Instances object to compare
* @param inst2
* the second Instances object to compare
* @return true if both are the same
*/
protected boolean compare(final Instances inst1, final Instances inst2) {
boolean result;
int i;
// check dimensions
result = (inst1.numInstances() == inst2.numInstances());
// check content
if (result) {
for (i = 0; i < inst1.numInstances(); i++) {
result = this.compare(inst1.instance(i), inst2.instance(i));
if (!result) {
break;
}
}
}
return result;
}
/**
* performs the comparison test
*
* @return true if tests were successful
* @throws Exception
* if tests fail
*/
public boolean execute() throws Exception {
boolean result;
Instances data;
Instance filteredInstance;
Instances filteredInstances;
Instance filteredInstanceSource;
Instances filteredInstancesSource;
DataSource source;
Filter filter;
Filter filterSource;
int i;
result = true;
// a few checks
if (this.getFilter() == null) {
throw new Exception("No filter set!");
}
if (this.getSourceCode() == null) {
throw new Exception("No source code set!");
}
if (this.getDataset() == null) {
throw new Exception("No dataset set!");
}
if (!this.getDataset().exists()) {
throw new Exception("Dataset '" + this.getDataset().getAbsolutePath() + "' does not exist!");
}
// load data
source = new DataSource(this.getDataset().getAbsolutePath());
data = source.getDataSet();
if (this.getClassIndex() == -2) {
data.setClassIndex(data.numAttributes() - 1);
} else {
data.setClassIndex(this.getClassIndex());
}
// compare output
// 1. batch filtering
filter = Filter.makeCopy(this.getFilter());
filter.setInputFormat(data);
filteredInstances = Filter.useFilter(data, filter);
filterSource = Filter.makeCopy(this.getSourceCode());
filterSource.setInputFormat(data);
filteredInstancesSource = Filter.useFilter(data, filterSource);
result = this.compare(filteredInstances, filteredInstancesSource);
// 2. instance by instance
if (result) {
filter = Filter.makeCopy(this.getFilter());
filter.setInputFormat(data);
Filter.useFilter(data, filter);
filterSource = Filter.makeCopy(this.getSourceCode());
filterSource.setInputFormat(data);
for (i = 0; i < data.numInstances(); i++) {
filter.input(data.instance(i));
filter.batchFinished();
filteredInstance = filter.output();
filterSource.input(data.instance(i));
filterSource.batchFinished();
filteredInstanceSource = filterSource.output();
}
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Executes the tests, use "-h" to list the commandline options.
*
* @param args
* the commandline parameters
* @throws Exception
* if something goes wrong
*/
public static void main(final String[] args) throws Exception {
CheckSource check;
StringBuffer text;
Enumeration<Option> enm;
check = new CheckSource();
if (Utils.getFlag('h', args)) {
text = new StringBuffer();
text.append("\nHelp requested:\n\n");
enm = check.listOptions();
while (enm.hasMoreElements()) {
Option option = enm.nextElement();
text.append(option.synopsis() + "\n");
text.append(option.description() + "\n");
}
} else {
check.setOptions(args);
if (check.execute()) {
System.out.println("Tests OK!");
} else {
System.out.println("Tests failed!");
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/Filter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Filter.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.CapabilitiesHandler;
import weka.core.CapabilitiesIgnorer;
import weka.core.CommandlineRunnable;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Queue;
import weka.core.RelationalLocator;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.SerializedObject;
import weka.core.StringLocator;
import weka.core.UnsupportedAttributeTypeException;
import weka.core.Utils;
import weka.core.Version;
import weka.core.converters.ConverterUtils.DataSource;
/**
* An abstract class for instance filters: objects that take instances as input,
* carry out some transformation on the instance and then output the instance.
* The method implementations in this class assume that most of the work will be
* done in the methods overridden by subclasses.
* <p>
*
* A simple example of filter use. This example doesn't remove instances from
* the output queue until all instances have been input, so has higher memory
* consumption than an approach that uses output instances as they are made
* available:
* <p>
*
* <code> <pre>
* Filter filter = ..some type of filter..
* Instances instances = ..some instances..
* for (int i = 0; i < data.numInstances(); i++) {
* filter.input(data.instance(i));
* }
* filter.batchFinished();
* Instances newData = filter.outputFormat();
* Instance processed;
* while ((processed = filter.output()) != null) {
* newData.add(processed);
* }
* ..do something with newData..
* </pre> </code>
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class Filter implements Serializable, CapabilitiesHandler, RevisionHandler, OptionHandler, CapabilitiesIgnorer, CommandlineRunnable {
/** for serialization */
private static final long serialVersionUID = -8835063755891851218L;
/** The output format for instances */
private Instances m_OutputFormat = null;
/** The output instance queue */
private Queue m_OutputQueue = null;
/** Indices of string attributes in the output format */
protected StringLocator m_OutputStringAtts = null;
/** Indices of string attributes in the input format */
protected StringLocator m_InputStringAtts = null;
/** Indices of relational attributes in the output format */
protected RelationalLocator m_OutputRelAtts = null;
/** Indices of relational attributes in the input format */
protected RelationalLocator m_InputRelAtts = null;
/** The input format for instances */
private Instances m_InputFormat = null;
/** Record whether the filter is at the start of a batch */
protected boolean m_NewBatch = true;
/** True if the first batch has been done */
protected boolean m_FirstBatchDone = false;
/** Whether the classifier is run in debug mode. */
protected boolean m_Debug = false;
/** Whether capabilities should not be checked before classifier is built. */
protected boolean m_DoNotCheckCapabilities = false;
/**
* Returns true if the a new batch was started, either a new instance of the
* filter was created or the batchFinished() method got called.
*
* @return true if a new batch has been initiated
* @see #m_NewBatch
* @see #batchFinished()
*/
public boolean isNewBatch() {
return this.m_NewBatch;
}
/**
* Returns true if the first batch of instances got processed. Necessary for
* supervised filters, which "learn" from the first batch and then shouldn't
* get updated with subsequent calls of batchFinished().
*
* @return true if the first batch has been processed
* @see #m_FirstBatchDone
* @see #batchFinished()
*/
public boolean isFirstBatchDone() {
return this.m_FirstBatchDone;
}
/**
* Default implementation returns false. Some filters may not necessarily be
* able to produce an instance for output for every instance input after the
* first batch has been completed - such filters should override this method
* and return true.
*
* @return false by default
*/
public boolean mayRemoveInstanceAfterFirstBatchDone() {
return false;
}
/**
* Returns the Capabilities of this filter. Derived filters have to override
* this method to enable capabilities.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
result = new Capabilities(this);
result.enableAll();
result.setMinimumNumberInstances(0);
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Returns the Capabilities of this filter, customized based on the data.
* I.e., if removes all class capabilities, in case there's not class
* attribute present or removes the NO_CLASS capability, in case that there's
* a class present.
*
* @param data the data to use for customization
* @return the capabilities of this object, based on the data
* @see #getCapabilities()
*/
public Capabilities getCapabilities(final Instances data) {
Capabilities result;
Capabilities classes;
Iterator<Capability> iter;
Capability cap;
result = this.getCapabilities();
// no class? -> remove all class capabilites apart from NO_CLASS
if (data.classIndex() == -1) {
classes = result.getClassCapabilities();
iter = classes.capabilities();
while (iter.hasNext()) {
cap = iter.next();
if (cap != Capability.NO_CLASS) {
result.disable(cap);
result.disableDependency(cap);
}
}
}
// class? -> remove NO_CLASS
else {
result.disable(Capability.NO_CLASS);
result.disableDependency(Capability.NO_CLASS);
}
return result;
}
/**
* Sets the format of output instances. The derived class should use this
* method once it has determined the outputformat. The output queue is
* cleared.
*
* @param outputFormat the new output format
*/
protected void setOutputFormat(final Instances outputFormat) {
if (outputFormat != null) {
this.m_OutputFormat = outputFormat.stringFreeStructure();
this.initOutputLocators(this.m_OutputFormat, null);
// Rename the relation
String relationName = outputFormat.relationName() + "-" + this.getClass().getName();
if (this instanceof OptionHandler) {
String[] options = ((OptionHandler) this).getOptions();
for (String option : options) {
relationName += option.trim();
}
}
this.m_OutputFormat.setRelationName(relationName);
} else {
this.m_OutputFormat = null;
}
this.m_OutputQueue = new Queue();
}
/**
* Gets the currently set inputformat instances. This dataset may contain
* buffered instances.
*
* @return the input Instances.
*/
protected Instances getInputFormat() {
return this.m_InputFormat;
}
/**
* Gets a copy of just the structure of the input format instances.
*
* @return a copy of the structure (attribute information) of the input
* format instances
*/
public Instances getCopyOfInputFormat() {
return this.getInputFormat() == null ? null : new Instances(this.getInputFormat(), 0);
}
/**
* Returns a reference to the current input format without copying it.
*
* @return a reference to the current input format
*/
protected Instances inputFormatPeek() {
return this.m_InputFormat;
}
/**
* Returns a reference to the current output format without copying it.
*
* @return a reference to the current output format
*/
protected Instances outputFormatPeek() {
return this.m_OutputFormat;
}
/**
* Adds an output instance to the queue. The derived class should use this
* method for each output instance it makes available. Note that the instance
* is only copied before it is added to the output queue if it has a reference
* to a dataset.
*
* @param instance the instance to be added to the queue.
*/
protected void push(final Instance instance) {
this.push(instance, true);
}
/**
* Adds an output instance to the queue. The derived class should use this
* method for each output instance it makes available. Note that the instance
* is only copied before it is added to the output queue if copyInstance has
* value true and if the instance has a reference to a dataset.
*
* @param instance the instance to be added to the queue.
* @param copyInstance whether instance is to be copied
*/
protected void push(Instance instance, final boolean copyInstance) {
if (instance != null) {
if (instance.dataset() != null) {
if (copyInstance) {
instance = (Instance) instance.copy();
}
this.copyValues(instance, false);
}
instance.setDataset(this.m_OutputFormat);
this.m_OutputQueue.push(instance);
}
}
/**
* Clears the output queue.
*/
protected void resetQueue() {
this.m_OutputQueue = new Queue();
}
/**
* Adds the supplied input instance to the inputformat dataset for later
* processing. Use this method rather than getInputFormat().add(instance). Or
* else. Note that the provided instance gets copied when buffered.
*
* @param instance the <code>Instance</code> to buffer.
*/
protected void bufferInput(Instance instance) {
if (instance != null) {
instance = (Instance) instance.copy(); // The copyValues() method *does* modify the instance!
this.copyValues(instance, true);
this.m_InputFormat.add(instance);
}
}
/**
* Initializes the input attribute locators. If indices is null then all
* attributes of the data will be considered, otherwise only the ones that
* were provided.
*
* @param data the data to initialize the locators with
* @param indices if not null, the indices to which to restrict the locating
*/
protected void initInputLocators(final Instances data, final int[] indices) {
if (indices == null) {
this.m_InputStringAtts = new StringLocator(data);
this.m_InputRelAtts = new RelationalLocator(data);
} else {
this.m_InputStringAtts = new StringLocator(data, indices);
this.m_InputRelAtts = new RelationalLocator(data, indices);
}
}
/**
* Initializes the output attribute locators. If indices is null then all
* attributes of the data will be considered, otherwise only the ones that
* were provided.
*
* @param data the data to initialize the locators with
* @param indices if not null, the indices to which to restrict the locating
*/
protected void initOutputLocators(final Instances data, final int[] indices) {
if (indices == null) {
this.m_OutputStringAtts = new StringLocator(data);
this.m_OutputRelAtts = new RelationalLocator(data);
} else {
this.m_OutputStringAtts = new StringLocator(data, indices);
this.m_OutputRelAtts = new RelationalLocator(data, indices);
}
}
/**
* Copies string/relational values contained in the instance copied to a new
* dataset. The Instance must already be assigned to a dataset. This dataset
* and the destination dataset must have the same structure.
*
* @param instance the Instance containing the string/relational values to
* copy.
* @param isInput if true the input format and input attribute locators are
* used otherwise the output format and output locators
*/
protected void copyValues(final Instance instance, final boolean isInput) {
RelationalLocator.copyRelationalValues(instance, (isInput) ? this.m_InputFormat : this.m_OutputFormat, (isInput) ? this.m_InputRelAtts : this.m_OutputRelAtts);
StringLocator.copyStringValues(instance, (isInput) ? this.m_InputFormat : this.m_OutputFormat, (isInput) ? this.m_InputStringAtts : this.m_OutputStringAtts);
}
/**
* Takes string/relational values referenced by an Instance and copies them
* from a source dataset to a destination dataset. The instance references are
* updated to be valid for the destination dataset. The instance may have the
* structure (i.e. number and attribute position) of either dataset (this
* affects where references are obtained from). Only works if the number of
* string/relational attributes is the same in both indices (implicitly these
* string/relational attributes should be semantically same but just with
* shifted positions).
*
* @param instance the instance containing references to strings/ relational
* values in the source dataset that will have references updated to
* be valid for the destination dataset.
* @param instSrcCompat true if the instance structure is the same as the
* source, or false if it is the same as the destination (i.e. which
* of the string/relational attribute indices contains the correct
* locations for this instance).
* @param srcDataset the dataset for which the current instance
* string/relational value references are valid (after any position
* mapping if needed)
* @param destDataset the dataset for which the current instance
* string/relational value references need to be inserted (after any
* position mapping if needed)
*/
protected void copyValues(final Instance instance, final boolean instSrcCompat, final Instances srcDataset, final Instances destDataset) {
RelationalLocator.copyRelationalValues(instance, instSrcCompat, srcDataset, this.m_InputRelAtts, destDataset, this.m_OutputRelAtts);
StringLocator.copyStringValues(instance, instSrcCompat, srcDataset, this.m_InputStringAtts, destDataset, this.m_OutputStringAtts);
}
/**
* This will remove all buffered instances from the inputformat dataset. Use
* this method rather than getInputFormat().delete();
*/
protected void flushInput() {
if ((this.m_InputStringAtts.getAttributeIndices().length > 0) || (this.m_InputRelAtts.getAttributeIndices().length > 0)) {
this.m_InputFormat = this.m_InputFormat.stringFreeStructure();
this.m_InputStringAtts = new StringLocator(this.m_InputFormat, this.m_InputStringAtts.getAllowedIndices());
this.m_InputRelAtts = new RelationalLocator(this.m_InputFormat, this.m_InputRelAtts.getAllowedIndices());
} else {
// This more efficient than new Instances(m_InputFormat, 0);
this.m_InputFormat.delete();
}
}
/**
* tests the data whether the filter can actually handle it
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
protected void testInputFormat(final Instances instanceInfo) throws Exception {
this.getCapabilities(instanceInfo).testWithFail(instanceInfo);
}
/**
* Sets the format of the input instances. If the filter is able to determine
* the output format before seeing any input instances, it does so here. This
* default implementation clears the output format and output queue, and the
* new batch flag is set. Overriders should call
* <code>super.setInputFormat(Instances)</code>
*
* @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 inputFormat can't be set successfully
*/
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
this.testInputFormat(instanceInfo);
this.m_InputFormat = instanceInfo.stringFreeStructure();
this.m_OutputFormat = null;
this.m_OutputQueue = new Queue();
this.m_NewBatch = true;
this.m_FirstBatchDone = false;
this.initInputLocators(this.m_InputFormat, null);
return false;
}
/**
* Gets the format of the output instances. This should only be called after
* input() or batchFinished() has returned true. The relation name of the
* output instances should be changed to reflect the action of the filter (eg:
* add the filter name and options).
*
* @return an Instances object containing the output instance structure only.
* @throws NullPointerException if no input structure has been defined (or the
* output format hasn't been determined yet)
*/
public Instances getOutputFormat() {
if (this.m_OutputFormat == null) {
throw new NullPointerException("No output format defined.");
}
return new Instances(this.m_OutputFormat, 0);
}
/**
* 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, in which case output instances should be
* collected after calling batchFinished(). If the input marks the start of a
* new batch, the output queue is cleared. This default implementation assumes
* all instance conversion will occur when batchFinished() is called.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws NullPointerException if the input format has not been defined.
* @throws Exception if the input instance was not of the correct format or if
* there was a problem with the filtering.
*/
public boolean input(final Instance instance) throws Exception {
if (this.m_InputFormat == null) {
throw new NullPointerException("No input instance format defined");
}
if (this.m_NewBatch) {
this.m_OutputQueue = new Queue();
this.m_NewBatch = false;
}
this.bufferInput(instance);
return false;
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* inputFormat has been re-assigned or new options have been set). This
* default implementation assumes all instance processing occurs during
* inputFormat() and input().
*
* @return true if there are instances pending output
* @throws NullPointerException if no input structure has been defined,
* @throws Exception if there was a problem finishing the batch.
*/
public boolean batchFinished() throws Exception {
if (this.m_InputFormat == null) {
throw new NullPointerException("No input instance format defined");
}
this.flushInput();
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
if (this.m_OutputQueue.empty()) {
// Clear out references to old strings/relationals occasionally
if ((this.m_OutputStringAtts.getAttributeIndices().length > 0) || (this.m_OutputRelAtts.getAttributeIndices().length > 0)) {
this.m_OutputFormat = this.m_OutputFormat.stringFreeStructure();
this.m_OutputStringAtts = new StringLocator(this.m_OutputFormat, this.m_OutputStringAtts.getAllowedIndices());
}
}
return (this.numPendingOutput() != 0);
}
/**
* Output an instance after filtering and remove from the output queue.
*
* @return the instance that has most recently been filtered (or null if the
* queue is empty).
* @throws NullPointerException if no output structure has been defined
*/
public Instance output() {
if (this.m_OutputFormat == null) {
throw new NullPointerException("No output instance format defined");
}
if (this.m_OutputQueue.empty()) {
return null;
}
Instance result = (Instance) this.m_OutputQueue.pop();
// Clear out references to old strings/relationals occasionally
/*
* if (m_OutputQueue.empty() && m_NewBatch) { if (
* (m_OutputStringAtts.getAttributeIndices().length > 0) ||
* (m_OutputRelAtts.getAttributeIndices().length > 0) ) { m_OutputFormat =
* m_OutputFormat.stringFreeStructure(); } }
*/
return result;
}
/**
* Output an instance after filtering but do not remove from the output queue.
*
* @return the instance that has most recently been filtered (or null if the
* queue is empty).
* @throws NullPointerException if no input structure has been defined
*/
public Instance outputPeek() {
if (this.m_OutputFormat == null) {
throw new NullPointerException("No output instance format defined");
}
if (this.m_OutputQueue.empty()) {
return null;
}
Instance result = (Instance) this.m_OutputQueue.peek();
return result;
}
/**
* Returns the number of instances pending output
*
* @return the number of instances pending output
* @throws NullPointerException if no input structure has been defined
*/
public int numPendingOutput() {
if (this.m_OutputFormat == null) {
throw new NullPointerException("No output instance format defined");
}
return this.m_OutputQueue.size();
}
/**
* Returns whether the output format is ready to be collected
*
* @return true if the output format is set
*/
public boolean isOutputFormatDefined() {
return (this.m_OutputFormat != null);
}
/**
* Creates a deep copy of the given filter using serialization.
*
* @param model the filter to copy
* @return a deep copy of the filter
* @throws Exception if an error occurs
*/
public static Filter makeCopy(final Filter model) throws Exception {
return (Filter) new SerializedObject(model).getObject();
}
/**
* Creates a given number of deep copies of the given filter using
* serialization.
*
* @param model the filter to copy
* @param num the number of filter copies to create.
* @return an array of filters.
* @throws Exception if an error occurs
*/
public static Filter[] makeCopies(final Filter model, final int num) throws Exception {
if (model == null) {
throw new Exception("No model filter set");
}
Filter[] filters = new Filter[num];
SerializedObject so = new SerializedObject(model);
for (int i = 0; i < filters.length; i++) {
filters[i] = (Filter) so.getObject();
}
return filters;
}
/**
* Filters an entire set of instances through a filter and returns the new
* set.
*
* @param data the data to be filtered
* @param filter the filter to be used
* @return the filtered set of data
* @throws Exception if the filter can't be used successfully
*/
public static Instances useFilter(final Instances data, final Filter filter) throws Exception {
/*
* System.err.println(filter.getClass().getName() + " in:" +
* data.numInstances());
*/
for (int i = 0; i < data.numInstances(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
filter.input(data.instance(i));
}
filter.batchFinished();
Instances newData = filter.getOutputFormat();
Instance processed;
while ((processed = filter.output()) != null) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
newData.add(processed);
}
/*
* System.err.println(filter.getClass().getName() + " out:" +
* newData.numInstances());
*/
return newData;
}
/**
* Returns a description of the filter, by default only the classname.
*
* @return a string describing the filter
*/
@Override
public String toString() {
return this.getClass().getName();
}
/**
* generates source code from the filter
*
* @param filter the filter to output as source
* @param className the name of the generated class
* @param input the input data the header is generated for
* @param output the output data the header is generated for
* @return the generated source code
* @throws Exception if source code cannot be generated
*/
public static String wekaStaticWrapper(final Sourcable filter, final String className, final Instances input, final Instances output) throws Exception {
StringBuffer result;
int i;
int n;
result = new StringBuffer();
result.append("// Generated with Weka " + Version.VERSION + "\n");
result.append("//\n");
result.append("// This code is public domain and comes with no warranty.\n");
result.append("//\n");
result.append("// Timestamp: " + new Date() + "\n");
result.append("// Relation: " + input.relationName() + "\n");
result.append("\n");
result.append("package weka.filters;\n");
result.append("\n");
result.append("import weka.core.Attribute;\n");
result.append("import weka.core.Capabilities;\n");
result.append("import weka.core.Capabilities.Capability;\n");
result.append("import weka.core.DenseInstance;\n");
result.append("import weka.core.Instance;\n");
result.append("import weka.core.Instances;\n");
result.append("import weka.core.Utils;\n");
result.append("import weka.filters.Filter;\n");
result.append("import java.util.ArrayList;\n");
result.append("\n");
result.append("public class WekaWrapper\n");
result.append(" extends Filter {\n");
// globalInfo
result.append("\n");
result.append(" /**\n");
result.append(" * Returns only the toString() method.\n");
result.append(" *\n");
result.append(" * @return a string describing the filter\n");
result.append(" */\n");
result.append(" public String globalInfo() {\n");
result.append(" return toString();\n");
result.append(" }\n");
// getCapabilities
result.append("\n");
result.append(" /**\n");
result.append(" * Returns the capabilities of this filter.\n");
result.append(" *\n");
result.append(" * @return the capabilities\n");
result.append(" */\n");
result.append(" public Capabilities getCapabilities() {\n");
result.append(((Filter) filter).getCapabilities().toSource("result", 4));
result.append(" return result;\n");
result.append(" }\n");
// objectsToInstance
result.append("\n");
result.append(" /**\n");
result.append(" * turns array of Objects into an Instance object\n");
result.append(" *\n");
result.append(" * @param obj the Object array to turn into an Instance\n");
result.append(" * @param format the data format to use\n");
result.append(" * @return the generated Instance object\n");
result.append(" */\n");
result.append(" protected Instance objectsToInstance(Object[] obj, Instances format) {\n");
result.append(" Instance result;\n");
result.append(" double[] values;\n");
result.append(" int i;\n");
result.append("\n");
result.append(" values = new double[obj.length];\n");
result.append("\n");
result.append(" for (i = 0 ; i < obj.length; i++) {\n");
result.append(" if (obj[i] == null)\n");
result.append(" values[i] = Utils.missingValue();\n");
result.append(" else if (format.attribute(i).isNumeric())\n");
result.append(" values[i] = (Double) obj[i];\n");
result.append(" else if (format.attribute(i).isNominal())\n");
result.append(" values[i] = format.attribute(i).indexOfValue((String) obj[i]);\n");
result.append(" }\n");
result.append("\n");
result.append(" // create new instance\n");
result.append(" result = new DenseInstance(1.0, values);\n");
result.append(" result.setDataset(format);\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
// instanceToObjects
result.append("\n");
result.append(" /**\n");
result.append(" * turns the Instance object into an array of Objects\n");
result.append(" *\n");
result.append(" * @param inst the instance to turn into an array\n");
result.append(" * @return the Object array representing the instance\n");
result.append(" */\n");
result.append(" protected Object[] instanceToObjects(Instance inst) {\n");
result.append(" Object[] result;\n");
result.append(" int i;\n");
result.append("\n");
result.append(" result = new Object[inst.numAttributes()];\n");
result.append("\n");
result.append(" for (i = 0 ; i < inst.numAttributes(); i++) {\n");
result.append(" if (inst.isMissing(i))\n");
result.append(" result[i] = null;\n");
result.append(" else if (inst.attribute(i).isNumeric())\n");
result.append(" result[i] = inst.value(i);\n");
result.append(" else\n");
result.append(" result[i] = inst.stringValue(i);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
// instancesToObjects
result.append("\n");
result.append(" /**\n");
result.append(" * turns the Instances object into an array of Objects\n");
result.append(" *\n");
result.append(" * @param data the instances to turn into an array\n");
result.append(" * @return the Object array representing the instances\n");
result.append(" */\n");
result.append(" protected Object[][] instancesToObjects(Instances data) {\n");
result.append(" Object[][] result;\n");
result.append(" int i;\n");
result.append("\n");
result.append(" result = new Object[data.numInstances()][];\n");
result.append("\n");
result.append(" for (i = 0; i < data.numInstances(); i++)\n");
result.append(" result[i] = instanceToObjects(data.instance(i));\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
// setInputFormat
result.append("\n");
result.append(" /**\n");
result.append(" * Only tests the input data.\n");
result.append(" *\n");
result.append(" * @param instanceInfo the format of the data to convert\n");
result.append(" * @return always true, to indicate that the output format can \n");
result.append(" * be collected immediately.\n");
result.append(" */\n");
result.append(" public boolean setInputFormat(Instances instanceInfo) throws Exception {\n");
result.append(" super.setInputFormat(instanceInfo);\n");
result.append(" \n");
result.append(" // generate output format\n");
result.append(" ArrayList<Attribute> atts = new ArrayList<Attribute>();\n");
result.append(" ArrayList<String> attValues;\n");
for (i = 0; i < output.numAttributes(); i++) {
result.append(" // " + output.attribute(i).name() + "\n");
if (output.attribute(i).isNumeric()) {
result.append(" atts.add(new Attribute(\"" + output.attribute(i).name() + "\"));\n");
} else if (output.attribute(i).isNominal()) {
result.append(" attValues = new ArrayList<String>();\n");
for (n = 0; n < output.attribute(i).numValues(); n++) {
result.append(" attValues.add(\"" + output.attribute(i).value(n) + "\");\n");
}
result.append(" atts.add(new Attribute(\"" + output.attribute(i).name() + "\", attValues));\n");
} else {
throw new UnsupportedAttributeTypeException("Attribute type '" + output.attribute(i).type() + "' (position " + (i + 1) + ") is not supported!");
}
}
result.append(" \n");
result.append(" Instances format = new Instances(\"" + output.relationName() + "\", atts, 0);\n");
result.append(" format.setClassIndex(" + output.classIndex() + ");\n");
result.append(" setOutputFormat(format);\n");
result.append(" \n");
result.append(" return true;\n");
result.append(" }\n");
// input
result.append("\n");
result.append(" /**\n");
result.append(" * Directly filters the instance.\n");
result.append(" *\n");
result.append(" * @param instance the instance to convert\n");
result.append(" * @return always true, to indicate that the output can \n");
result.append(" * be collected immediately.\n");
result.append(" */\n");
result.append(" public boolean input(Instance instance) throws Exception {\n");
result.append(" Object[] filtered = " + className + ".filter(instanceToObjects(instance));\n");
result.append(" push(objectsToInstance(filtered, getOutputFormat()));\n");
result.append(" return true;\n");
result.append(" }\n");
// batchFinished
result.append("\n");
result.append(" /**\n");
result.append(" * Performs a batch filtering of the buffered data, if any available.\n");
result.append(" *\n");
result.append(" * @return true if instances were filtered otherwise false\n");
result.append(" */\n");
result.append(" public boolean batchFinished() throws Exception {\n");
result.append(" if (getInputFormat() == null)\n");
result.append(" throw new NullPointerException(\"No input instance format defined\");;\n");
result.append("\n");
result.append(" Instances inst = getInputFormat();\n");
result.append(" if (inst.numInstances() > 0) {\n");
result.append(" Object[][] filtered = " + className + ".filter(instancesToObjects(inst));\n");
result.append(" for (int i = 0; i < filtered.length; i++) {\n");
result.append(" push(objectsToInstance(filtered[i], getOutputFormat()));\n");
result.append(" }\n");
result.append(" }\n");
result.append("\n");
result.append(" flushInput();\n");
result.append(" m_NewBatch = true;\n");
result.append(" m_FirstBatchDone = true;\n");
result.append("\n");
result.append(" return (inst.numInstances() > 0);\n");
result.append(" }\n");
// toString
result.append("\n");
result.append(" /**\n");
result.append(" * Returns only the classnames and what filter it is based on.\n");
result.append(" *\n");
result.append(" * @return a short description\n");
result.append(" */\n");
result.append(" public String toString() {\n");
result.append(" return \"Auto-generated filter wrapper, based on " + filter.getClass().getName() + " (generated with Weka " + Version.VERSION + ").\\n" + "\" + this.getClass().getName() + \"/" + className + "\";\n");
result.append(" }\n");
// main
result.append("\n");
result.append(" /**\n");
result.append(" * Runs the filter from commandline.\n");
result.append(" *\n");
result.append(" * @param args the commandline arguments\n");
result.append(" */\n");
result.append(" public static void main(String args[]) {\n");
result.append(" runFilter(new WekaWrapper(), args);\n");
result.append(" }\n");
result.append("}\n");
// actual filter code
result.append("\n");
result.append(filter.toSource(className, input));
return result.toString();
}
/**
* Method for testing filters.
*
* @param filter the filter to use
* @param options should contain the following arguments: <br/>
* -i input_file <br/>
* -o output_file <br/>
* -c class_index <br/>
* -z classname (for filters implementing weka.filters.Sourcable)
* <br/>
* -decimal num (the number of decimal places to use in the output;
* default = 6) <br/>
* or -h for help on options
* @throws Exception if something goes wrong or the user requests help on
* command options
*/
public static void filterFile(final Filter filter, final String[] options) throws Exception {
boolean debug = false;
Instances data = null;
DataSource input = null;
PrintWriter output = null;
boolean helpRequest;
String sourceCode = "";
int maxDecimalPlaces = 6;
try {
helpRequest = Utils.getFlag('h', options);
if (Utils.getFlag('d', options)) {
debug = true;
}
String infileName = Utils.getOption('i', options);
String outfileName = Utils.getOption('o', options);
String classIndex = Utils.getOption('c', options);
if (filter instanceof Sourcable) {
sourceCode = Utils.getOption('z', options);
}
String tmpStr = Utils.getOption("decimal", options);
if (tmpStr.length() > 0) {
maxDecimalPlaces = Integer.parseInt(tmpStr);
}
if (filter instanceof OptionHandler) {
((OptionHandler) filter).setOptions(options);
}
Utils.checkForRemainingOptions(options);
if (helpRequest) {
throw new Exception("Help requested.\n");
}
if (infileName.length() != 0) {
input = new DataSource(infileName);
} else {
input = new DataSource(System.in);
}
if (outfileName.length() != 0) {
output = new PrintWriter(new FileOutputStream(outfileName));
} else {
output = new PrintWriter(System.out);
}
data = input.getStructure();
if (classIndex.length() != 0) {
if (classIndex.equals("first")) {
data.setClassIndex(0);
} else if (classIndex.equals("last")) {
data.setClassIndex(data.numAttributes() - 1);
} else {
data.setClassIndex(Integer.parseInt(classIndex) - 1);
}
}
} catch (Exception ex) {
String filterOptions = "";
// Output the error and also the valid options
if (filter instanceof OptionHandler) {
filterOptions += "\nFilter options:\n\n";
Enumeration<Option> enu = ((OptionHandler) filter).listOptions();
while (enu.hasMoreElements()) {
Option option = enu.nextElement();
filterOptions += option.synopsis() + '\n' + option.description() + "\n";
}
}
String genericOptions = "\nGeneral options:\n\n" + "-h\n" + "\tGet help on available options.\n" + "\t(use -b -h for help on batch mode.)\n" + "-i <file>\n" + "\tThe name of the file containing input instances.\n"
+ "\tIf not supplied then instances will be read from stdin.\n" + "-o <file>\n" + "\tThe name of the file output instances will be written to.\n" + "\tIf not supplied then instances will be written to stdout.\n"
+ "-c <class index>\n" + "\tThe number of the attribute to use as the class.\n" + "\t\"first\" and \"last\" are also valid entries.\n" + "\tIf not supplied then no class is assigned.\n" + "-decimal <integer>\n"
+ "\tThe maximum number of digits to print after the decimal\n" + "\tplace for numeric values (default: 6)\n";
if (filter instanceof Sourcable) {
genericOptions += "-z <class name>\n" + "\tOutputs the source code representing the trained filter.\n";
}
throw new Exception('\n' + ex.getMessage() + filterOptions + genericOptions);
}
if (debug) {
System.err.println("Setting input format");
}
boolean printedHeader = false;
if (filter.setInputFormat(data)) {
if (debug) {
System.err.println("Getting output format");
}
output.println(filter.getOutputFormat().toString());
printedHeader = true;
}
// Pass all the instances to the filter
Instance inst;
while (input.hasMoreElements(data)) {
inst = input.nextElement(data);
if (debug) {
System.err.println("Input instance to filter");
}
if (filter.input(inst)) {
if (debug) {
System.err.println("Filter said collect immediately");
}
if (!printedHeader) {
throw new Error("Filter didn't return true from setInputFormat() " + "earlier!");
}
if (debug) {
System.err.println("Getting output instance");
}
output.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
}
}
// Say that input has finished, and print any pending output instances
if (debug) {
System.err.println("Setting end of batch");
}
if (filter.batchFinished()) {
if (debug) {
System.err.println("Filter said collect output");
}
if (!printedHeader) {
if (debug) {
System.err.println("Getting output format");
}
output.println(filter.getOutputFormat().toString());
}
if (debug) {
System.err.println("Getting output instance");
}
while (filter.numPendingOutput() > 0) {
output.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
if (debug) {
System.err.println("Getting output instance");
}
}
}
if (debug) {
System.err.println("Done");
}
if (output != null) {
output.close();
}
if (sourceCode.length() != 0) {
System.out.println(wekaStaticWrapper((Sourcable) filter, sourceCode, data, filter.getOutputFormat()));
}
}
/**
* Method for testing filters ability to process multiple batches.
*
* @param filter the filter to use
* @param options should contain the following arguments: <br/>
* -i (first) input file <br/>
* -o (first) output file <br/>
* -r (second) input file <br/>
* -s (second) output file <br/>
* -c class_index <br/>
* -z classname (for filters implementing weka.filters.Sourcable)
* <br/>
* -decimal num (the number of decimal places to use in the output;
* default = 6) <br/>
* or -h for help on options
* @throws Exception if something goes wrong or the user requests help on
* command options
*/
public static void batchFilterFile(final Filter filter, final String[] options) throws Exception {
Instances firstData = null;
Instances secondData = null;
DataSource firstInput = null;
DataSource secondInput = null;
PrintWriter firstOutput = null;
PrintWriter secondOutput = null;
boolean helpRequest;
String sourceCode = "";
int maxDecimalPlaces = 6;
try {
helpRequest = Utils.getFlag('h', options);
String fileName = Utils.getOption('i', options);
if (fileName.length() != 0) {
firstInput = new DataSource(fileName);
} else {
throw new Exception("No first input file given.\n");
}
fileName = Utils.getOption('r', options);
if (fileName.length() != 0) {
secondInput = new DataSource(fileName);
} else {
throw new Exception("No second input file given.\n");
}
fileName = Utils.getOption('o', options);
if (fileName.length() != 0) {
firstOutput = new PrintWriter(new FileOutputStream(fileName));
} else {
firstOutput = new PrintWriter(System.out);
}
fileName = Utils.getOption('s', options);
if (fileName.length() != 0) {
secondOutput = new PrintWriter(new FileOutputStream(fileName));
} else {
secondOutput = new PrintWriter(System.out);
}
String classIndex = Utils.getOption('c', options);
if (filter instanceof Sourcable) {
sourceCode = Utils.getOption('z', options);
}
String tmpStr = Utils.getOption("decimal", options);
if (tmpStr.length() > 0) {
maxDecimalPlaces = Integer.parseInt(tmpStr);
}
if (filter instanceof OptionHandler) {
((OptionHandler) filter).setOptions(options);
}
Utils.checkForRemainingOptions(options);
if (helpRequest) {
throw new Exception("Help requested.\n");
}
firstData = firstInput.getStructure();
secondData = secondInput.getStructure();
if (!secondData.equalHeaders(firstData)) {
throw new Exception("Input file formats differ.\n" + secondData.equalHeadersMsg(firstData) + "\n");
}
if (classIndex.length() != 0) {
if (classIndex.equals("first")) {
firstData.setClassIndex(0);
secondData.setClassIndex(0);
} else if (classIndex.equals("last")) {
firstData.setClassIndex(firstData.numAttributes() - 1);
secondData.setClassIndex(secondData.numAttributes() - 1);
} else {
firstData.setClassIndex(Integer.parseInt(classIndex) - 1);
secondData.setClassIndex(Integer.parseInt(classIndex) - 1);
}
}
} catch (Exception ex) {
String filterOptions = "";
// Output the error and also the valid options
if (filter instanceof OptionHandler) {
filterOptions += "\nFilter options:\n\n";
Enumeration<Option> enu = ((OptionHandler) filter).listOptions();
while (enu.hasMoreElements()) {
Option option = enu.nextElement();
filterOptions += option.synopsis() + '\n' + option.description() + "\n";
}
}
String genericOptions = "\nGeneral options:\n\n" + "-h\n" + "\tGet help on available options.\n" + "-i <filename>\n" + "\tThe file containing first input instances.\n" + "-o <filename>\n"
+ "\tThe file first output instances will be written to.\n" + "-r <filename>\n" + "\tThe file containing second input instances.\n" + "-s <filename>\n" + "\tThe file second output instances will be written to.\n"
+ "-c <class index>\n" + "\tThe number of the attribute to use as the class.\n" + "\t\"first\" and \"last\" are also valid entries.\n" + "\tIf not supplied then no class is assigned.\n" + "-decimal <integer>\n"
+ "\tThe maximum number of digits to print after the decimal\n" + "\tplace for numeric values (default: 6)\n";
if (filter instanceof Sourcable) {
genericOptions += "-z <class name>\n" + "\tOutputs the source code representing the trained filter.\n";
}
throw new Exception('\n' + ex.getMessage() + filterOptions + genericOptions);
}
boolean printedHeader = false;
if (filter.setInputFormat(firstData)) {
firstOutput.println(filter.getOutputFormat().toString());
printedHeader = true;
}
// Pass all the instances to the filter
Instance inst;
while (firstInput.hasMoreElements(firstData)) {
inst = firstInput.nextElement(firstData);
if (filter.input(inst)) {
if (!printedHeader) {
throw new Error("Filter didn't return true from setInputFormat() " + "earlier!");
}
firstOutput.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
}
}
// Say that input has finished, and print any pending output instances
if (filter.batchFinished()) {
if (!printedHeader) {
firstOutput.println(filter.getOutputFormat().toString());
}
while (filter.numPendingOutput() > 0) {
firstOutput.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
}
}
if (firstOutput != null) {
firstOutput.close();
}
printedHeader = false;
if (filter.isOutputFormatDefined()) {
secondOutput.println(filter.getOutputFormat().toString());
printedHeader = true;
}
// Pass all the second instances to the filter
while (secondInput.hasMoreElements(secondData)) {
inst = secondInput.nextElement(secondData);
if (filter.input(inst)) {
if (!printedHeader) {
throw new Error("Filter didn't return true from" + " isOutputFormatDefined() earlier!");
}
secondOutput.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
}
}
// Say that input has finished, and print any pending output instances
if (filter.batchFinished()) {
if (!printedHeader) {
secondOutput.println(filter.getOutputFormat().toString());
}
while (filter.numPendingOutput() > 0) {
secondOutput.println(filter.output().toStringMaxDecimalDigits(maxDecimalPlaces));
}
}
if (secondOutput != null) {
secondOutput.close();
}
if (sourceCode.length() != 0) {
System.out.println(wekaStaticWrapper((Sourcable) filter, sourceCode, firstData, filter.getOutputFormat()));
}
}
/**
* runs the filter instance with the given options.
*
* @param filter the filter to run
* @param options the commandline options
*/
public static void runFilter(final Filter filter, final String[] options) {
try {
filter.preExecution();
if (Utils.getFlag('b', options)) {
Filter.batchFilterFile(filter, options);
} else {
Filter.filterFile(filter, options);
}
} catch (Exception e) {
if ((e.toString().indexOf("Help requested") == -1) && (e.toString().indexOf("Filter options") == -1)) {
e.printStackTrace();
} else {
System.err.println(e.getMessage());
}
}
try {
filter.postExecution();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = Option.listOptionsForClassHierarchy(this.getClass(), Filter.class);
newVector.addElement(new Option("\tIf set, filter is run in debug mode and\n" + "\tmay output additional info to the console", "output-debug-info", 0, "-output-debug-info"));
newVector.addElement(new Option("\tIf set, filter capabilities are not checked before filter is built\n" + "\t(use with caution).", "-do-not-check-capabilities", 0, "-do-not-check-capabilities"));
return newVector.elements();
}
/**
* Parses a given list of options. Valid options are:
* <p>
*
* -D <br>
* If set, filter is run in debug mode and may output additional info to the
* console.
* <p>
*
* -do-not-check-capabilities <br>
* If set, filter capabilities are not checked before filter is built (use
* with caution).
* <p>
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
Option.setOptionsForHierarchy(options, this, Filter.class);
this.setDebug(Utils.getFlag("output-debug-info", options));
this.setDoNotCheckCapabilities(Utils.getFlag("do-not-check-capabilities", options));
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
for (String s : Option.getOptionsForHierarchy(this, Filter.class)) {
options.add(s);
}
if (this.getDebug()) {
options.add("-output-debug-info");
}
if (this.getDoNotCheckCapabilities()) {
options.add("-do-not-check-capabilities");
}
return options.toArray(new String[0]);
}
/**
* Set debugging mode.
*
* @param debug true if debug output should be printed
*/
public void setDebug(final boolean debug) {
this.m_Debug = debug;
}
/**
* Get whether debugging is turned on.
*
* @return true if debugging output is on
*/
public boolean getDebug() {
return this.m_Debug;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String debugTipText() {
return "If set to true, filter may output additional info to " + "the console.";
}
/**
* Set whether not to check capabilities.
*
* @param doNotCheckCapabilities true if capabilities are not to be checked.
*/
@Override
public void setDoNotCheckCapabilities(final boolean doNotCheckCapabilities) {
this.m_DoNotCheckCapabilities = doNotCheckCapabilities;
}
/**
* Get whether capabilities checking is turned off.
*
* @return true if capabilities checking is turned off.
*/
@Override
public boolean getDoNotCheckCapabilities() {
return this.m_DoNotCheckCapabilities;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String doNotCheckCapabilitiesTipText() {
return "If set, the filter's capabilities are not checked before it is built." + " (Use with caution to reduce runtime.)";
}
/**
* Perform any setup stuff that might need to happen before commandline
* execution. Subclasses should override if they need to do something here
*
* @throws Exception if a problem occurs during setup
*/
@Override
public void preExecution() throws Exception {
}
/**
* Execute the supplied object.
*
* @param toRun the object to execute
* @param options any options to pass to the object
* @throws Exception if the object is not of the expected type.
*/
@Override
public void run(final Object toRun, final String[] options) throws Exception {
if (!(toRun instanceof Filter)) {
throw new IllegalArgumentException("Object to run is not a Filter!");
}
runFilter((Filter) toRun, options);
}
/**
* Perform any teardown stuff that might need to happen after execution.
* Subclasses should override if they need to do something here
*
* @throws Exception if a problem occurs during teardown
*/
@Override
public void postExecution() throws Exception {
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(final String[] args) {
try {
if (args.length == 0) {
throw new Exception("First argument must be the class name of a Filter");
}
String fname = args[0];
Filter f = (Filter) Class.forName(fname).newInstance();
args[0] = "";
runFilter(f, args);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/MultiFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MultiFilter.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
/**
* <!-- globalinfo-start --> Applies several filters successively. In case all
* supplied filters are StreamableFilters, it will act as a streamable one, too.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -F <classname [options]>
* A filter to apply (can be specified multiple times).
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see weka.filters.StreamableFilter
*/
public class MultiFilter extends SimpleStreamFilter implements WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -6293720886005713120L;
/** The filters */
protected Filter m_Filters[] = { new AllFilter() };
/** caches the streamable state */
protected boolean m_Streamable = false;
/** whether we already checked the streamable state */
protected boolean m_StreamableChecked = false;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Applies several filters successively. In case all supplied filters "
+ "are StreamableFilters, it will act as a streamable one, too.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tA filter to apply (can be specified multiple times).", "F", 1,
"-F <classname [options]>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -F <classname [options]>
* A filter to apply (can be specified multiple times).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
String filter;
String[] options2;
Vector<Filter> filters;
super.setOptions(options);
filters = new Vector<Filter>();
while ((tmpStr = Utils.getOption("F", options)).length() != 0) {
options2 = Utils.splitOptions(tmpStr);
filter = options2[0];
options2[0] = "";
filters.add((Filter) Utils.forName(Filter.class, filter, options2));
}
// at least one filter
if (filters.size() == 0) {
filters.add(new AllFilter());
}
setFilters(filters.toArray(new Filter[filters.size()]));
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
String[] options;
int i;
result = new Vector<String>();
options = super.getOptions();
for (i = 0; i < options.length; i++) {
result.add(options[i]);
}
for (i = 0; i < getFilters().length; i++) {
result.add("-F");
result.add(getFilterSpec(getFilter(i)));
}
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
if (getFilters().length == 0) {
Capabilities result = super.getCapabilities();
result.disableAll();
return result;
} else {
return getFilters()[0].getCapabilities();
}
}
/**
* resets the filter, i.e., m_NewBatch to true and m_FirstBatchDone to false.
*
* @see #m_NewBatch
* @see #m_FirstBatchDone
*/
@Override
protected void reset() {
super.reset();
m_StreamableChecked = false;
}
/**
* Sets the list of possible filters to choose from. Also resets the state of
* the filter (this reset doesn't affect the options).
*
* @param filters an array of filters with all options set.
* @see #reset()
*/
public void setFilters(Filter[] filters) {
m_Filters = filters;
reset();
}
/**
* Gets the list of possible filters to choose from.
*
* @return the array of Filters
*/
public Filter[] getFilters() {
return m_Filters;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String filtersTipText() {
return "The base filters to be used.";
}
/**
* Gets a single filter from the set of available filters.
*
* @param index the index of the filter wanted
* @return the Filter
*/
public Filter getFilter(int index) {
return m_Filters[index];
}
/**
* returns the filter classname and the options as one string
*
* @param filter the filter to get the specs for
* @return the classname plus options
*/
protected String getFilterSpec(Filter filter) {
String result;
if (filter == null) {
result = "";
} else {
result = filter.getClass().getName();
if (filter instanceof OptionHandler) {
result += " "
+ Utils.joinOptions(((OptionHandler) filter).getOptions());
}
}
return result;
}
/**
* tests whether all the enclosed filters are streamable
*
* @return true if all the enclosed filters are streamable
*/
public boolean isStreamableFilter() {
int i;
if (!m_StreamableChecked) {
m_Streamable = true;
m_StreamableChecked = true;
for (i = 0; i < getFilters().length; i++) {
if (getFilter(i) instanceof MultiFilter) {
m_Streamable = ((MultiFilter) getFilter(i)).isStreamableFilter();
} else if (getFilter(i) instanceof StreamableFilter) {
m_Streamable = true;
} else {
m_Streamable = false;
}
if (!m_Streamable) {
break;
}
}
if (getDebug()) {
System.out.println("Streamable: " + m_Streamable);
}
}
return m_Streamable;
}
/**
* Returns true if the output format is immediately available after the input
* format has been set and not only after all the data has been seen (see
* batchFinished()). This method should normally return true for a stream
* filter, since the data will be processed in a batch manner instead (or at
* least for the second batch of files, see m_FirstBatchDone).
*
* @return true if the output format is immediately available
* @see #batchFinished()
* @see #setInputFormat(Instances)
* @see #m_FirstBatchDone
*/
@Override
protected boolean hasImmediateOutputFormat() {
return isStreamableFilter();
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
* @see #preprocess(Instances)
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
int i;
result = getInputFormat();
for (i = 0; i < getFilters().length; i++) {
if (!isFirstBatchDone()) {
getFilter(i).setInputFormat(result);
}
result = getFilter(i).getOutputFormat();
}
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
Instance result;
int i;
result = (Instance) instance.copy();
for (i = 0; i < getFilters().length; i++) {
if (getFilter(i).input(result)) {
result = getFilter(i).output();
} else {
// if a filter says nothing to collect then terminate
result = null;
break;
}
}
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished(). This
* implementation only calls process(Instance) for each instance in the given
* dataset.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
* @see #process(Instance)
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result;
int i;
result = instances;
for (i = 0; i < getFilters().length; i++) {
if (!isFirstBatchDone()) {
getFilter(i).setInputFormat(result);
}
result = Filter.useFilter(result, getFilter(i));
}
return result;
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* setInputFormat has been re-assigned or new options have been set).
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input format has been set.
*/
@Override
public boolean batchFinished() throws Exception {
super.batchFinished();
for (int i = 0; i > getFilters().length; i++) {
getFilter(i).batchFinished();
}
return (numPendingOutput() != 0);
}
/**
* RemoveWithValues may return false from input() (thus not making an instance
* available immediately) even after the first batch has been completed due to
* matching a value that the user wants to remove. Therefore this method
* returns true.
*
* @return true if one of the base filters returns true for this method.
*/
@Override
public boolean mayRemoveInstanceAfterFirstBatchDone() {
boolean result = false;
for (Filter f : m_Filters) {
result = (result || f.mayRemoveInstanceAfterFirstBatchDone());
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for executing this class.
*
* @param args should contain arguments for the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new MultiFilter(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/RenameRelation.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RenameRelation.java
* Copyright (C) 2006-2017 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import weka.core.*;
import java.util.regex.Pattern;
/**
* A simple filter that allows the relation name of a set of instances to be
* altered in various ways.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class RenameRelation extends Filter
implements StreamableFilter, WeightedAttributesHandler, WeightedInstancesHandler {
private static final long serialVersionUID = 8082179220141937043L;
/** Text to modify the relation name with */
protected String m_relationNameModText = "change me";
/** The type of modification to make */
protected ModType m_modType = ModType.REPLACE;
/** Pattern for regex replacement */
protected Pattern m_regexPattern;
/** Regex string to match */
protected String m_regexMatch = "([\\s\\S]+)";
/** Whether to replace all rexex matches, or just the first */
protected boolean m_replaceAll;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that allows the relation name of a set of instances to be "
+ "altered.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capabilities.Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
/**
* Set the modification text to apply
*
* @param text the text to apply
*/
@OptionMetadata(displayName = "Text to use",
description = "The text to modify the relation name with",
commandLineParamName = "modify",
commandLineParamSynopsis = "-modify <string>", displayOrder = 0)
public void setModificationText(String text) {
m_relationNameModText = text;
}
/**
* Get the modification text to apply
*
* @return the modification text
*/
public String getModificationText() {
return m_relationNameModText;
}
/**
* Set the modification type to apply
*
* @param mod the modification type to apply
*/
@OptionMetadata(
displayName = "Relation name modification type",
description = "The type of modification to apply (default = REPLACE)",
commandLineParamName = "mod-type",
commandLineParamSynopsis = "-mod-type <REPLACE | PREPEND | APPEND | REGEX>",
displayOrder = 1)
public
void setModType(ModType mod) {
m_modType = mod;
}
/**
* Get the modification type to apply
*
* @return the modification type to apply
*/
public ModType getModType() {
return m_modType;
}
/**
* Set the match string for regex modifications
*
* @param match the regular expression to apply for matching
*/
@OptionMetadata(displayName = "Regular expression",
description = "Regular expression to use for matching when performing a "
+ "REGEX modification (default = ([\\s\\S]+))",
commandLineParamName = "find",
commandLineParamSynopsis = "-find <pattern>", displayOrder = 2)
public void setRegexMatch(String match) {
m_regexMatch = match;
}
/**
* Get the match string for regex modifications
*
* @return the regular expression to apply for matching
*/
public String getRegexMatch() {
return m_regexMatch;
}
/**
* Set whether to replace all regular expression matches, or just the first.
*
* @param replaceAll true to replace all regex matches
*/
@OptionMetadata(displayName = "Replace all regex matches",
description = "Replace all matching occurrences if set to true, or just "
+ "the first match if set to false",
commandLineParamName = "replace-all",
commandLineParamSynopsis = "-replace-all", commandLineParamIsFlag = true,
displayOrder = 3)
public void setReplaceAll(boolean replaceAll) {
m_replaceAll = replaceAll;
}
/**
* Get whether to replace all regular expression matches, or just the first.
*
* @return true to replace all regex matches
*/
public boolean getReplaceAll() {
return m_replaceAll;
}
/**
* 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 something goes wrong
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
// alter the relation name on output format
if (m_modType == ModType.REGEX && m_relationNameModText != null
&& m_relationNameModText.length() > 0 && m_regexMatch != null
&& m_regexMatch.length() > 0) {
m_regexPattern = Pattern.compile(m_regexMatch);
}
applyRelationNameChange(outputFormatPeek());
return true;
}
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (instance.dataset() == null) {
push((Instance) instance.copy());
} else {
push(instance); // push() will make a copy anyway.
}
return true;
}
/**
* Apply the change to the relation name in the given Instances object
*
* @param insts the Instances object to operate on
*/
protected void applyRelationNameChange(Instances insts) {
switch (m_modType) {
case REPLACE:
insts.setRelationName(m_relationNameModText);
break;
case APPEND:
insts.setRelationName(getInputFormat().relationName() + m_relationNameModText);
break;
case PREPEND:
insts.setRelationName(m_relationNameModText + getInputFormat().relationName());
break;
case REGEX:
String rel = getInputFormat().relationName();
if (m_replaceAll) {
rel = m_regexPattern.matcher(rel).replaceAll(m_relationNameModText);
} else {
rel = m_regexPattern.matcher(rel).replaceFirst(m_relationNameModText);
}
insts.setRelationName(rel);
break;
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: $");
}
/**
* Enum of modification types
*/
protected enum ModType {
REPLACE, PREPEND, APPEND, REGEX;
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RenameRelation(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/SimpleBatchFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SimpleBatchFilter.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import weka.core.Instance;
import weka.core.Instances;
/**
* This filter is a superclass for simple batch filters.
* <p/>
*
* <b>General notes:</b><br/>
* <ul>
* <li>After adding instances to the filter via input(Instance) one always has
* to call batchFinished() to make them available via output().</li>
* <li>After the first call of batchFinished() the field m_FirstBatchDone is set
* to <code>true</code>.</li>
* </ul>
* <p/>
*
* <b>Example:</b><br/>
* The following code snippet uses the filter <code>SomeFilter</code> on a
* dataset that is loaded from <code>filename</code>.
*
* <pre>
* import weka.core.*;
* import weka.filters.*;
* import java.io.*;
* ...
* SomeFilter filter = new SomeFilter();
* // set necessary options for the filter
* Instances data = new Instances(
* new BufferedReader(
* new FileReader(filename)));
* Instances filteredData = Filter.useFilter(data, filter);
* </pre>
*
* <b>Implementation:</b><br/>
* Only the following abstract methods need to be implemented:
* <ul>
* <li>globalInfo()</li>
* <li>determineOutputFormat(Instances)</li>
* <li>process(Instances)</li>
* </ul>
* <br/>
* And the <b>getCapabilities()</b> method must return what kind of attributes
* and classes the filter can handle.
* <p/>
*
* If more options are necessary, then the following methods need to be
* overriden:
* <ul>
* <li>listOptions()</li>
* <li>setOptions(String[])</li>
* <li>getOptions()</li>
* </ul>
* <p/>
*
* To make the filter available from commandline one must add the following main
* method for correct execution (<Filtername> must be replaced with the
* actual filter classname):
*
* <pre>
* public static void main(String[] args) {
* runFilter(new <Filtername>(), args);
* }
* </pre>
* <p/>
*
* <b>Example implementation:</b><br/>
*
* <pre>
* import weka.core.*;
* import weka.core.Capabilities.*;
* import weka.filters.*;
*
* public class SimpleBatch extends SimpleBatchFilter {
*
* public String globalInfo() {
* return "A simple batch filter that adds an additional attribute 'bla' at the end containing the index of the processed instance.";
* }
*
* public Capabilities getCapabilities() {
* Capabilities result = super.getCapabilities();
* result.enableAllAttributes();
* result.enableAllClasses();
* result.enable(Capability.NO_CLASS); // filter doesn't need class to be set
* return result;
* }
*
* protected Instances determineOutputFormat(Instances inputFormat) {
* Instances result = new Instances(inputFormat, 0);
* result.insertAttributeAt(new Attribute("bla"), result.numAttributes());
* return result;
* }
*
* protected Instances process(Instances inst) {
* Instances result = new Instances(determineOutputFormat(inst), 0);
* for (int i = 0; i < inst.numInstances(); i++) {
* double[] values = new double[result.numAttributes()];
* for (int n = 0; n < inst.numAttributes(); n++)
* values[n] = inst.instance(i).value(n);
* values[values.length - 1] = i;
* result.add(new DenseInstance(1, values));
* }
* return result;
* }
*
* public static void main(String[] args) {
* runFilter(new SimpleBatch(), args);
* }
* }
*
* </pre>
* <p/>
*
* <b>Options:</b><br/>
* Valid filter-specific options are:
* <p/>
*
* -D <br/>
* Turns on output of debugging information.
* <p/>
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see SimpleStreamFilter
* @see #input(Instance)
* @see #batchFinished()
* @see #m_FirstBatchDone
*/
public abstract class SimpleBatchFilter extends SimpleFilter {
/** for serialization */
private static final long serialVersionUID = 8102908673378055114L;
/**
* returns true if the output format is immediately available after the input
* format has been set and not only after all the data has been seen (see
* batchFinished())
*
* @return true if the output format is immediately available
* @see #batchFinished()
* @see #setInputFormat(Instances)
*/
@Override
protected boolean hasImmediateOutputFormat() {
return false;
}
/**
* Returns whether to allow the determineOutputFormat(Instances) method access
* to the full dataset rather than just the header.
* <p/>
* Default implementation returns false.
*
* @return whether determineOutputFormat has access to the full input dataset
*/
public boolean allowAccessToFullInputFormat() {
return false;
}
/**
* Input an instance for filtering. Filter requires all training instances be
* read before producing output (calling the method batchFinished() makes the
* data available). If this instance is part of a new batch, m_NewBatch is set
* to false.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input structure has been defined
* @throws Exception if something goes wrong
* @see #batchFinished()
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
bufferInput(instance); // bufferInput() makes a copy of the instance.
if (isFirstBatchDone()) {
Instances inst = new Instances(getInputFormat());
inst = process(inst);
for (int i = 0; i < inst.numInstances(); i++) {
push(inst.instance(i), false); // No need to copy instance
}
flushInput();
}
return m_FirstBatchDone;
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* setInputFormat has been re-assigned or new options have been set). Sets
* m_FirstBatchDone and m_NewBatch to true.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input format has been set.
* @throws Exception if something goes wrong
* @see #m_NewBatch
* @see #m_FirstBatchDone
*/
@Override
public boolean batchFinished() throws Exception {
int i;
Instances inst;
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
// get data
inst = new Instances(getInputFormat());
// if output format hasn't been set yet, do it now
if (!hasImmediateOutputFormat() && !isFirstBatchDone()) {
if (allowAccessToFullInputFormat()) {
setOutputFormat(determineOutputFormat(inst));
} else {
setOutputFormat(determineOutputFormat(new Instances(inst, 0)));
}
}
// don't do anything in case there are no instances pending.
// in case of second batch, they may have already been processed
// directly by the input method and added to the output queue
if (inst.numInstances() > 0) {
// process data
inst = process(inst);
// clear input queue
flushInput();
// move it to the output
for (i = 0; i < inst.numInstances(); i++) {
push(inst.instance(i), false); // No need to copy instance
}
}
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/SimpleFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SimpleFilter.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Utils;
/**
* This filter contains common behavior of the SimpleBatchFilter and the
* SimpleStreamFilter.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see SimpleBatchFilter
* @see SimpleStreamFilter
*/
public abstract class SimpleFilter extends Filter {
/** for serialization */
private static final long serialVersionUID = 5702974949137433141L;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public abstract String globalInfo();
/**
* resets the filter, i.e., m_NewBatch to true and m_FirstBatchDone to false.
*
* @see #m_NewBatch
* @see #m_FirstBatchDone
*/
protected void reset() {
m_NewBatch = true;
m_FirstBatchDone = false;
}
/**
* returns true if the output format is immediately available after the input
* format has been set and not only after all the data has been seen (see
* batchFinished())
*
* @return true if the output format is immediately available
* @see #batchFinished()
* @see #setInputFormat(Instances)
*/
protected abstract boolean hasImmediateOutputFormat();
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
protected abstract Instances determineOutputFormat(Instances inputFormat)
throws Exception;
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
protected abstract Instances process(Instances instances) throws Exception;
/**
* Sets the format of the input instances. Also resets the state of the filter
* (this reset doesn't affect the options).
*
* @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
* @see #reset()
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
reset();
if (hasImmediateOutputFormat()) {
setOutputFormat(determineOutputFormat(instanceInfo));
}
return hasImmediateOutputFormat();
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/SimpleStreamFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SimpleStreamFilter.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import weka.core.Instance;
import weka.core.Instances;
/**
* This filter is a superclass for simple stream filters.
* <p/>
* <p/>
*
* <b>General notes:</b><br/>
* <ul>
* <li>After the first call of batchFinished() the field m_FirstBatchDone is set
* to <code>true</code>.</li>
* </ul>
* <p/>
*
* <b>Example:</b><br/>
* The following code snippet uses the filter <code>SomeFilter</code> on a
* dataset that is loaded from <code>filename</code>.
*
* <pre>
* import weka.core.*;
* import weka.filters.*;
* import java.io.*;
* ...
* SomeFilter filter = new SomeFilter();
* // set necessary options for the filter
* Instances data = new Instances(
* new BufferedReader(
* new FileReader(filename)));
* Instances filteredData = Filter.useFilter(data, filter);
* </pre>
*
* <b>Implementation:</b><br/>
* Only the following abstract methods need to be implemented:
* <ul>
* <li>globalInfo()</li>
* <li>determineOutputFormat(Instances)</li>
* <li>process(Instance)</li>
* </ul>
* <br/>
* And the <b>getCapabilities()</b> method must return what kind of attributes
* and classes the filter can handle.
* <p/>
*
* If more options are necessary, then the following methods need to be
* overriden:
* <ul>
* <li>listOptions()</li>
* <li>setOptions(String[])</li>
* <li>getOptions()</li>
* </ul>
* <p/>
*
* To make the filter available from commandline one must add the following main
* method for correct execution (<Filtername> must be replaced with the
* actual filter classname):
*
* <pre>
* public static void main(String[] args) {
* runFilter(new <Filtername>(), args);
* }
* </pre>
* <p/>
*
* <b>Example implementation:</b><br/>
*
* <pre>
* import weka.core.*;
* import weka.core.Capabilities.*;
* import weka.filters.*;
*
* import java.util.Random;
*
* public class SimpleStream extends SimpleStreamFilter {
*
* public String globalInfo() {
* return "A simple stream filter that adds an attribute 'bla' at the end containing a random number.";
* }
*
* public Capabilities getCapabilities() {
* Capabilities result = super.getCapabilities();
* result.enableAllAttributes();
* result.enableAllClasses();
* result.enable(Capability.NO_CLASS); // filter doesn't need class to be set
* return result;
* }
*
* protected Instances determineOutputFormat(Instances inputFormat) {
* Instances result = new Instances(inputFormat, 0);
* result.insertAttributeAt(new Attribute("bla"), result.numAttributes());
* return result;
* }
*
* protected Instance process(Instance inst) {
* double[] values = new double[inst.numAttributes() + 1];
* for (int n = 0; n < inst.numAttributes(); n++)
* values[n] = inst.value(n);
* values[values.length - 1] = new Random().nextInt();
* Instance result = new DenseInstance(1, values);
* return result;
* }
*
* public static void main(String[] args) {
* runFilter(new SimpleStream(), args);
* }
* }
*
* </pre>
* <p/>
*
* <b>Options:</b><br/>
* Valid filter-specific options are:
* <p/>
*
* -D <br/>
* Turns on output of debugging information.
* <p/>
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see SimpleBatchFilter
* @see #input(Instance)
* @see #batchFinished()
* @see #m_FirstBatchDone
*/
public abstract class SimpleStreamFilter extends SimpleFilter implements
StreamableFilter {
/** for serialization */
private static final long serialVersionUID = 2754882676192747091L;
/**
* Returns true if the output format is immediately available after the input
* format has been set and not only after all the data has been seen (see
* batchFinished()). This method should normally return true for a stream
* filter, since the data will be processed in a batch manner instead (or at
* least for the second batch of files, see m_FirstBatchDone).
*
* @return true if the output format is immediately available
* @see #batchFinished()
* @see #setInputFormat(Instances)
* @see #m_FirstBatchDone
*/
@Override
protected boolean hasImmediateOutputFormat() {
return true;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
* @see #preprocess(Instances)
*/
@Override
protected abstract Instances determineOutputFormat(Instances inputFormat)
throws Exception;
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
protected abstract Instance process(Instance instance) throws Exception;
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished(). This
* implementation only calls process(Instance) for each instance in the given
* dataset.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
* @see #process(Instance)
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result;
int i;
result = new Instances(getOutputFormat(), 0);
for (i = 0; i < instances.numInstances(); i++) {
result.add(process(instances.instance(i)));
}
return result;
}
/**
* In case the output format cannot be returned immediately, this method is
* called before the actual processing of the instances. Derived classes can
* implement specific behavior here.
*
* @param instances the instances to work on
* @see #hasImmediateOutputFormat()
* @see #determineOutputFormat(Instances)
*/
protected void preprocess(Instances instances) {
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
* @throws Exception if something goes wrong
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
try {
if (hasImmediateOutputFormat() || isFirstBatchDone()) {
Instance processed = process((Instance) instance.copy());
if (processed != null) {
push(processed, false); // No need to copy instance
return true;
}
return false;
} else {
bufferInput(instance);
return false;
}
} catch (Exception e) {
return false;
}
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* setInputFormat has been re-assigned or new options have been set).
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input format has been set.
*/
@Override
public boolean batchFinished() throws Exception {
int i;
Instances inst;
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
inst = new Instances(getInputFormat());
flushInput();
if (!hasImmediateOutputFormat()) {
preprocess(inst);
}
// process data
inst = process(inst);
// if output format hasn't been set yet, do it now
if (!hasImmediateOutputFormat() && !isFirstBatchDone()) {
setOutputFormat(inst);
}
// move data to the output
for (i = 0; i < inst.numInstances(); i++) {
push(inst.instance(i), false); // No need to copy instance
}
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/Sourcable.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Sourcable.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
import weka.core.Instances;
/**
* Interface for filters that can be converted to Java source.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface Sourcable {
/**
* Returns a string that describes the filter as source. The
* filter will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain two methods with these signatures:
* <pre><code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
public String toSource(String className, Instances data) throws Exception;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/StreamableFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* StreamableFilter.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
/**
* Interface for filters can work with a stream of instances.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface StreamableFilter {
/**
* Empty interface, to be used as a hint of the filters behaviour.
*/
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/SupervisedFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SupervisedFilter.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
/**
* Interface for filters that make use of a class attribute.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface SupervisedFilter {
/**
* Empty interface, to be used as a hint of the filters behaviour.
*/
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/UnsupervisedFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* UnsupervisedFilter.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters;
/**
* Interface for filters that do not need a class attribute.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface UnsupervisedFilter {
/**
* Empty interface, to be used as a hint of the filters behaviour.
*/
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/AddClassification.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddClassification.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.supervised.attribute;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Classifier;
import weka.classifiers.misc.InputMappedClassifier;
import weka.core.*;
import weka.filters.SimpleBatchFilter;
/**
* <!-- globalinfo-start --> A filter for adding the classification, the class
* distribution and an error flag to a dataset with a classifier. The classifier
* is either trained on the data itself or provided as serialized model.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -W <classifier specification>
* Full class name of classifier to use, followed
* by scheme options. eg:
* "weka.classifiers.bayes.NaiveBayes -D"
* (default: weka.classifiers.rules.ZeroR)
* </pre>
*
* <pre>
* -serialized <file>
* Instead of training a classifier on the data, one can also provide
* a serialized model and use that for tagging the data.
* </pre>
*
* <pre>
* -classification
* Adds an attribute with the actual classification.
* (default: off)
* </pre>
*
* <pre>
* -remove-old-class
* Removes the old class attribute.
* (default: off)
* </pre>
*
* <pre>
* -distribution
* Adds attributes with the distribution for all classes
* (for numeric classes this will be identical to the attribute
* output with '-classification').
* (default: off)
* </pre>
*
* <pre>
* -error
* Adds an attribute indicating whether the classifier output
* a wrong classification (for numeric classes this is the numeric
* difference).
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class AddClassification extends SimpleBatchFilter
implements WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization. */
private static final long serialVersionUID = -1931467132568441909L;
/** The classifier template used to do the classification. */
protected Classifier m_Classifier = new weka.classifiers.rules.ZeroR();
/** The file from which to load a serialized classifier. */
protected File m_SerializedClassifierFile = new File(
System.getProperty("user.dir"));
/** The actual classifier used to do the classification. */
protected Classifier m_ActualClassifier = null;
/** the header of the file the serialized classifier was trained with. */
protected Instances m_SerializedHeader = null;
/** whether to output the classification. */
protected boolean m_OutputClassification = false;
/** whether to remove the old class attribute. */
protected boolean m_RemoveOldClass = false;
/** whether to output the class distribution. */
protected boolean m_OutputDistribution = false;
/** whether to output the error flag. */
protected boolean m_OutputErrorFlag = false;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for adding the classification, the class distribution and "
+ "an error flag to a dataset with a classifier. The classifier is "
+ "either trained on the data itself or provided as serialized model.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tFull class name of classifier to use, followed\n"
+ "\tby scheme options. eg:\n"
+ "\t\t\"weka.classifiers.bayes.NaiveBayes -D\"\n"
+ "\t(default: weka.classifiers.rules.ZeroR)", "W", 1,
"-W <classifier specification>"));
result.addElement(new Option(
"\tInstead of training a classifier on the data, one can also provide\n"
+ "\ta serialized model and use that for tagging the data.",
"serialized", 1, "-serialized <file>"));
result.addElement(new Option(
"\tAdds an attribute with the actual classification.\n"
+ "\t(default: off)", "classification", 0, "-classification"));
result.addElement(new Option("\tRemoves the old class attribute.\n"
+ "\t(default: off)", "remove-old-class", 0, "-remove-old-class"));
result.addElement(new Option(
"\tAdds attributes with the distribution for all classes \n"
+ "\t(for numeric classes this will be identical to the attribute \n"
+ "\toutput with '-classification').\n" + "\t(default: off)",
"distribution", 0, "-distribution"));
result
.addElement(new Option(
"\tAdds an attribute indicating whether the classifier output \n"
+ "\ta wrong classification (for numeric classes this is the numeric \n"
+ "\tdifference).\n" + "\t(default: off)", "error", 0, "-error"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses the options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -W <classifier specification>
* Full class name of classifier to use, followed
* by scheme options. eg:
* "weka.classifiers.bayes.NaiveBayes -D"
* (default: weka.classifiers.rules.ZeroR)
* </pre>
*
* <pre>
* -serialized <file>
* Instead of training a classifier on the data, one can also provide
* a serialized model and use that for tagging the data.
* </pre>
*
* <pre>
* -classification
* Adds an attribute with the actual classification.
* (default: off)
* </pre>
*
* <pre>
* -remove-old-class
* Removes the old class attribute.
* (default: off)
* </pre>
*
* <pre>
* -distribution
* Adds attributes with the distribution for all classes
* (for numeric classes this will be identical to the attribute
* output with '-classification').
* (default: off)
* </pre>
*
* <pre>
* -error
* Adds an attribute indicating whether the classifier output
* a wrong classification (for numeric classes this is the numeric
* difference).
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
String[] tmpOptions;
File file;
boolean serializedModel;
setOutputClassification(Utils.getFlag("classification", options));
setRemoveOldClass(Utils.getFlag("remove-old-class", options));
setOutputDistribution(Utils.getFlag("distribution", options));
setOutputErrorFlag(Utils.getFlag("error", options));
serializedModel = false;
tmpStr = Utils.getOption("serialized", options);
if (tmpStr.length() != 0) {
file = new File(tmpStr);
if (!file.exists()) {
throw new FileNotFoundException("File '" + file.getAbsolutePath()
+ "' not found!");
}
if (file.isDirectory()) {
throw new FileNotFoundException("'" + file.getAbsolutePath()
+ "' points to a directory not a file!");
}
setSerializedClassifierFile(file);
serializedModel = true;
} else {
setSerializedClassifierFile(null);
}
if (!serializedModel) {
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() == 0) {
tmpStr = weka.classifiers.rules.ZeroR.class.getName();
}
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length == 0) {
throw new Exception("Invalid classifier specification string");
}
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setClassifier(AbstractClassifier.forName(tmpStr, tmpOptions));
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getOutputClassification()) {
result.add("-classification");
}
if (getRemoveOldClass()) {
result.add("-remove-old-class");
}
if (getOutputDistribution()) {
result.add("-distribution");
}
if (getOutputErrorFlag()) {
result.add("-error");
}
File file = getSerializedClassifierFile();
if ((file != null) && (!file.isDirectory())) {
result.add("-serialized");
result.add(file.getAbsolutePath());
} else {
result.add("-W");
result.add(getClassifierSpec());
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* resets the filter, i.e., m_ActualClassifier to null.
*
* @see #m_ActualClassifier
*/
@Override
protected void reset() {
super.reset();
m_ActualClassifier = null;
m_SerializedHeader = null;
}
/**
* Returns the actual classifier to use, either from the serialized model or
* the one specified by the user.
*
* @return the classifier to use, null in case of an error
*/
protected Classifier getActualClassifier() {
File file;
ObjectInputStream ois;
if (m_ActualClassifier == null) {
try {
file = getSerializedClassifierFile();
if (!file.isDirectory()) {
// ois = new ObjectInputStream(new FileInputStream(file));
ois =
SerializationHelper.getObjectInputStream(new FileInputStream(file));
m_ActualClassifier = (Classifier) ois.readObject();
m_SerializedHeader = null;
// let's see whether there's an Instances header stored as well
try {
m_SerializedHeader = (Instances) ois.readObject();
} catch (Exception e) {
// ignored
m_SerializedHeader = null;
}
ois.close();
} else {
m_ActualClassifier = AbstractClassifier.makeCopy(m_Classifier);
}
} catch (Exception e) {
m_ActualClassifier = null;
System.err.println("Failed to instantiate classifier:");
e.printStackTrace();
}
}
return m_ActualClassifier;
}
/**
* Need to override this to deal with InputMappedClassifier case.
* (If InputMappedClassifier is applied to test data that is different in some important aspects: we
* need to test capabilities with respect to format of data used to train the classifier.)
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
protected void testInputFormat(Instances instanceInfo) throws Exception {
Classifier classifier = getActualClassifier();
if (classifier instanceof InputMappedClassifier) {
Instances trainingData = ((InputMappedClassifier)classifier).getModelHeader(new Instances(instanceInfo, 0));
getCapabilities(trainingData).testWithFail(trainingData);
} else {
getCapabilities(instanceInfo).testWithFail(instanceInfo);
}
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
if (getActualClassifier() == null) {
result = super.getCapabilities();
result.disableAll();
} else {
result = getActualClassifier().getCapabilities();
}
result.setMinimumNumberInstances(0);
return result;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classifierTipText() {
return "The classifier to use for classification.";
}
/**
* Sets the classifier to classify instances with.
*
* @param value The classifier to be used (with its options set).
*/
public void setClassifier(Classifier value) {
m_Classifier = value;
}
/**
* Gets the classifier used by the filter.
*
* @return The classifier to be used.
*/
public Classifier getClassifier() {
return m_Classifier;
}
/**
* Gets the classifier specification string, which contains the class name of
* the classifier and any options to the classifier.
*
* @return the classifier string.
*/
protected String getClassifierSpec() {
String result;
Classifier c;
c = getClassifier();
result = c.getClass().getName();
if (c instanceof OptionHandler) {
result += " " + Utils.joinOptions(((OptionHandler) c).getOptions());
}
return result;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String serializedClassifierFileTipText() {
return "A file containing the serialized model of a trained classifier.";
}
/**
* Gets the file pointing to a serialized, trained classifier. If it is null
* or pointing to a directory it will not be used.
*
* @return the file the serialized, trained classifier is located in
*/
public File getSerializedClassifierFile() {
return m_SerializedClassifierFile;
}
/**
* Sets the file pointing to a serialized, trained classifier. If the argument
* is null, doesn't exist or pointing to a directory, then the value is
* ignored.
*
* @param value the file pointing to the serialized, trained classifier
*/
public void setSerializedClassifierFile(File value) {
if ((value == null) || (!value.exists())) {
value = new File(System.getProperty("user.dir"));
}
m_SerializedClassifierFile = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputClassificationTipText() {
return "Whether to add an attribute with the actual classification.";
}
/**
* Get whether the classifiction of the classifier is output.
*
* @return true if the classification of the classifier is output.
*/
public boolean getOutputClassification() {
return m_OutputClassification;
}
/**
* Set whether the classification of the classifier is output.
*
* @param value whether the classification of the classifier is output.
*/
public void setOutputClassification(boolean value) {
m_OutputClassification = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String removeOldClassTipText() {
return "Whether to remove the old class attribute.";
}
/**
* Get whether the old class attribute is removed.
*
* @return true if the old class attribute is removed.
*/
public boolean getRemoveOldClass() {
return m_RemoveOldClass;
}
/**
* Set whether the old class attribute is removed.
*
* @param value whether the old class attribute is removed.
*/
public void setRemoveOldClass(boolean value) {
m_RemoveOldClass = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputDistributionTipText() {
return "Whether to add attributes with the distribution for all classes "
+ "(for numeric classes this will be identical to the attribute output "
+ "with 'outputClassification').";
}
/**
* Get whether the classifiction of the classifier is output.
*
* @return true if the distribution of the classifier is output.
*/
public boolean getOutputDistribution() {
return m_OutputDistribution;
}
/**
* Set whether the Distribution of the classifier is output.
*
* @param value whether the distribution of the classifier is output.
*/
public void setOutputDistribution(boolean value) {
m_OutputDistribution = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputErrorFlagTipText() {
return "Whether to add an attribute indicating whether the classifier output "
+ "a wrong classification (for numeric classes this is the numeric "
+ "difference).";
}
/**
* Get whether the classifiction of the classifier is output.
*
* @return true if the classification of the classifier is output.
*/
public boolean getOutputErrorFlag() {
return m_OutputErrorFlag;
}
/**
* Set whether the classification of the classifier is output.
*
* @param value whether the classification of the classifier is output.
*/
public void setOutputErrorFlag(boolean value) {
m_OutputErrorFlag = value;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
int i;
ArrayList<String> values;
int classindex;
classindex = -1;
// Need to get actual class attribute from saved model if we are working with a saved model and it
// is an InputMappedClassifier.
Attribute classAttribute = inputFormat.classIndex() >= 0 ? inputFormat.classAttribute() : null;
Classifier classifier = getActualClassifier();
if (!getSerializedClassifierFile().isDirectory()) {
if (classifier instanceof InputMappedClassifier) {
classAttribute = ((InputMappedClassifier) classifier).getModelHeader(new Instances(inputFormat, 0)).classAttribute();
}
} else {
if ((classAttribute == null) && (!(classifier instanceof InputMappedClassifier))) {
throw new IllegalArgumentException("AddClassification: class must be set if InputMappedClassifier is not used.");
}
}
// copy old attributes
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (i = 0; i < inputFormat.numAttributes(); i++) {
// remove class?
if ((i == inputFormat.classIndex()) && (getRemoveOldClass())) {
continue;
}
// record class index
if (i == inputFormat.classIndex()) {
classindex = i;
}
atts.add((Attribute) inputFormat.attribute(i).copy());
}
// add new attributes
// 1. classification?
if (getOutputClassification()) {
// if old class got removed, use this one
if (classindex == -1) {
classindex = atts.size();
}
atts.add(classAttribute.copy("classification"));
}
// 2. distribution?
if (getOutputDistribution()) {
if (classAttribute.isNominal()) {
for (i = 0; i < classAttribute.numValues(); i++) {
atts.add(new Attribute("distribution_"
+ classAttribute.value(i)));
}
} else {
atts.add(new Attribute("distribution"));
}
}
// 2. error flag?
if (getOutputErrorFlag()) {
if (classAttribute.isNominal()) {
values = new ArrayList<String>();
values.add("no");
values.add("yes");
atts.add(new Attribute("error", values));
} else {
atts.add(new Attribute("error"));
}
}
// generate new header
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(classindex);
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result;
double[] newValues;
double[] oldValues;
int i;
int n;
Instance newInstance;
Instance oldInstance;
double[] distribution;
// load or train classifier
if (!isFirstBatchDone()) {
getActualClassifier();
if (!getSerializedClassifierFile().isDirectory()) {
// same dataset format?
if ((m_SerializedHeader != null)
&& (!m_SerializedHeader.equalHeaders(instances)) && (!(m_ActualClassifier instanceof InputMappedClassifier))) {
throw new WekaException(
"Training header of classifier and filter dataset don't match:\n"
+ m_SerializedHeader.equalHeadersMsg(instances));
}
} else {
m_ActualClassifier.buildClassifier(instances);
}
}
result = getOutputFormat();
// traverse all instances
for (i = 0; i < instances.numInstances(); i++) {
oldInstance = instances.instance(i);
oldValues = oldInstance.toDoubleArray();
newValues = new double[result.numAttributes()];
// copy values
int start = 0;
for (int j = 0; j < oldValues.length; j++) {
// remove class?
if ((j == inputFormatPeek().classIndex()) && (getRemoveOldClass())) {
continue;
}
newValues[start++] = oldValues[j];
}
// add new values:
// 1. classification?
if (getOutputClassification()) {
newValues[start] = m_ActualClassifier.classifyInstance(oldInstance);
start++;
}
// 2. distribution?
if (getOutputDistribution()) {
distribution = m_ActualClassifier.distributionForInstance(oldInstance);
for (n = 0; n < distribution.length; n++) {
newValues[start] = distribution[n];
start++;
}
}
// 3. error flag?
if (getOutputErrorFlag()) {
Instance inst = oldInstance;
if (m_ActualClassifier instanceof InputMappedClassifier) {
inst = ((InputMappedClassifier)m_ActualClassifier).constructMappedInstance(inst);
}
if (instances.classIndex() < 0) {
newValues[start] = Utils.missingValue();
} else if (result.classAttribute().isNominal()) {
if (inst.classValue() == m_ActualClassifier.classifyInstance(oldInstance)) {
newValues[start] = 0;
} else {
newValues[start] = 1;
}
} else {
newValues[start] = m_ActualClassifier.classifyInstance(oldInstance) - inst.classValue();
}
start++;
}
// create new instance
if (oldInstance instanceof SparseInstance) {
newInstance = new SparseInstance(oldInstance.weight(), newValues);
} else {
newInstance = new DenseInstance(oldInstance.weight(), newValues);
}
// copy string/relational values from input to output
copyValues(newInstance, false, oldInstance.dataset(), outputFormatPeek());
result.add(newInstance);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the filter with the given arguments.
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new AddClassification(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/AttributeSelection.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AttributeSelection.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.attributeSelection.ASEvaluation;
import weka.attributeSelection.ASSearch;
import weka.attributeSelection.AttributeEvaluator;
import weka.attributeSelection.AttributeTransformer;
import weka.attributeSelection.BestFirst;
import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.Ranker;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> A supervised attribute filter that can be used to select attributes. It is very flexible and allows various search and evaluation methods to be combined.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <"Name of search class [search options]">
* Sets search method for subset evaluators.
* eg. -S "weka.attributeSelection.BestFirst -S 8"
* </pre>
*
* <pre>
* -E <"Name of attribute/subset evaluation class [evaluator options]">
* Sets attribute/subset evaluator.
* eg. -E "weka.attributeSelection.CfsSubsetEval -L"
* </pre>
*
* <pre>
* Options specific to evaluator weka.attributeSelection.CfsSubsetEval:
* </pre>
*
* <pre>
* -M
* Treat missing values as a seperate value.
* </pre>
*
* <pre>
* -L
* Don't include locally predictive attributes.
* </pre>
*
* <pre>
* Options specific to search weka.attributeSelection.BestFirst:
* </pre>
*
* <pre>
* -P <start set>
* Specify a starting set of attributes.
* Eg. 1,3,5-7.
* </pre>
*
* <pre>
* -D <0 = backward | 1 = forward | 2 = bi-directional>
* Direction of search. (default = 1).
* </pre>
*
* <pre>
* -N <num>
* Number of non-improving nodes to
* consider before terminating search.
* </pre>
*
* <pre>
* -S <num>
* Size of lookup cache for evaluated subsets.
* Expressed as a multiple of the number of
* attributes in the data set. (default = 1)
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public class AttributeSelection extends Filter implements SupervisedFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -296211247688169716L;
/** the attribute selection evaluation object */
private weka.attributeSelection.AttributeSelection m_trainSelector;
/** the attribute evaluator to use */
private ASEvaluation m_ASEvaluator;
/** the search method if any */
private ASSearch m_ASSearch;
/** holds the selected attributes */
private int[] m_SelectedAttributes;
/** True if a class attribute is set in the data */
protected boolean m_hasClass;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "A supervised attribute filter that can be used to select " + "attributes. It is very flexible and allows various search " + "and evaluation methods to be combined.";
}
/**
* Constructor
*/
public AttributeSelection() {
this.resetOptions();
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(6);
newVector.addElement(new Option("\tSets search method for subset evaluators.\n" + "\teg. -S \"weka.attributeSelection.BestFirst -S 8\"", "S", 1, "-S <\"Name of search class [search options]\">"));
newVector.addElement(new Option("\tSets attribute/subset evaluator.\n" + "\teg. -E \"weka.attributeSelection.CfsSubsetEval -L\"", "E", 1, "-E <\"Name of attribute/subset evaluation class [evaluator options]\">"));
if ((this.m_ASEvaluator != null) && (this.m_ASEvaluator instanceof OptionHandler)) {
newVector.addElement(new Option("", "", 0, "\nOptions specific to " + "evaluator " + this.m_ASEvaluator.getClass().getName() + ":"));
newVector.addAll(Collections.list(((OptionHandler) this.m_ASEvaluator).listOptions()));
}
if ((this.m_ASSearch != null) && (this.m_ASSearch instanceof OptionHandler)) {
newVector.addElement(new Option("", "", 0, "\nOptions specific to " + "search " + this.m_ASSearch.getClass().getName() + ":"));
newVector.addAll(Collections.list(((OptionHandler) this.m_ASSearch).listOptions()));
}
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <"Name of search class [search options]">
* Sets search method for subset evaluators.
* eg. -S "weka.attributeSelection.BestFirst -S 8"
* </pre>
*
* <pre>
* -E <"Name of attribute/subset evaluation class [evaluator options]">
* Sets attribute/subset evaluator.
* eg. -E "weka.attributeSelection.CfsSubsetEval -L"
* </pre>
*
* <pre>
* Options specific to evaluator weka.attributeSelection.CfsSubsetEval:
* </pre>
*
* <pre>
* -M
* Treat missing values as a seperate value.
* </pre>
*
* <pre>
* -L
* Don't include locally predictive attributes.
* </pre>
*
* <pre>
* Options specific to search weka.attributeSelection.BestFirst:
* </pre>
*
* <pre>
* -P <start set>
* Specify a starting set of attributes.
* Eg. 1,3,5-7.
* </pre>
*
* <pre>
* -D <0 = backward | 1 = forward | 2 = bi-directional>
* Direction of search. (default = 1).
* </pre>
*
* <pre>
* -N <num>
* Number of non-improving nodes to
* consider before terminating search.
* </pre>
*
* <pre>
* -S <num>
* Size of lookup cache for evaluated subsets.
* Expressed as a multiple of the number of
* attributes in the data set. (default = 1)
* </pre>
*
* <!-- options-end -->
*
* @param options
* the list of options as an array of strings
* @throws Exception
* if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String optionString;
this.resetOptions();
if (Utils.getFlag('X', options)) {
throw new Exception("Cross validation is not a valid option" + " when using attribute selection as a Filter.");
}
optionString = Utils.getOption('E', options);
if (optionString.length() != 0) {
optionString = optionString.trim();
// split a quoted evaluator name from its options (if any)
int breakLoc = optionString.indexOf(' ');
String evalClassName = optionString;
String evalOptionsString = "";
String[] evalOptions = null;
if (breakLoc != -1) {
evalClassName = optionString.substring(0, breakLoc);
evalOptionsString = optionString.substring(breakLoc).trim();
evalOptions = Utils.splitOptions(evalOptionsString);
}
this.setEvaluator(ASEvaluation.forName(evalClassName, evalOptions));
}
if (this.m_ASEvaluator instanceof AttributeEvaluator) {
this.setSearch(new Ranker());
}
optionString = Utils.getOption('S', options);
if (optionString.length() != 0) {
optionString = optionString.trim();
int breakLoc = optionString.indexOf(' ');
String SearchClassName = optionString;
String SearchOptionsString = "";
String[] SearchOptions = null;
if (breakLoc != -1) {
SearchClassName = optionString.substring(0, breakLoc);
SearchOptionsString = optionString.substring(breakLoc).trim();
SearchOptions = Utils.splitOptions(SearchOptionsString);
}
this.setSearch(ASSearch.forName(SearchClassName, SearchOptions));
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings for the attribute selection (search, evaluator) etc.
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
String[] EvaluatorOptions = new String[0];
String[] SearchOptions = new String[0];
int current = 0;
if (this.m_ASEvaluator instanceof OptionHandler) {
EvaluatorOptions = ((OptionHandler) this.m_ASEvaluator).getOptions();
}
if (this.m_ASSearch instanceof OptionHandler) {
SearchOptions = ((OptionHandler) this.m_ASSearch).getOptions();
}
String[] setOptions = new String[10];
setOptions[current++] = "-E";
setOptions[current++] = this.getEvaluator().getClass().getName() + " " + Utils.joinOptions(EvaluatorOptions);
setOptions[current++] = "-S";
setOptions[current++] = this.getSearch().getClass().getName() + " " + Utils.joinOptions(SearchOptions);
while (current < setOptions.length) {
setOptions[current++] = "";
}
return setOptions;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String evaluatorTipText() {
return "Determines how attributes/attribute subsets are evaluated.";
}
/**
* set attribute/subset evaluator
*
* @param evaluator
* the evaluator to use
*/
public void setEvaluator(final ASEvaluation evaluator) {
this.m_ASEvaluator = evaluator;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String searchTipText() {
return "Determines the search method.";
}
/**
* Set search class
*
* @param search
* the search class to use
*/
public void setSearch(final ASSearch search) {
this.m_ASSearch = search;
}
/**
* Get the name of the attribute/subset evaluator
*
* @return the name of the attribute/subset evaluator as a string
*/
public ASEvaluation getEvaluator() {
return this.m_ASEvaluator;
}
/**
* Get the name of the search method
*
* @return the name of the search method as a string
*/
public ASSearch getSearch() {
return this.m_ASSearch;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
if (this.m_ASEvaluator == null) {
result = super.getCapabilities();
result.disableAll();
} else {
result = this.m_ASEvaluator.getCapabilities();
// class index will be set if necessary, so we always allow the dataset
// to have no class attribute set. see the following method:
// weka.attributeSelection.AttributeSelection.SelectAttributes(Instances)
result.enable(Capability.NO_CLASS);
}
result.setMinimumNumberInstances(0);
return result;
}
/**
* 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.
* @throws Exception
* if the input instance was not of the correct format or if there was a problem with the filtering.
*/
@Override
public boolean input(final Instance instance) throws Exception {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isOutputFormatDefined()) {
this.convertInstance(instance);
return true;
}
this.bufferInput(instance);
return false;
}
/**
* Signify 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.
* @throws Exception
* if there is a problem during the attribute selection.
*/
@Override
public boolean batchFinished() throws Exception {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!this.isOutputFormatDefined()) {
this.m_hasClass = (this.getInputFormat().classIndex() >= 0);
this.m_trainSelector.setEvaluator(this.m_ASEvaluator);
this.m_trainSelector.setSearch(this.m_ASSearch);
this.m_trainSelector.SelectAttributes(this.getInputFormat());
this.m_SelectedAttributes = this.m_trainSelector.selectedAttributes();
if (this.m_SelectedAttributes == null) {
throw new Exception("No selected attributes\n");
}
this.setOutputFormat();
// Convert pending input instances
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
this.convertInstance(this.getInputFormat().instance(i));
}
this.flushInput();
}
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Set the output format. Takes the currently defined attribute set m_InputFormat and calls setOutputFormat(Instances) appropriately.
*
* @throws Exception
* if something goes wrong
*/
protected void setOutputFormat() throws Exception {
Instances informat;
if (this.m_SelectedAttributes == null) {
this.setOutputFormat(null);
return;
}
ArrayList<Attribute> attributes = new ArrayList<Attribute>(this.m_SelectedAttributes.length);
int i;
if (this.m_ASEvaluator instanceof AttributeTransformer) {
informat = ((AttributeTransformer) this.m_ASEvaluator).transformedHeader();
} else {
informat = this.getInputFormat();
}
for (i = 0; i < this.m_SelectedAttributes.length; i++) {
attributes.add((Attribute) informat.attribute(this.m_SelectedAttributes[i]).copy());
}
Instances outputFormat = new Instances(this.getInputFormat().relationName(), attributes, 0);
// if (!(m_ASEvaluator instanceof UnsupervisedSubsetEvaluator)
// && !(m_ASEvaluator instanceof UnsupervisedAttributeEvaluator)) {
if (this.m_hasClass) {
outputFormat.setClassIndex(this.m_SelectedAttributes.length - 1);
}
this.setOutputFormat(outputFormat);
}
/**
* Convert a single instance over. Selected attributes only are transfered. The converted instance is added to the end of the output queue.
*
* @param instance
* the instance to convert
* @throws Exception
* if something goes wrong
*/
protected void convertInstance(final Instance instance) throws Exception {
double[] newVals = new double[this.getOutputFormat().numAttributes()];
if (this.m_ASEvaluator instanceof AttributeTransformer) {
Instance tempInstance = ((AttributeTransformer) this.m_ASEvaluator).convertInstance(instance);
for (int i = 0; i < this.m_SelectedAttributes.length; i++) {
int current = this.m_SelectedAttributes[i];
newVals[i] = tempInstance.value(current);
}
} else {
for (int i = 0; i < this.m_SelectedAttributes.length; i++) {
int current = this.m_SelectedAttributes[i];
newVals[i] = instance.value(current);
}
}
if (instance instanceof SparseInstance) {
this.push(new SparseInstance(instance.weight(), newVals));
} else {
this.push(new DenseInstance(instance.weight(), newVals));
}
}
/**
* set options to their default values
*/
protected void resetOptions() {
this.m_trainSelector = new weka.attributeSelection.AttributeSelection();
this.setEvaluator(new CfsSubsetEval());
this.setSearch(new BestFirst());
this.m_SelectedAttributes = null;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv
* should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new AttributeSelection(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/ClassConditionalProbabilities.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ClassConditionalProbabilities
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.*;
import weka.estimators.Estimator;
import weka.filters.Filter;
import weka.filters.SimpleBatchFilter;
import weka.filters.unsupervised.attribute.Remove;
import weka.gui.ProgrammaticProperty;
/**
<!-- globalinfo-start -->
* Converts the values of nominal and/or numeric attributes into class conditional probabilities. If there are k classes, then k new attributes are created for each of the original ones, giving pr(att val | class k).<br/>
* <br/>
* Can be useful for converting nominal attributes with a lot of distinct values into something more manageable for learning schemes that can't handle nominal attributes (as opposed to creating binary indicator attributes). For nominal attributes, the user can specify the number values above which an attribute will be converted by this method. Normal distributions are assumed for numeric attributes.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N
* Don't apply this transformation to numeric attributes</pre>
*
* <pre> -C
* Don't apply this transformation to nominal attributes</pre>
*
* <pre> -min-values <integer>
* Transform nominal attributes with at least this many values.
* -1 means always transform.</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <pre>-spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.</pre>
*
<!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class ClassConditionalProbabilities extends SimpleBatchFilter
implements WeightedAttributesHandler, WeightedInstancesHandler{
/** For serialization */
private static final long serialVersionUID = 1684310720200284263L;
/** True if numeric attributes are to be excluded from the transformation */
protected boolean m_excludeNumericAttributes;
/** True if nominal attributes are to be excluded from the transformation */
protected boolean m_excludeNominalAttributes;
/**
* Don't convert nominal attributes with fewer than this number of values. -1
* means always convert
*/
protected int m_nominalConversionThreshold = -1;
/** The Naive Bayes classifier to use for class conditional estimation */
protected NaiveBayes m_estimator;
/** Remove filter to use for creating a set of untouched attributes */
protected Remove m_remove;
/**
* The attributes from the original data that are untouched by this
* transformation
*/
protected Instances m_unchanged;
/** A lookup of estimators from Naive Bayes */
protected Map<String, Estimator[]> m_estimatorLookup;
/** Whether to spread attribute weight when creating binary attributes */
protected boolean m_SpreadAttributeWeight = false;
/**
* Main method for testing this class
*
* @param args args
*/
public static void main(String[] args) {
runFilter(new ClassConditionalProbabilities(), args);
}
/**
* Global help info for this method
*
* @return the global help info
*/
@Override
public String globalInfo() {
return "Converts the values of nominal and/or numeric attributes into "
+ "class conditional probabilities. If there are k classes, then k "
+ "new attributes are created for each of the original ones, giving "
+ "pr(att val | class k).\n\nCan be useful for converting nominal attributes "
+ "with a lot of distinct values into something more manageable for learning "
+ "schemes that can't handle nominal attributes (as opposed to creating "
+ "binary indicator attributes). For nominal attributes, the user can "
+ "specify the number values above which an attribute will be converted "
+ "by this method. Normal distributions are assumed for numeric attributes.";
}
/**
* Get whether numeric attributes are being excluded from the transformation
*
* @return true if numeric attributes are to be excluded
*/
@OptionMetadata(displayName = "Exclude numeric attributes",
description = "Don't apply this transformation to numeric attributes",
commandLineParamName = "N", commandLineParamIsFlag = true,
commandLineParamSynopsis = "-N", displayOrder = 1)
public boolean getExcludeNumericAttributes() {
return m_excludeNumericAttributes;
}
/**
* Set whether numeric attributes are being excluded from the transformation
*
* @param e true if numeric attributes are to be excluded
*/
public void setExcludeNumericAttributes(boolean e) {
m_excludeNumericAttributes = e;
}
/**
* Get whether nominal attributes are to be excluded from the transformation
*
* @return true if nominal attributes are to be excluded
*/
@OptionMetadata(displayName = "Exclude nominal attributes",
description = "Don't apply this transformation to nominal attributes",
commandLineParamName = "C", commandLineParamIsFlag = true,
commandLineParamSynopsis = "-C", displayOrder = 2)
public boolean getExcludeNominalAttributes() {
return m_excludeNominalAttributes;
}
/**
* Set whether nominal attributes are to be excluded from the transformation
*
* @param e true if nominal attributes are to be excluded
*/
public void setExcludeNominalAttributes(boolean e) {
m_excludeNominalAttributes = e;
}
/**
* If true, when generating attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @param p whether weight is spread
*/
@OptionMetadata(displayName = "Spread weight across new attributes",
description = "When generating attributes, spread weight of old\n" +
"attribute across new attributes. Do not give each new attribute the old weight.",
commandLineParamName = "spread-attribute-weight", commandLineParamIsFlag = true,
commandLineParamSynopsis = "-spread-attribute-weight", displayOrder = 3)
public void setSpreadAttributeWeight(boolean p) {
m_SpreadAttributeWeight = p;
}
/**
* If true, when generating attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @return whether weight is spread
*/
public boolean getSpreadAttributeWeight() {
return m_SpreadAttributeWeight;
}
/**
* Get the minimum number of values a nominal attribute must have in order to
* be transformed. -1 indicates no minimum (i.e. transform all nominal
* attributes)
*
* @return the number of values of a nominal attribute after which the
* transformation applies
*/
@OptionMetadata(displayName = "Nominal conversion threshold",
description = "Transform nominal attributes with at least this many"
+ " values.\n-1 means always transform.",
commandLineParamName = "min-values",
commandLineParamSynopsis = "-min-values <integer>", displayOrder = 3)
public int getNominalConversionThreshold() {
return m_nominalConversionThreshold;
}
/**
* Set the minimum number of values a nominal attribute must have in order to
* be transformed. -1 indicates no minimum (i.e. transform all nominal
* attributes)
*
* @param n the number of values of a nominal attribute after which the
* transformation applies
*/
public void setNominalConversionThreshold(int n) {
m_nominalConversionThreshold = n;
}
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
if (m_excludeNominalAttributes && m_excludeNumericAttributes) {
throw new Exception("No transformation will be done if both nominal and "
+ "numeric attributes are excluded!");
}
if (m_remove == null) {
List<Integer> attsToExclude = new ArrayList<Integer>();
if (m_excludeNumericAttributes) {
for (int i = 0; i < inputFormat.numAttributes(); i++) {
if (inputFormat.attribute(i).isNumeric()
&& i != inputFormat.classIndex()) {
attsToExclude.add(i);
}
}
}
if (m_excludeNominalAttributes || m_nominalConversionThreshold > 1) {
for (int i = 0; i < inputFormat.numAttributes(); i++) {
if (inputFormat.attribute(i).isNominal()
&& i != inputFormat.classIndex()) {
if (m_excludeNominalAttributes
|| inputFormat.attribute(i).numValues() < m_nominalConversionThreshold) {
attsToExclude.add(i);
}
}
}
}
if (attsToExclude.size() > 0) {
int[] r = new int[attsToExclude.size()];
for (int i = 0; i < attsToExclude.size(); i++) {
r[i] = attsToExclude.get(i);
}
m_remove = new Remove();
m_remove.setAttributeIndicesArray(r);
m_remove.setInputFormat(inputFormat);
Remove forRetaining = new Remove();
forRetaining.setAttributeIndicesArray(r);
forRetaining.setInvertSelection(true);
forRetaining.setInputFormat(inputFormat);
m_unchanged = Filter.useFilter(inputFormat, forRetaining);
}
}
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < inputFormat.numAttributes(); i++) {
if (i != inputFormat.classIndex()) {
if (m_unchanged != null
&& m_unchanged.attribute(inputFormat.attribute(i).name()) != null) {
atts.add((Attribute) m_unchanged.attribute(
inputFormat.attribute(i).name()).copy());
continue;
}
for (int j = 0; j < inputFormat.classAttribute().numValues(); j++) {
String name =
"pr_" + inputFormat.attribute(i).name() + "|"
+ inputFormat.classAttribute().value(j);
Attribute a = new Attribute(name);
if (getSpreadAttributeWeight()) {
a.setWeight(inputFormat.attribute(i).weight() / inputFormat.classAttribute().numValues());
} else {
a.setWeight(inputFormat.attribute(i).weight());
}
atts.add(a);
}
}
}
atts.add((Attribute) inputFormat.classAttribute().copy());
Instances data = new Instances(inputFormat.relationName(), atts, 0);
data.setClassIndex(data.numAttributes() - 1);
return data;
}
@Override
protected Instances process(Instances instances) throws Exception {
if (m_estimator == null) {
m_estimator = new NaiveBayes();
Instances trainingData = new Instances(instances);
if (m_remove != null) {
trainingData = Filter.useFilter(instances, m_remove);
}
m_estimator.buildClassifier(trainingData);
}
if (m_estimatorLookup == null) {
m_estimatorLookup = new HashMap<String, Estimator[]>();
Estimator[][] estimators = m_estimator.getConditionalEstimators();
Instances header = m_estimator.getHeader();
int index = 0;
for (int i = 0; i < header.numAttributes(); i++) {
if (i != header.classIndex()) {
m_estimatorLookup.put(header.attribute(i).name(), estimators[index]);
index++;
}
}
}
Instances result =
new Instances(getOutputFormat(), instances.numInstances());
for (int i = 0; i < instances.numInstances(); i++) {
Instance current = instances.instance(i);
Instance instNew = convertInstance(current);
// add instance to output
result.add(instNew);
}
return result;
}
/**
* Convert an input instance
*
* @param current the input instance to convert
* @return a transformed instance
* @throws Exception if a problem occurs
*/
protected Instance convertInstance(Instance current) throws Exception {
double[] vals = new double[getOutputFormat().numAttributes()];
int index = 0;
for (int j = 0; j < current.numAttributes(); j++) {
if (j != current.classIndex()) {
if (m_unchanged != null
&& m_unchanged.attribute(current.attribute(j).name()) != null) {
vals[index++] = current.value(j);
} else {
Estimator[] estForAtt =
m_estimatorLookup.get(current.attribute(j).name());
for (int k = 0; k < current.classAttribute().numValues(); k++) {
if (current.isMissing(j)) {
vals[index++] = Utils.missingValue();
} else {
double e = estForAtt[k].getProbability(current.value(j));
vals[index++] = e;
}
}
}
}
}
vals[vals.length - 1] = current.classValue();
DenseInstance instNew = new DenseInstance(current.weight(), vals);
return instNew;
}
@Override public boolean input(Instance inst) throws Exception {
if (!isFirstBatchDone()) {
return super.input(inst);
}
Instance converted = convertInstance(inst);
push(converted);
return true;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
return new NaiveBayes().getCapabilities();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: $");
}
/**
* Get the naive Bayes estimator in use
*
* @return the naive Bayes estimator
*/
@ProgrammaticProperty
public NaiveBayes getEstimator() {
return m_estimator;
}
/**
* Set the naive Bayes estimator to use
*
* @param nb the naive Bayes estimator to use
*/
public void setEstimator(NaiveBayes nb) {
m_estimator = nb;
}
/**
* Get the remove filter in use
*
* @return
*/
@ProgrammaticProperty
public Remove getRemoveFilter() {
return m_remove;
}
public void setRemoveFilter(Remove r) {
m_remove = r;
m_unchanged = r.getOutputFormat();
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/ClassOrder.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ClassOrder.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> Changes the order of the classes so that the class
* values are no longer of in the order specified in the header. The values will
* be in the order specified by the user -- it could be either in
* ascending/descending order by the class frequency or in random order.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <seed>
* Specify the seed of randomization
* used to randomize the class
* order (default: 1)
* </pre>
*
* <pre>
* -C <order>
* Specify the class order to be
* sorted, could be 0: ascending
* 1: descending and 2: random.(default: 0)
* </pre>
*
* <!-- options-end -->
*
* @author Xin Xu (xx5@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class ClassOrder extends Filter implements SupervisedFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -2116226838887628411L;
/** The seed of randomization */
private long m_Seed = 1;
/** The random object */
private Random m_Random = null;
/**
* The 1-1 converting table from the original class values to the new values
*/
private int[] m_Converter = null;
/** Class attribute of the data */
private Attribute m_ClassAttribute = null;
/** The class order to be sorted */
private int m_ClassOrder = 0;
/** The class values are sorted in ascending order based on their frequencies */
public static final int FREQ_ASCEND = 0;
/** The class values are sorted in descending order based on their frequencies */
public static final int FREQ_DESCEND = 1;
/** The class values are sorted in random order */
public static final int RANDOM = 2;
/**
* This class can provide the class distribution in the sorted order as side
* effect
*/
private double[] m_ClassCounts = null;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Changes the order of the classes so that the class values are " + "no longer of in the order specified in the header. " + "The values will be in the order specified by the user "
+ "-- it could be either in ascending/descending order by the class " + "frequency or in random order.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option("\tSpecify the seed of randomization\n" + "\tused to randomize the class\n" + "\torder (default: 1)", "R", 1, "-R <seed>"));
newVector.addElement(new Option("\tSpecify the class order to be\n" + "\tsorted, could be 0: ascending\n" + "\t1: descending and 2: random.(default: 0)", "C", 1, "-C <order>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <seed>
* Specify the seed of randomization
* used to randomize the class
* order (default: 1)
* </pre>
*
* <pre>
* -C <order>
* Specify the class order to be
* sorted, could be 0: ascending
* 1: descending and 2: random.(default: 0)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String seedString = Utils.getOption('R', options);
if (seedString.length() != 0) {
this.m_Seed = Long.parseLong(seedString);
} else {
this.m_Seed = 1;
}
String orderString = Utils.getOption('C', options);
if (orderString.length() != 0) {
this.m_ClassOrder = Integer.parseInt(orderString);
} else {
this.m_ClassOrder = FREQ_ASCEND;
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
this.m_Random = null;
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-R");
options.add("" + this.m_Seed);
options.add("-C");
options.add("" + this.m_ClassOrder);
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "Specify the seed of randomization of the class order";
}
/**
* Get the current randomization seed
*
* @return a seed
*/
public long getSeed() {
return this.m_Seed;
}
/**
* Set randomization seed
*
* @param seed the set seed
*/
public void setSeed(final long seed) {
this.m_Seed = seed;
this.m_Random = null;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classOrderTipText() {
return "Specify the class order after the filtering (0: ascending," + "1: descending, or 2: random)";
}
/**
* Get the wanted class order
*
* @return class order
*/
public int getClassOrder() {
return this.m_ClassOrder;
}
/**
* Set the wanted class order
*
* @param order the class order
*/
public void setClassOrder(final int order) {
this.m_ClassOrder = order;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_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 no class index set or class not nominal
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(new Instances(instanceInfo, 0));
this.m_ClassAttribute = instanceInfo.classAttribute();
this.m_Random = new Random(this.m_Seed);
this.m_Converter = null;
int numClasses = instanceInfo.numClasses();
this.m_ClassCounts = new double[numClasses];
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.
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
// In case some one use this routine in testing,
// although he/she should not do so
if (this.m_Converter != null) {
Instance datum = (Instance) instance.copy();
if (!datum.isMissing(this.m_ClassAttribute)) {
datum.setClassValue(this.m_Converter[(int) datum.classValue()]);
}
this.push(datum, false); // No need to copy instance
return true;
}
if (!instance.isMissing(this.m_ClassAttribute)) {
this.m_ClassCounts[(int) instance.classValue()] += instance.weight();
}
this.bufferInput(instance);
return false;
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* inputFormat has been re-assigned or new options have been set). This
* implementation sorts the class values and provide class counts in the
* output format
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined,
* @throws Exception if there was a problem finishing the batch.
*/
@Override
public boolean batchFinished() throws Exception {
Instances data = this.getInputFormat();
if (data == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_Converter == null) {
// Get randomized indices and class counts
int[] randomIndices = new int[this.m_ClassCounts.length];
for (int i = 0; i < randomIndices.length; i++) {
randomIndices[i] = i;
}
for (int j = randomIndices.length - 1; j > 0; j--) {
int toSwap = this.m_Random.nextInt(j + 1);
int tmpIndex = randomIndices[j];
randomIndices[j] = randomIndices[toSwap];
randomIndices[toSwap] = tmpIndex;
}
double[] randomizedCounts = new double[this.m_ClassCounts.length];
for (int i = 0; i < randomizedCounts.length; i++) {
randomizedCounts[i] = this.m_ClassCounts[randomIndices[i]];
}
// Create new order. For the moment m_Converter converts new indices
// into old ones.
if (this.m_ClassOrder == RANDOM) {
this.m_Converter = randomIndices;
this.m_ClassCounts = randomizedCounts;
} else {
int[] sorted = Utils.sort(randomizedCounts);
this.m_Converter = new int[sorted.length];
if (this.m_ClassOrder == FREQ_ASCEND) {
for (int i = 0; i < sorted.length; i++) {
this.m_Converter[i] = randomIndices[sorted[i]];
}
} else if (this.m_ClassOrder == FREQ_DESCEND) {
for (int i = 0; i < sorted.length; i++) {
this.m_Converter[i] = randomIndices[sorted[sorted.length - i - 1]];
}
} else {
throw new IllegalArgumentException("Class order not defined!");
}
// Change class counts
double[] tmp2 = new double[this.m_ClassCounts.length];
for (int i = 0; i < this.m_Converter.length; i++) {
tmp2[i] = this.m_ClassCounts[this.m_Converter[i]];
}
this.m_ClassCounts = tmp2;
}
// Change the class values
ArrayList<String> values = new ArrayList<String>(data.classAttribute().numValues());
for (int i = 0; i < data.numClasses(); i++) {
values.add(data.classAttribute().value(this.m_Converter[i]));
}
ArrayList<Attribute> newVec = new ArrayList<Attribute>(data.numAttributes());
for (int i = 0; i < data.numAttributes(); i++) {
if (i == data.classIndex()) {
newVec.add(new Attribute(data.classAttribute().name(), values, data.classAttribute().getMetadata()));
} else {
newVec.add(data.attribute(i));
}
}
Instances newInsts = new Instances(data.relationName(), newVec, 0);
newInsts.setClassIndex(data.classIndex());
this.setOutputFormat(newInsts);
// From now on we need m_Converter to convert old indices into new ones
int[] temp = new int[this.m_Converter.length];
for (int i = 0; i < temp.length; i++) {
temp[this.m_Converter[i]] = i;
}
this.m_Converter = temp;
// Process all instances
for (int xyz = 0; xyz < data.numInstances(); xyz++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Instance datum = data.instance(xyz);
if (!datum.isMissing(datum.classIndex())) {
datum.setClassValue(this.m_Converter[(int) datum.classValue()]);
}
this.push(datum, false); // No need to copy instance.
}
}
this.flushInput();
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Get the class distribution of the sorted class values. If class is numeric
* it returns null
*
* @return the class counts
*/
public double[] getClassCounts() {
if (this.m_ClassAttribute.isNominal()) {
return this.m_ClassCounts;
} else {
return null;
}
}
/**
* Convert the given class distribution back to the distributions with the
* original internal class index
*
* @param before the given class distribution
* @return the distribution converted back
*/
public double[] distributionsByOriginalIndex(final double[] before) {
double[] after = new double[this.m_Converter.length];
for (int i = 0; i < this.m_Converter.length; i++) {
after[i] = before[this.m_Converter[i]];
}
return after;
}
/**
* Return the original internal class value given the randomized class value,
* i.e. the string presentations of the two indices are the same. It's useful
* when the filter is used within a classifier so that the filtering procedure
* should be transparent to the evaluation
*
* @param value the given value
* @return the original internal value, -1 if not found
* @throws Exception if the coverter table is not set yet
*/
public double originalValue(final double value) throws Exception {
if (this.m_Converter == null) {
throw new IllegalStateException("Coverter table not defined yet!");
}
for (int i = 0; i < this.m_Converter.length; i++) {
if ((int) value == this.m_Converter[i]) {
return i;
}
}
return -1;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new ClassOrder(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Discretize.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.ContingencyTables;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.SpecialFunctions;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that discretizes a range of numeric attributes in
* the dataset into nominal attributes. Discretization is by Fayyad & Irani's MDL method (the
* default).<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Usama M. Fayyad, Keki B. Irani: Multi-interval discretization of continuousvalued attributes for
* classification learning. In: Thirteenth International Joint Conference on Articial Intelligence,
* 1022-1027, 1993.<br/>
* <br/>
* Igor Kononenko: On Biases in Estimating Multi-Valued Attributes. In: 14th International Joint
* Conference on Articial Intelligence, 1034-1040, 1995.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Fayyad1993,
* author = {Usama M. Fayyad and Keki B. Irani},
* booktitle = {Thirteenth International Joint Conference on Articial Intelligence},
* pages = {1022-1027},
* publisher = {Morgan Kaufmann Publishers},
* title = {Multi-interval discretization of continuousvalued attributes for classification learning},
* volume = {2},
* year = {1993}
* }
*
* @inproceedings{Kononenko1995,
* author = {Igor Kononenko},
* booktitle = {14th International Joint Conference on Articial Intelligence},
* pages = {1034-1040},
* title = {On Biases in Estimating Multi-Valued Attributes},
* year = {1995},
* PS = {http://ai.fri.uni-lj.si/papers/kononenko95-ijcai.ps.gz}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to Discretize. First and last are valid indexes.
* (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -D
* Output binary attributes for discretized attributes.
* </pre>
*
* <pre>
* -Y
* Use bin numbers rather than ranges for discretized attributes.
* </pre>
*
* <pre>
* -E
* Use better encoding of split point for MDL.
* </pre>
*
* <pre>
* -K
* Use Kononenko's MDL criterion.
* </pre>
*
* <pre>
* -precision <integer>
* Precision for bin boundary labels.
* (default = 6 decimal places).
* </pre>
*
* <pre>
* -spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Discretize extends Filter implements SupervisedFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler, TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = -3141006402280129097L;
/** Stores which columns to Discretize */
protected Range m_DiscretizeCols = new Range();
/** Store the current cutpoints */
protected double[][] m_CutPoints = null;
/** Output binary attributes for discretized attributes. */
protected boolean m_MakeBinary = false;
/** Use bin numbers rather than ranges for discretized attributes. */
protected boolean m_UseBinNumbers = 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;
/** Precision for bin range labels */
protected int m_BinRangePrecision = 6;
/** Whether to spread attribute weight when creating binary attributes */
protected boolean m_SpreadAttributeWeight = false;
/** Constructor - initialises the filter */
public Discretize() {
this.setAttributeIndices("first-last");
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<>(6);
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 bin numbers rather than ranges for discretized attributes.", "Y", 0, "-Y"));
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"));
newVector.addElement(new Option("\tPrecision for bin boundary labels.\n\t" + "(default = 6 decimal places).", "precision", 1, "-precision <integer>"));
newVector.addElement(
new Option("\tWhen generating binary attributes, spread weight of old " + "attribute across new attributes. Do not give each new attribute the old weight.\n\t", "spread-attribute-weight", 0, "-spread-attribute-weight"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to Discretize. First and last are valid indexes.
* (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -D
* Output binary attributes for discretized attributes.
* </pre>
*
* <pre>
* -Y
* Use bin numbers rather than ranges for discretized attributes.
* </pre>
*
* <pre>
* -E
* Use better encoding of split point for MDL.
* </pre>
*
* <pre>
* -K
* Use Kononenko's MDL criterion.
* </pre>
*
* <pre>
* -precision <integer>
* Precision for bin boundary labels.
* (default = 6 decimal places).
* </pre>
*
* <pre>
* -spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
* </pre>
*
* <!-- options-end -->
*
* @param options
* the list of options as an array of strings
* @throws Exception
* if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setMakeBinary(Utils.getFlag('D', options));
this.setUseBinNumbers(Utils.getFlag('Y', options));
this.setUseBetterEncoding(Utils.getFlag('E', options));
this.setUseKononenko(Utils.getFlag('K', options));
this.setInvertSelection(Utils.getFlag('V', options));
String convertList = Utils.getOption('R', options);
if (convertList.length() != 0) {
this.setAttributeIndices(convertList);
} else {
this.setAttributeIndices("first-last");
}
String precisionS = Utils.getOption("precision", options);
if (precisionS.length() > 0) {
this.setBinRangePrecision(Integer.parseInt(precisionS));
}
this.setSpreadAttributeWeight(Utils.getFlag("spread-attribute-weight", options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
List<String> options = new ArrayList<>();
if (this.getMakeBinary()) {
options.add("-D");
}
if (this.getUseBinNumbers()) {
options.add("-Y");
}
if (this.getUseBetterEncoding()) {
options.add("-E");
}
if (this.getUseKononenko()) {
options.add("-K");
}
if (this.getInvertSelection()) {
options.add("-V");
}
if (!this.getAttributeIndices().equals("")) {
options.add("-R");
options.add(this.getAttributeIndices());
}
options.add("-precision");
options.add("" + this.getBinRangePrecision());
if (this.getSpreadAttributeWeight()) {
options.add("-spread-attribute-weight");
}
return options.toArray(new String[options.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.m_DiscretizeCols.setUpper(instanceInfo.numAttributes() - 1);
this.m_CutPoints = null;
// 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 InterruptedException
* @throws IllegalStateException
* if no input format has been defined.
*/
@Override
public boolean input(final Instance instance) throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.m_CutPoints != null) {
this.convertInstance(instance);
return true;
}
this.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 InterruptedException
* @throws IllegalStateException
* if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_CutPoints == null) {
this.calculateCutPoints();
this.setOutputFormat();
// If we implement saving cutfiles, save the cuts here
// Convert pending input instances
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
this.convertInstance(this.getInputFormat().instance(i));
}
}
this.flushInput();
this.m_NewBatch = true;
return (this.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 Fayyad & Irani's MDL method (the default).\n\n" + "For more information, see:\n\n"
+ this.getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed information about the
* technical background of this class, e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
TechnicalInformation additional;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Usama M. Fayyad and Keki B. Irani");
result.setValue(Field.TITLE, "Multi-interval discretization of continuousvalued attributes for classification learning");
result.setValue(Field.BOOKTITLE, "Thirteenth International Joint Conference on Articial Intelligence");
result.setValue(Field.YEAR, "1993");
result.setValue(Field.VOLUME, "2");
result.setValue(Field.PAGES, "1022-1027");
result.setValue(Field.PUBLISHER, "Morgan Kaufmann Publishers");
additional = result.add(Type.INPROCEEDINGS);
additional.setValue(Field.AUTHOR, "Igor Kononenko");
additional.setValue(Field.TITLE, "On Biases in Estimating Multi-Valued Attributes");
additional.setValue(Field.BOOKTITLE, "14th International Joint Conference on Articial Intelligence");
additional.setValue(Field.YEAR, "1995");
additional.setValue(Field.PAGES, "1034-1040");
additional.setValue(Field.PS, "http://ai.fri.uni-lj.si/papers/kononenko95-ijcai.ps.gz");
return result;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String spreadAttributeWeightTipText() {
return "When generating binary attributes, spread weight of old attribute across new attributes. " + "Do not give each new attribute the old weight.";
}
/**
* If true, when generating binary attributes, spread weight of old attribute across new attributes.
* Do not give each new attribute the old weight.
*
* @param p
* whether weight is spread
*/
public void setSpreadAttributeWeight(final boolean p) {
this.m_SpreadAttributeWeight = p;
}
/**
* If true, when generating binary attributes, spread weight of old attribute across new attributes.
* Do not give each new attribute the old weight.
*
* @return whether weight is spread
*/
public boolean getSpreadAttributeWeight() {
return this.m_SpreadAttributeWeight;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String binRangePrecisionTipText() {
return "The number of decimal places for cut points to use when generating bin labels";
}
/**
* Set the precision for bin boundaries. Only affects the boundary values used in the labels for the
* converted attributes; internal cutpoints are at full double precision.
*
* @param p
* the precision for bin boundaries
*/
public void setBinRangePrecision(final int p) {
this.m_BinRangePrecision = p;
}
/**
* Get the precision for bin boundaries. Only affects the boundary values used in the labels for the
* converted attributes; internal cutpoints are at full double precision.
*
* @return the precision for bin boundaries
*/
public int getBinRangePrecision() {
return this.m_BinRangePrecision;
}
/**
* 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 this.m_MakeBinary;
}
/**
* Sets whether binary attributes should be made for discretized ones.
*
* @param makeBinary
* if binary attributes are to be made
*/
public void setMakeBinary(final boolean makeBinary) {
this.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 useBinNumbersTipText() {
return "Use bin numbers (eg BXofY) rather than ranges fordiscretized attributes";
}
/**
* Gets whether bin numbers rather than ranges should be used for discretized attributes.
*
* @return true if bin numbers should be used
*/
public boolean getUseBinNumbers() {
return this.m_UseBinNumbers;
}
/**
* Sets whether bin numbers rather than ranges should be used for discretized attributes.
*
* @param useBinNumbers
* if bin numbers should be used
*/
public void setUseBinNumbers(final boolean useBinNumbers) {
this.m_UseBinNumbers = useBinNumbers;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String useKononenkoTipText() {
return "Use Kononenko's MDL criterion. If set to false" + " uses the Fayyad & Irani criterion.";
}
/**
* Gets whether Kononenko's MDL criterion is to be used.
*
* @return true if Kononenko's criterion will be used.
*/
public boolean getUseKononenko() {
return this.m_UseKononenko;
}
/**
* Sets whether Kononenko's MDL criterion is to be used.
*
* @param useKon
* true if Kononenko's one is to be used
*/
public void setUseKononenko(final boolean useKon) {
this.m_UseKononenko = useKon;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String useBetterEncodingTipText() {
return "Uses a more efficient split point encoding.";
}
/**
* Gets whether better encoding is to be used for MDL.
*
* @return true if the better MDL encoding will be used
*/
public boolean getUseBetterEncoding() {
return this.m_UseBetterEncoding;
}
/**
* Sets whether better encoding is to be used for MDL.
*
* @param useBetterEncoding
* true if better encoding to be used.
*/
public void setUseBetterEncoding(final boolean useBetterEncoding) {
this.m_UseBetterEncoding = useBetterEncoding;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected" + " (numeric) attributes in the range will be discretized; if" + " true, only non-selected attributes will be discretized.";
}
/**
* Gets whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return this.m_DiscretizeCols.getInvert();
}
/**
* Sets whether selected columns should be removed or kept. If true the selected columns are kept
* and unselected columns are deleted. If false selected columns are deleted and unselected columns
* are kept.
*
* @param invert
* the new invert setting
*/
public void setInvertSelection(final boolean invert) {
this.m_DiscretizeCols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on." + " This is a comma separated list of attribute indices, with" + " \"first\" and \"last\" valid values. Specify an inclusive" + " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return this.m_DiscretizeCols.getRanges();
}
/**
* Sets which attributes are to be Discretized (only numeric attributes among the selection will be
* Discretized).
*
* @param rangeList
* a string representing the list of attributes. Since the string will typically come from
* a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException
* if an invalid range list is supplied
*/
public void setAttributeIndices(final String rangeList) {
this.m_DiscretizeCols.setRanges(rangeList);
}
/**
* Sets which attributes are to be Discretized (only numeric attributes among the selection will be
* Discretized).
*
* @param attributes
* an array containing indexes of attributes to Discretize. Since the array will typically
* come from a program, attributes are indexed from 0.
* @throws IllegalArgumentException
* if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(final int[] attributes) {
this.setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Gets the cut points for an attribute
*
* @param attributeIndex
* the index (from 0) of the attribute to get the cut points of
* @return an array containing the cutpoints (or null if the attribute requested isn't being
* Discretized
*/
public double[] getCutPoints(final int attributeIndex) {
if (this.m_CutPoints == null) {
return null;
}
return this.m_CutPoints[attributeIndex];
}
/**
* Gets the bin ranges string for an attribute
*
* @param attributeIndex
* the index (from 0) of the attribute to get the bin ranges string of
* @return the bin ranges string (or null if the attribute requested has been discretized into only
* one interval.)
*/
public String getBinRangesString(final int attributeIndex) {
if (this.m_CutPoints == null) {
return null;
}
double[] cutPoints = this.m_CutPoints[attributeIndex];
if (cutPoints == null) {
return "All";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
if (first) {
first = false;
} else {
sb.append(',');
}
sb.append(binRangeString(cutPoints, j, this.m_BinRangePrecision));
}
return sb.toString();
}
/**
* Get a bin range string for a specified bin of some attribute's cut points.
*
* @param cutPoints
* The attribute's cut points; never null.
* @param j
* The bin number (zero based); never out of range.
* @param precision
* the precision for the range values
*
* @return The bin range string.
*/
private static String binRangeString(final double[] cutPoints, final int j, final int precision) {
assert cutPoints != null;
int n = cutPoints.length;
assert 0 <= j && j <= n;
return j == 0 ? "" + "(" + "-inf" + "-" + Utils.doubleToString(cutPoints[0], precision) + "]"
: j == n ? "" + "(" + Utils.doubleToString(cutPoints[n - 1], precision) + "-" + "inf" + ")" : "" + "(" + Utils.doubleToString(cutPoints[j - 1], precision) + "-" + Utils.doubleToString(cutPoints[j], precision) + "]";
}
/**
* Generate the cutpoints for each attribute
*
* @throws InterruptedException
*/
protected void calculateCutPoints() throws InterruptedException {
Instances copy = null;
this.m_CutPoints = new double[this.getInputFormat().numAttributes()][];
for (int i = this.getInputFormat().numAttributes() - 1; i >= 0; i--) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if ((this.m_DiscretizeCols.isInRange(i)) && (this.getInputFormat().attribute(i).isNumeric())) {
// Use copy to preserve order
if (copy == null) {
copy = new Instances(this.getInputFormat());
}
this.calculateCutPointsByMDL(i, copy);
}
}
}
/**
* Set cutpoints for a single attribute using MDL.
*
* @param index
* the index of the attribute to set cutpoints for
* @param data
* the data to work with
* @throws InterruptedException
*/
protected void calculateCutPointsByMDL(final int index, final Instances data) throws InterruptedException {
// Sort instances
data.sort(data.attribute(index));
// Find first instances that's missing
int firstMissing = data.numInstances();
for (int i = 0; i < data.numInstances(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (data.instance(i).isMissing(index)) {
firstMissing = i;
break;
}
}
this.m_CutPoints[index] = this.cutPointsForSubset(data, index, 0, firstMissing);
}
/**
* Test using Kononenko's MDL criterion.
*
* @param priorCounts
* @param bestCounts
* @param numInstances
* @param numCutPoints
* @return true if the split is acceptable
*/
private boolean KononenkosMDL(final double[] priorCounts, final double[][] bestCounts, final double numInstances, final int numCutPoints) {
double distPrior, instPrior, distAfter = 0, sum, instAfter = 0;
double before, after;
int numClassesTotal;
// Number of classes occuring in the set
numClassesTotal = 0;
for (double priorCount : priorCounts) {
if (priorCount > 0) {
numClassesTotal++;
}
}
// Encode distribution prior to split
distPrior = SpecialFunctions.log2Binomial(numInstances + numClassesTotal - 1, numClassesTotal - 1);
// Encode instances prior to split.
instPrior = SpecialFunctions.log2Multinomial(numInstances, priorCounts);
before = instPrior + distPrior;
// Encode distributions and instances after split.
for (double[] bestCount : bestCounts) {
sum = Utils.sum(bestCount);
distAfter += SpecialFunctions.log2Binomial(sum + numClassesTotal - 1, numClassesTotal - 1);
instAfter += SpecialFunctions.log2Multinomial(sum, bestCount);
}
// Coding cost after split
after = Utils.log2(numCutPoints) + distAfter + instAfter;
// Check if split is to be accepted
return (before > after);
}
/**
* Test using Fayyad and Irani's MDL criterion.
*
* @param priorCounts
* @param bestCounts
* @param numInstances
* @param numCutPoints
* @return true if the splits is acceptable
*/
private boolean FayyadAndIranisMDL(final double[] priorCounts, final double[][] bestCounts, final double numInstances, final int numCutPoints) {
double priorEntropy, entropy, gain;
double entropyLeft, entropyRight, delta;
int numClassesTotal, numClassesRight, numClassesLeft;
// Compute entropy before split.
priorEntropy = ContingencyTables.entropy(priorCounts);
// Compute entropy after split.
entropy = ContingencyTables.entropyConditionedOnRows(bestCounts);
// Compute information gain.
gain = priorEntropy - entropy;
// Number of classes occuring in the set
numClassesTotal = 0;
for (double priorCount : priorCounts) {
if (priorCount > 0) {
numClassesTotal++;
}
}
// Number of classes occuring in the left subset
numClassesLeft = 0;
for (int i = 0; i < bestCounts[0].length; i++) {
if (bestCounts[0][i] > 0) {
numClassesLeft++;
}
}
// Number of classes occuring in the right subset
numClassesRight = 0;
for (int i = 0; i < bestCounts[1].length; i++) {
if (bestCounts[1][i] > 0) {
numClassesRight++;
}
}
// Entropy of the left and the right subsets
entropyLeft = ContingencyTables.entropy(bestCounts[0]);
entropyRight = ContingencyTables.entropy(bestCounts[1]);
// Compute terms for MDL formula
delta = Utils.log2(Math.pow(3, numClassesTotal) - 2) - ((numClassesTotal * priorEntropy) - (numClassesRight * entropyRight) - (numClassesLeft * entropyLeft));
// Check if split is to be accepted
return (gain > (Utils.log2(numCutPoints) + delta) / numInstances);
}
/**
* Selects cutpoints for sorted subset.
*
* @param instances
* @param attIndex
* @param first
* @param lastPlusOne
* @return
* @throws InterruptedException
*/
private double[] cutPointsForSubset(final Instances instances, final int attIndex, final int first, final int lastPlusOne) throws InterruptedException {
double[][] counts, bestCounts;
double[] priorCounts, left, right, cutPoints;
double currentCutPoint = -Double.MAX_VALUE, bestCutPoint = -1, currentEntropy, bestEntropy, priorEntropy, gain;
int bestIndex = -1, numCutPoints = 0;
double numInstances = 0;
// Compute number of instances in set
if ((lastPlusOne - first) < 2) {
return null;
}
// Compute class counts.
counts = new double[2][instances.numClasses()];
for (int i = first; i < lastPlusOne; i++) {
numInstances += instances.instance(i).weight();
counts[1][(int) instances.instance(i).classValue()] += instances.instance(i).weight();
}
// Save prior counts
priorCounts = new double[instances.numClasses()];
System.arraycopy(counts[1], 0, priorCounts, 0, instances.numClasses());
// Entropy of the full set
priorEntropy = ContingencyTables.entropy(priorCounts);
bestEntropy = priorEntropy;
// Find best entropy.
bestCounts = new double[2][instances.numClasses()];
for (int i = first; i < (lastPlusOne - 1); i++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
counts[0][(int) instances.instance(i).classValue()] += instances.instance(i).weight();
counts[1][(int) instances.instance(i).classValue()] -= instances.instance(i).weight();
if (instances.instance(i).value(attIndex) < instances.instance(i + 1).value(attIndex)) {
currentCutPoint = (instances.instance(i).value(attIndex) + instances.instance(i + 1).value(attIndex)) / 2.0;
currentEntropy = ContingencyTables.entropyConditionedOnRows(counts);
if (currentEntropy < bestEntropy) {
bestCutPoint = currentCutPoint;
bestEntropy = currentEntropy;
bestIndex = i;
System.arraycopy(counts[0], 0, bestCounts[0], 0, instances.numClasses());
System.arraycopy(counts[1], 0, bestCounts[1], 0, instances.numClasses());
}
numCutPoints++;
}
}
// Use worse encoding?
if (!this.m_UseBetterEncoding) {
numCutPoints = (lastPlusOne - first) - 1;
}
// Checks if gain is zero
gain = priorEntropy - bestEntropy;
if (gain <= 0) {
return null;
}
// Check if split is to be accepted
if ((this.m_UseKononenko && this.KononenkosMDL(priorCounts, bestCounts, numInstances, numCutPoints)) || (!this.m_UseKononenko && this.FayyadAndIranisMDL(priorCounts, bestCounts, numInstances, numCutPoints))) {
// Select split points for the left and right subsets
left = this.cutPointsForSubset(instances, attIndex, first, bestIndex + 1);
right = this.cutPointsForSubset(instances, attIndex, bestIndex + 1, lastPlusOne);
// Merge cutpoints and return them
if ((left == null) && (right) == null) {
cutPoints = new double[1];
cutPoints[0] = bestCutPoint;
} else if (right == null) {
cutPoints = new double[left.length + 1];
System.arraycopy(left, 0, cutPoints, 0, left.length);
cutPoints[left.length] = bestCutPoint;
} else if (left == null) {
cutPoints = new double[1 + right.length];
cutPoints[0] = bestCutPoint;
System.arraycopy(right, 0, cutPoints, 1, right.length);
} else {
cutPoints = new double[left.length + right.length + 1];
System.arraycopy(left, 0, cutPoints, 0, left.length);
cutPoints[left.length] = bestCutPoint;
System.arraycopy(right, 0, cutPoints, left.length + 1, right.length);
}
return cutPoints;
} else {
return null;
}
}
/**
* Set the output format. Takes the currently defined cutpoints and m_InputFormat and calls
* setOutputFormat(Instances) appropriately.
*/
protected void setOutputFormat() {
if (this.m_CutPoints == null) {
this.setOutputFormat(null);
return;
}
ArrayList<Attribute> attributes = new ArrayList<>(this.getInputFormat().numAttributes());
int classIndex = this.getInputFormat().classIndex();
for (int i = 0, m = this.getInputFormat().numAttributes(); i < m; ++i) {
if ((this.m_DiscretizeCols.isInRange(i)) && (this.getInputFormat().attribute(i).isNumeric())) {
Set<String> cutPointsCheck = new HashSet<>();
double[] cutPoints = this.m_CutPoints[i];
if (!this.m_MakeBinary) {
ArrayList<String> attribValues;
if (cutPoints == null) {
attribValues = new ArrayList<>(1);
attribValues.add("'All'");
} else {
attribValues = new ArrayList<>(cutPoints.length + 1);
if (this.m_UseBinNumbers) {
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
attribValues.add("'B" + (j + 1) + "of" + (n + 1) + "'");
}
} else {
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
String newBinRangeString = binRangeString(cutPoints, j, this.m_BinRangePrecision);
if (!cutPointsCheck.add(newBinRangeString)) {
throw new IllegalArgumentException("A duplicate bin range was detected. Try increasing the bin range precision.");
}
attribValues.add("'" + newBinRangeString + "'");
}
}
}
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name(), attribValues);
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
attributes.add(newAtt);
} else {
if (cutPoints == null) {
ArrayList<String> attribValues = new ArrayList<>(1);
attribValues.add("'All'");
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name(), attribValues);
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
attributes.add(newAtt);
} else {
if (i < this.getInputFormat().classIndex()) {
classIndex += cutPoints.length - 1;
}
for (int j = 0, n = cutPoints.length; j < n; ++j) {
ArrayList<String> attribValues = new ArrayList<>(2);
if (this.m_UseBinNumbers) {
attribValues.add("'B1of2'");
attribValues.add("'B2of2'");
} else {
double[] binaryCutPoint = { cutPoints[j] };
String newBinRangeString1 = binRangeString(binaryCutPoint, 0, this.m_BinRangePrecision);
String newBinRangeString2 = binRangeString(binaryCutPoint, 1, this.m_BinRangePrecision);
if (newBinRangeString1.equals(newBinRangeString2)) {
throw new IllegalArgumentException("A duplicate bin range was detected. Try increasing the bin range precision.");
}
attribValues.add("'" + newBinRangeString1 + "'");
attribValues.add("'" + newBinRangeString2 + "'");
}
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name() + "_" + (j + 1), attribValues);
if (this.getSpreadAttributeWeight()) {
newAtt.setWeight(this.getInputFormat().attribute(i).weight() / cutPoints.length);
} else {
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
}
attributes.add(newAtt);
}
}
}
} else {
attributes.add((Attribute) this.getInputFormat().attribute(i).copy());
}
}
Instances outputFormat = new Instances(this.getInputFormat().relationName(), attributes, 0);
outputFormat.setClassIndex(classIndex);
this.setOutputFormat(outputFormat);
}
/**
* Convert a single instance over. The converted instance is added to the end of the output queue.
*
* @param instance
* the instance to convert
* @throws InterruptedException
*/
protected void convertInstance(final Instance instance) throws InterruptedException {
int index = 0;
double[] vals = new double[this.outputFormatPeek().numAttributes()];
// Copy and convert the values
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (this.m_DiscretizeCols.isInRange(i) && this.getInputFormat().attribute(i).isNumeric()) {
int j;
double currentVal = instance.value(i);
if (this.m_CutPoints[i] == null) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else {
vals[index] = 0;
}
index++;
} else {
if (!this.m_MakeBinary) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else {
for (j = 0; j < this.m_CutPoints[i].length; j++) {
if (currentVal <= this.m_CutPoints[i][j]) {
break;
}
}
vals[index] = j;
}
index++;
} else {
for (j = 0; j < this.m_CutPoints[i].length; j++) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else if (currentVal <= this.m_CutPoints[i][j]) {
vals[index] = 0;
} else {
vals[index] = 1;
}
index++;
}
}
}
} else {
vals[index] = instance.value(i);
index++;
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
this.copyValues(inst, false, instance.dataset(), this.outputFormatPeek());
this.push(inst); // No need to copy instance
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv
* should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new Discretize(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/MergeNominalValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MergeNominalValues.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.filters.SimpleBatchFilter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> Merges values of all nominal attributes among the
* specified attributes, excluding the class attribute, using the CHAID method,
* but without considering re-splitting of merged subsets. It implements Steps 1 and
* 2 described by Kass (1980), see<br/>
* <br/>
* Gordon V. Kass (1980). An Exploratory Technique for Investigating Large
* Quantities of Categorical Data. Applied Statistics. 29(2):119-127.<br/>
* <br/>
* Once attribute values have been merged, a chi-squared test using the
* Bonferroni correction is applied to check if the resulting attribute is a
* valid predictor, based on the Bonferroni multiplier in Equation 3.2 in Kass
* (1980). If an attribute does not pass this test, all remaining values (if
* any) are merged. Nevertheless, useless predictors can slip through without
* being fully merged, e.g. identifier attributes.<br/>
* <br/>
* The code applies the Yates correction when the chi-squared statistic is
* computed.<br/>
* <br/>
* Note that the algorithm is quadratic in the number of attribute values for an
* attribute.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -L <double>
* The significance level (default: 0.05).
* </pre>
*
* <pre>
* -R <range>
* Sets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. act on all attributes not specified in list)
* </pre>
*
* <pre>
* -O
* Use short identifiers for merged subsets.
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank
* @version $Revision$
*/
public class MergeNominalValues extends SimpleBatchFilter implements
SupervisedFilter, WeightedInstancesHandler, WeightedAttributesHandler, TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = 7447337831221353842L;
/** Set the significance level */
protected double m_SigLevel = 0.05;
/** Stores which atributes to operate on (or nto) */
protected Range m_SelectCols = new Range("first-last");
/** Stores the indexes of the selected attributes in order. */
protected int[] m_SelectedAttributes;
/** Indicators for which attributes need to be changed. */
protected boolean[] m_AttToBeModified;
/** The indicators used to map the old values. */
protected int[][] m_Indicators;
/** Use short values */
protected boolean m_UseShortIdentifiers = false;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Merges values of all nominal attributes among the specified attributes, excluding "
+ "the class attribute, using the CHAID method, but without considering re-splitting of "
+ "merged subsets. It implements Steps 1 and 2 described by Kass (1980), see\n\n"
+ getTechnicalInformation().toString()
+ "\n\n"
+ "Once attribute values have been merged, a chi-squared test using the Bonferroni "
+ "correction is applied to check if the resulting attribute is a valid predictor, "
+ "based on the Bonferroni multiplier in Equation 3.2 in Kass (1980). If an attribute does "
+ "not pass this test, all remaining values (if any) are merged. Nevertheless, useless "
+ "predictors can slip through without being fully merged, e.g. identifier attributes.\n\n"
+ "The code applies the Yates correction when the chi-squared statistic is computed.\n\n"
+ "Note that the algorithm is quadratic in the number of attribute values for an attribute.";
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.ARTICLE);
result.setValue(Field.AUTHOR, "Gordon V. Kass");
result
.setValue(
Field.TITLE,
"An Exploratory Technique for Investigating Large Quantities of Categorical Data");
result.setValue(Field.JOURNAL, "Applied Statistics");
result.setValue(Field.YEAR, "1980");
result.setValue(Field.VOLUME, "29");
result.setValue(Field.NUMBER, "2");
result.setValue(Field.PAGES, "119-127");
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe significance level (default: 0.05).\n",
"-L", 1, "-L <double>"));
result
.addElement(new Option(
"\tSets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'\n"
+ "\tE.g.: first-5,7,9,20-last\n" + "\t(default: first-last)", "R",
1, "-R <range>"));
result
.addElement(new Option(
"\tInvert matching sense (i.e. act on all attributes not specified in list)",
"V", 0, "-V"));
result.addElement(new Option("\tUse short identifiers for merged subsets.",
"O", 0, "-O"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-L");
result.add("" + getSignificanceLevel());
if (!getAttributeIndices().equals("")) {
;
}
{
result.add("-R");
result.add(getAttributeIndices());
}
if (getInvertSelection()) {
result.add("-V");
}
if (getUseShortIdentifiers()) {
result.add("-O");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -L <double>
* The significance level (default: 0.05).
* </pre>
*
* <pre>
* -R <range>
* Sets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. act on all attributes not specified in list)
* </pre>
*
* <pre>
* -O
* Use short identifiers for merged subsets.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String significanceLevelString = Utils.getOption('L', options);
if (significanceLevelString.length() != 0) {
setSignificanceLevel(Double.parseDouble(significanceLevelString));
} else {
setSignificanceLevel(0.05);
}
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
setUseShortIdentifiers(Utils.getFlag('O', options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String significanceLevelTipText() {
return "The significance level for the chi-squared test used to decide when to stop merging.";
}
/**
* Gets the significance level.
*
* @return int the significance level.
*/
public double getSignificanceLevel() {
return m_SigLevel;
}
/**
* Sets the significance level.
*
* @param sF the significance level as a double.
*/
public void setSignificanceLevel(double sF) {
m_SigLevel = sF;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on (or its inverse)."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_SelectCols.getRanges();
}
/**
* Set which attributes are to be acted on (or not, if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String rangeList) {
m_SelectCols.setRanges(rangeList);
}
/**
* Set which attributes are to be acted on (or not, if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether selected attributes are to be acted "
+ "on or all other attributes are used instead.";
}
/**
* Get whether the supplied attributes are to be acted on or all other
* attributes.
*
* @return true if the supplied attributes will be kept
*/
public boolean getInvertSelection() {
return m_SelectCols.getInvert();
}
/**
* Set whether selected attributes should be acted on or all other attributes.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_SelectCols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useShortIdentifiersTipText() {
return "Whether to use short identifiers for the merged values.";
}
/**
* Get whether short identifiers are to be output.
*
* @return true if short IDs are output
*/
public boolean getUseShortIdentifiers() {
return m_UseShortIdentifiers;
}
/**
* Set whether to output short identifiers for merged values.
*
* @param b if true, short IDs are output
*/
public void setUseShortIdentifiers(boolean b) {
m_UseShortIdentifiers = b;
}
/**
* We need access to the full input data in determineOutputFormat.
*/
@Override
public boolean allowAccessToFullInputFormat() {
return true;
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) {
// Set the upper limit of the range
m_SelectCols.setUpper(inputFormat.numAttributes() - 1);
// Get the selected attributes
m_SelectedAttributes = m_SelectCols.getSelection();
// Allocate arrays to store frequencies
double[][][] freqs = new double[inputFormat.numAttributes()][][];
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
Attribute att = inputFormat.attribute(current);
if ((current != inputFormat.classIndex()) && (att.isNominal())) {
freqs[current] = new double[att.numValues()][inputFormat.numClasses()];
}
}
// Go through all the instances and compute frequencies
for (Instance inst : inputFormat) {
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
if ((current != inputFormat.classIndex())
&& (inputFormat.attribute(current).isNominal())) {
if (!inst.isMissing(current) && !inst.classIsMissing()) {
freqs[current][(int) inst.value(current)][(int) inst.classValue()] += inst
.weight();
}
}
}
}
// For each attribute in turn merge values
m_AttToBeModified = new boolean[inputFormat.numAttributes()];
m_Indicators = new int[inputFormat.numAttributes()][];
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
if ((current != inputFormat.classIndex())
&& (inputFormat.attribute(current).isNominal())) {
if (m_Debug) {
System.err.println(inputFormat.attribute(current));
}
// Compute subset indicators
m_Indicators[current] = mergeValues(freqs[current]);
if (m_Debug) {
for (int j = 0; j < m_Indicators[current].length; j++) {
System.err.print(" - " + m_Indicators[current][j] + " - ");
}
System.err.println();
}
// Does attribute need to modified?
for (int k = 0; k < m_Indicators[current].length; k++) {
if (m_Indicators[current][k] != k) {
m_AttToBeModified[current] = true;
}
}
}
}
// Create new header
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < inputFormat.numAttributes(); i++) {
int current = i;
Attribute att = inputFormat.attribute(current);
if (m_AttToBeModified[i]) {
// Compute number of new values
int numValues = 0;
for (int j = 0; j < m_Indicators[current].length; j++) {
if (m_Indicators[current][j] + 1 > numValues) {
numValues = m_Indicators[current][j] + 1;
}
}
// Establish new values
ArrayList<StringBuilder> vals = new ArrayList<StringBuilder>(numValues);
for (int j = 0; j < numValues; j++) {
vals.add(null);
}
for (int j = 0; j < m_Indicators[current].length; j++) {
int index = m_Indicators[current][j];
// Do we already have a value at the given index?
StringBuilder val = vals.get(index);
if (val == null) {
if (m_UseShortIdentifiers) {
vals.set(index, new StringBuilder("" + (index + 1)));
} else {
vals.set(index, new StringBuilder(att.value(j)));
}
} else {
if (!m_UseShortIdentifiers) {
vals.get(index).append("_or_").append(att.value(j));
}
}
}
ArrayList<String> valsAsStrings = new ArrayList<String>(vals.size());
for (StringBuilder val : vals) {
valsAsStrings.add(val.toString());
}
Attribute a = new Attribute(att.name() + "_merged_values", valsAsStrings);
a.setWeight(att.weight());
atts.add(a);
} else {
atts.add((Attribute) att.copy());
}
}
// Return modified header
Instances data = new Instances(inputFormat.relationName(), atts, 0);
data.setClassIndex(inputFormat.classIndex());
return data;
}
/**
* Compute factor for Bonferroni correction. This is based on Equation 3.2 in
* Kass (1980).
*/
protected double BFfactor(int c, int r) {
double sum = 0;
double multiplier = 1.0;
for (int i = 0; i < r; i++) {
sum += multiplier
* Math
.exp((c * Math.log(r - i) - (SpecialFunctions.lnFactorial(i) + SpecialFunctions
.lnFactorial(r - i))));
multiplier *= -1.0;
}
return sum;
}
/**
* Merges values and returns list of subset indicators for the values.
*/
protected int[] mergeValues(double[][] counts) {
int[] indicators = new int[counts.length];
// Initially, each value is in its own subset
for (int i = 0; i < indicators.length; i++) {
indicators[i] = i;
}
// Can't merge further if only one subset remains
while (counts.length > 1) {
// Find two rows that differ the least according to chi-squared statistic
double[][] reducedCounts = new double[2][];
double minVal = Double.MAX_VALUE;
int toMergeOne = -1;
int toMergeTwo = -1;
for (int i = 0; i < counts.length; i++) {
reducedCounts[0] = counts[i];
for (int j = i + 1; j < counts.length; j++) {
reducedCounts[1] = counts[j];
double val = ContingencyTables.chiVal(reducedCounts, true);
if (val < minVal) {
minVal = val;
toMergeOne = i;
toMergeTwo = j;
}
}
}
// Is least significant difference still significant?
if (Statistics.chiSquaredProbability(minVal, reducedCounts[0].length - 1) <= m_SigLevel) {
// Check whether overall split is insignificant using Bonferroni
// correction
double val = ContingencyTables.chiVal(counts, true);
int df = (counts[0].length - 1) * (counts.length - 1);
double originalSig = Statistics.chiSquaredProbability(val, df);
double adjustedSig = originalSig
* BFfactor(indicators.length, counts.length);
if (m_Debug) {
System.err.println("Original p-value: " + originalSig
+ "\tAdjusted p-value: " + adjustedSig);
}
if (!(adjustedSig <= m_SigLevel)) {
// Not significant: merge all values
for (int i = 0; i < indicators.length; i++) {
indicators[i] = 0;
}
}
break;
}
// Reduce table by merging
double[][] newCounts = new double[counts.length - 1][];
for (int i = 0; i < counts.length; i++) {
if (i < toMergeTwo) {
// Can simply copy reference
newCounts[i] = counts[i];
} else if (i == toMergeTwo) {
// Need to add counts
for (int k = 0; k < counts[i].length; k++) {
newCounts[toMergeOne][k] += counts[i][k];
}
} else {
// Need to shift row
newCounts[i - 1] = counts[i];
}
}
// Update membership indicators
for (int i = 0; i < indicators.length; i++) {
// All row indices < toMergeTwo remain unmodified
if (indicators[i] >= toMergeTwo) {
if (indicators[i] == toMergeTwo) {
// Need to change index for *all* indicator fields corresponding to
// merged row
indicators[i] = toMergeOne;
} else {
// We have one row less because toMergeTwo is gone
indicators[i]--;
}
}
}
// Replace matrix
counts = newCounts;
}
return indicators;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Processes the given data.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instances process(Instances instances) throws Exception {
// Generate the output and return it
Instances result = new Instances(getOutputFormat(),
instances.numInstances());
for (int i = 0; i < instances.numInstances(); i++) {
Instance inst = instances.instance(i);
double[] newData = new double[instances.numAttributes()];
for (int j = 0; j < instances.numAttributes(); j++) {
if (m_AttToBeModified[j] && !inst.isMissing(j)) {
newData[j] = m_Indicators[j][(int) inst.value(j)];
} else {
newData[j] = inst.value(j);
}
}
DenseInstance instNew = new DenseInstance(1.0, newData);
instNew.setDataset(result);
// copy possible strings, relational values...
copyValues(instNew, false, inst.dataset(), outputFormatPeek());
// Add instance to output
result.add(instNew);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the filter with the given arguments
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new MergeNominalValues(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/MultiClassFLDA.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MultiClassFLDA.java
* Copyright (C) 2016 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import no.uib.cipr.matrix.*;
import no.uib.cipr.matrix.Matrix;
import weka.core.*;
import weka.filters.SimpleBatchFilter;
/**
<!-- globalinfo-start -->
* Implements Fisher's linear discriminant analysis for dimensionality reduction. Note that this implementation
* adds the value of the ridge parameter to the diagonal of the pooled within-class scatter matrix.
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -R
* The ridge parameter to add to the diagonal of the pooled within-class scatter matrix.
* (default is 1e-6)</pre>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 12341 $
*/
public class MultiClassFLDA extends SimpleBatchFilter implements OptionHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -291536442147283133L;
/** Stores the weighting matrix. */
protected Matrix m_WeightingMatrix;
/** Ridge parameter */
protected double m_Ridge = 1e-6;
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = new Capabilities(this);
result.disableAll();
result.setMinimumNumberInstances(0);
// attributes
result.enable(Capabilities.Capability.NUMERIC_ATTRIBUTES);
// class
result.enable(Capabilities.Capability.NOMINAL_CLASS);
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Provides information regarding this class.
*
* @return string describing the method that this class implements
*/
@Override
public String globalInfo() {
return "Implements Fisher's linear discriminant analysis for dimensionality reduction. Note that this implementation " +
"adds the value of the ridge parameter to the diagonal of the pooled within-class scatter matrix.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ridgeTipText() {
return "The ridge parameter to add to the diagonal of the pooled within-class scatter matrix.";
}
/**
* Get the value of Ridge.
*
* @return Value of Ridge.
*/
public double getRidge() {
return m_Ridge;
}
/**
* Set the value of Ridge.
*
* @param newRidge Value to assign to Ridge.
*/
public void setRidge(double newRidge) {
m_Ridge = newRidge;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration<Option> listOptions() {
java.util.Vector<Option> newVector = new java.util.Vector<Option>(7);
newVector.addElement(new Option(
"\tThe ridge parameter to add to the diagonal of the pooled within-class scatter matrix.\n"+
"\t(default is 1e-6)",
"R", 0, "-R"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
/**
* Parses a given list of options. <p/>
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -R
* The ridge parameter to add to the diagonal of the pooled within-class scatter matrix.
* (default is 1e-6)</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 {
String ridgeString = Utils.getOption('R', options);
if (ridgeString.length() != 0) {
setRidge(Double.parseDouble(ridgeString));
} else {
setRidge(1e-6);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of IBk.
*
* @return an array of strings suitable for passing to setOptions()
*/
public String [] getOptions() {
java.util.Vector<String> options = new java.util.Vector<String>();
options.add("-R"); options.add("" + getRidge());
Collections.addAll(options, super.getOptions());
return options.toArray(new String[0]);
}
/**
* Returns whether to allow the determineOutputFormat(Instances) method access
* to the full dataset rather than just the header.
* <p/>
* Default implementation returns false.
*
* @return whether determineOutputFormat has access to the full input dataset
*/
public boolean allowAccessToFullInputFormat() {
return true;
}
/**
* Computes the mean vector for the given dataset.
*/
protected Vector computeMean(Instances data, double[] totalWeight, int aI) {
Vector meanVector = new DenseVector(data.numAttributes() - 1);
totalWeight[aI] = 0;
for (Instance inst : data) {
if (!inst.classIsMissing()) {
meanVector.add(inst.weight(), instanceToVector(inst));
totalWeight[aI] += inst.weight();
}
}
meanVector.scale(1.0 / totalWeight[aI]);
return meanVector;
}
/**
* Turns an instance with a class into a vector without a class.
*/
protected Vector instanceToVector(Instance inst) {
Vector v = new DenseVector(inst.numAttributes() - 1);
int index = 0;
for (int i = 0; i < inst.numAttributes(); i++) {
if (i != inst.classIndex()){
v.set(index++, inst.value(i));
}
}
return v;
}
/**
* Determines the output format for the data that is produced by this filter.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception if a problem occurs when the output format is generated
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) throws Exception {
// Determine number of attributes
int m = inputFormat.numAttributes() - 1;
// Compute global mean
double[] totalWeight = new double[1];
Vector globalMean = computeMean(inputFormat, totalWeight, 0);
// Compute subset for each class
Instances[] subsets = new Instances[inputFormat.numClasses()];
for (int j = 0; j < subsets.length; j++) {
subsets[j] = new Instances(inputFormat, inputFormat.numInstances());
}
for (Instance inst : inputFormat) {
if (!inst.classIsMissing()) {
subsets[(int) inst.classValue()].add(inst);
}
}
// Compute mean vector and weight for each class
Vector[] perClassMeans = new DenseVector[inputFormat.numClasses()];
double[] perClassWeights = new double[inputFormat.numClasses()];
for (int i = 0; i < inputFormat.numClasses(); i++) {
perClassMeans[i] = computeMean(subsets[i], perClassWeights, i);
}
// Compute within-class scatter matrix
Matrix Cw = new UpperSymmDenseMatrix(m);
for (Instance inst : inputFormat) {
if (!inst.classIsMissing()) {
Vector diff = instanceToVector(inst);
diff = diff.add(-1.0, perClassMeans[(int) inst.classValue()]);
Cw = Cw.rank1(inst.weight(), diff);
}
}
// Add ridge to pooled within-class scatter matrix
for (int i = 0; i < Cw.numColumns(); i++) {
Cw.add(i, i, m_Ridge);
}
// Compute between-class scatter matrix
Matrix Cb = new UpperSymmDenseMatrix(m);
for (int i = 0; i < inputFormat.numClasses(); i++) {
Vector diff = perClassMeans[i].copy();
diff = diff.add(-1.0, globalMean);
Cb = Cb.rank1(perClassWeights[i], diff);
}
if (m_Debug) {
System.err.println("Within-class scatter matrix :\n" + Cw);
System.err.println("Between-class scatter matrix :\n" + Cb);
}
// Compute square root of inverse within-class scatter matrix
SymmDenseEVD evdCw = SymmDenseEVD.factorize(Cw);
Matrix evCw = evdCw.getEigenvectors();
double[] evs = evdCw.getEigenvalues();
// Eigenvectors for Cw and its inverse are the same. Eigenvalues of inverse are reciprocal of evs of original.
Matrix D = new UpperSymmDenseMatrix(evs.length);
for (int i = 0; i < evs.length; i++) {
if (evs[i] > 0) {
D.set(i, i, Math.sqrt(1.0 / evs[i]));
} else {
throw new IllegalArgumentException("Found non-positive eigenvalue of within-class scatter matrix.");
}
}
if (m_Debug) {
System.err.println("evCw : \n" + evCw);
System.err.println("Sqrt of reciprocal of eigenvalues of Cw: \n" + D);
System.err.println("evCw times evCwTransposed : \n" + evCw.mult(evCw.transpose(new DenseMatrix(m,m)), new DenseMatrix(m, m)));
}
Matrix temp = evCw.mult(D, new DenseMatrix(m, m));
Matrix sqrtCwInverse = temp.mult(evCw.transpose(), new UpperSymmDenseMatrix(m));
if (m_Debug) {
System.err.println("sqrtCwInverse : \n");
for (int i = 0; i < sqrtCwInverse.numRows(); i++) {
for (int j = 0; j < sqrtCwInverse.numColumns(); j++) {
System.err.print(sqrtCwInverse.get(i, j) + "\t");
}
System.err.println();
}
System.err.println("sqrtCwInverse times sqrtCwInverse : \n" + sqrtCwInverse.mult(sqrtCwInverse, new DenseMatrix(m, m)));
DenseMatrix I = Matrices.identity(m);
DenseMatrix CwInverse = I.copy();
System.err.println("CwInverse : \n" + Cw.solve(I, CwInverse));
}
// Compute symmetric matrix using square root
temp = sqrtCwInverse.mult(Cb, new DenseMatrix(m, m));
Matrix symmMatrix = temp.mult(sqrtCwInverse, new UpperSymmDenseMatrix(m));
if (m_Debug) {
System.err.println("Symmetric matrix : \n" + symmMatrix);
}
// Perform eigendecomposition on symmetric matrix
SymmDenseEVD evd = SymmDenseEVD.factorize(symmMatrix);
if (m_Debug) {
System.err.println("Eigenvectors of symmetric matrix :\n" + evd.getEigenvectors());
System.err.println("Eigenvalues of symmetric matrix :\n" + Utils.arrayToString(evd.getEigenvalues()) + "\n");
}
// Only keep non-zero eigenvectors
ArrayList<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < evd.getEigenvalues().length; i++) {
if (Utils.gr(evd.getEigenvalues()[i], 0)) {
indices.add(i);
}
}
int[] cols = new int[indices.size()];
int index = 0;
for (int i = indices.size() - 1; i >= 0; i--) {
cols[index++] = indices.get(i);
}
int[] rows = new int[evd.getEigenvectors().numRows()];
for (int i = 0; i < rows.length; i++) {
rows[i] = i;
}
Matrix reducedMatrix = Matrices.getSubMatrix(evd.getEigenvectors(), rows, cols);
if (m_Debug) {
System.err.println("Eigenvectors with eigenvalues > eps :\n" + reducedMatrix);
}
//
// Compute weighting Matrix
//
// Note: we do not scale the matrix so that the new attributes have (unbiased) variance 1, like R's lda does.
// In our case, the *scatter matrix* of the new data is I (if no regularization is used).
// Also, R's lda always centers the data.
//
m_WeightingMatrix = sqrtCwInverse.mult(reducedMatrix, new DenseMatrix(rows.length, cols.length)).
transpose(new DenseMatrix(cols.length, rows.length));
if (m_Debug) {
System.err.println("Weighting matrix: \n");
for (int i = 0; i < m_WeightingMatrix.numRows(); i++) {
for (int j = 0; j < m_WeightingMatrix.numColumns(); j++) {
System.err.print(m_WeightingMatrix.get(i, j) + "\t");
}
System.err.println();
}
}
// Construct header for output format
ArrayList<Attribute> atts = new ArrayList<Attribute>(cols.length + 1);
for (int i = 0; i < cols.length; i++) {
atts.add(new Attribute("z" + (i + 1)));
}
atts.add((Attribute) inputFormat.classAttribute().copy());
Instances d = new Instances(inputFormat.relationName(), atts, 0);
d.setClassIndex(d.numAttributes() - 1);
return d;
}
/**
* Takes a batch of data and transforms it.
*
* @param instances the data to process
* @return the processed instances
* @throws Exception is thrown if a problem occurs
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances transformed = getOutputFormat();
for (Instance inst : instances) {
Vector newInst = m_WeightingMatrix.mult(instanceToVector(inst), new DenseVector(m_WeightingMatrix.numRows()));
double[] newVals = new double[m_WeightingMatrix.numRows() + 1];
for (int i = 0; i < m_WeightingMatrix.numRows(); i++) {
newVals[i] = newInst.get(i);
}
newVals[transformed.classIndex()] = inst.classValue();
transformed.add(new DenseInstance(inst.weight(), newVals));
}
return transformed;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 12037 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new MultiClassFLDA(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/NominalToBinary.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NominalToBinary.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.UnassignedClassException;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> Converts all nominal attributes into binary numeric
* attributes. An attribute with k values is transformed into k binary
* attributes if the class is nominal (using the one-attribute-per-value
* approach). Binary attributes are left binary if option '-A' is not given. If
* the class is numeric, k - 1 new binary attributes are generated in the manner
* described in "Classification and Regression Trees" by Breiman et al. (i.e.
* by taking the average class value associated with each attribute value into
* account)<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* L. Breiman, J.H. Friedman, R.A. Olshen, C.J. Stone (1984). Classification and
* Regression Trees. Wadsworth Inc.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @book{Breiman1984,
* author = {L. Breiman and J.H. Friedman and R.A. Olshen and C.J. Stone},
* publisher = {Wadsworth Inc},
* title = {Classification and Regression Trees},
* year = {1984},
* ISBN = {0412048418}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Sets if binary attributes are to be coded as nominal ones.
* </pre>
*
* <pre>
* -A
* For each nominal value a new attribute is created,
* not only if there are more than 2 values.
* </pre>
*
* <pre>-spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NominalToBinary extends Filter implements SupervisedFilter, OptionHandler, TechnicalInformationHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -5004607029857673950L;
/** The sorted indices of the attribute values. */
private int[][] m_Indices = null;
/** Are the new attributes going to be nominal or numeric ones? */
private boolean m_Numeric = true;
/** Are all values transformed into new attributes? */
private boolean m_TransformAll = false;
/** Whether we need to transform at all */
private boolean m_needToTransform = false;
/** Whether to spread attribute weight when creating binary attributes */
protected boolean m_SpreadAttributeWeight = false;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Converts all nominal attributes into binary numeric attributes. An " + "attribute with k values is transformed into k binary attributes if " + "the class is nominal (using the one-attribute-per-value approach). "
+ "Binary attributes are left binary if option '-A' is not given. " + "If the class is numeric, k - 1 new binary attributes are generated " + "in the manner described in \"Classification and Regression "
+ "Trees\" by Breiman et al. (i.e., by taking the average class value associated " + "with each attribute value into account).\n\n" + "For more information, see:\n\n" + this.getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.BOOK);
result.setValue(Field.AUTHOR, "L. Breiman and J.H. Friedman and R.A. Olshen and C.J. Stone");
result.setValue(Field.TITLE, "Classification and Regression Trees");
result.setValue(Field.YEAR, "1984");
result.setValue(Field.PUBLISHER, "Wadsworth Inc");
result.setValue(Field.ISBN, "0412048418");
return result;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
if (instanceInfo.classIndex() < 0) {
throw new UnassignedClassException("No class has been assigned to the instances");
}
this.setOutputFormat();
this.m_Indices = null;
if (instanceInfo.classAttribute().isNominal()) {
return true;
} else {
return false;
}
}
/**
* Input an instance for filtering. Filter requires all training 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 set
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if ((this.m_Indices != null) || (this.getInputFormat().classAttribute().isNominal())) {
this.convertInstance((Instance) instance.copy());
return true;
}
this.bufferInput(instance);
return false;
}
/**
* Signify 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 InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if ((this.m_Indices == null) && (this.getInputFormat().classAttribute().isNumeric())) {
this.computeAverageClassValues();
this.setOutputFormat();
// Convert pending input instances
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
this.convertInstance(this.getInputFormat().instance(i));
}
}
this.flushInput();
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option("\tSets if binary attributes are to be coded as nominal ones.", "N", 0, "-N"));
newVector.addElement(new Option("\tFor each nominal value a new attribute is created, \n" + "\tnot only if there are more than 2 values.", "A", 0, "-A"));
newVector.addElement(
new Option("\tWhen generating binary attributes, spread weight of old " + "attribute across new attributes. Do not give each new attribute the old weight.\n\t", "spread-attribute-weight", 0, "-spread-attribute-weight"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Sets if binary attributes are to be coded as nominal ones.
* </pre>
*
* <pre>
* -A
* For each nominal value a new attribute is created,
* not only if there are more than 2 values.
* </pre>
*
* <pre>-spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setBinaryAttributesNominal(Utils.getFlag('N', options));
this.setTransformAllValues(Utils.getFlag('A', options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
this.setSpreadAttributeWeight(Utils.getFlag("spread-attribute-weight", options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (this.getBinaryAttributesNominal()) {
options.add("-N");
}
if (this.getTransformAllValues()) {
options.add("-A");
}
if (this.getSpreadAttributeWeight()) {
options.add("-spread-attribute-weight");
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String spreadAttributeWeightTipText() {
return "When generating binary attributes, spread weight of old attribute across new attributes. " + "Do not give each new attribute the old weight.";
}
/**
* If true, when generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @param p whether weight is spread
*/
public void setSpreadAttributeWeight(final boolean p) {
this.m_SpreadAttributeWeight = p;
}
/**
* If true, when generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @return whether weight is spread
*/
public boolean getSpreadAttributeWeight() {
return this.m_SpreadAttributeWeight;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String binaryAttributesNominalTipText() {
return "Whether resulting binary attributes will be nominal.";
}
/**
* Gets if binary attributes are to be treated as nominal ones.
*
* @return true if binary attributes are to be treated as nominal ones
*/
public boolean getBinaryAttributesNominal() {
return !this.m_Numeric;
}
/**
* Sets if binary attributes are to be treates as nominal ones.
*
* @param bool true if binary attributes are to be treated as nominal ones
*/
public void setBinaryAttributesNominal(final boolean bool) {
this.m_Numeric = !bool;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String transformAllValuesTipText() {
return "Whether all nominal values are turned into new attributes, not only if there are more than 2.";
}
/**
* Gets if all nominal values are turned into new attributes, not only if
* there are more than 2.
*
* @return true all nominal values are transformed into new attributes
*/
public boolean getTransformAllValues() {
return this.m_TransformAll;
}
/**
* Sets whether all nominal values are transformed into new attributes, not
* just if there are more than 2.
*
* @param bool true if all nominal value are transformed into new attributes
*/
public void setTransformAllValues(final boolean bool) {
this.m_TransformAll = bool;
}
/** Computes average class values for each attribute and value
* @throws InterruptedException */
private void computeAverageClassValues() throws InterruptedException {
double totalCounts, sum;
Instance instance;
double[] counts;
double[][] avgClassValues = new double[this.getInputFormat().numAttributes()][0];
this.m_Indices = new int[this.getInputFormat().numAttributes()][0];
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
Attribute att = this.getInputFormat().attribute(j);
if (att.isNominal()) {
avgClassValues[j] = new double[att.numValues()];
counts = new double[att.numValues()];
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
instance = this.getInputFormat().instance(i);
if (!instance.classIsMissing() && (!instance.isMissing(j))) {
counts[(int) instance.value(j)] += instance.weight();
avgClassValues[j][(int) instance.value(j)] += instance.weight() * instance.classValue();
}
}
sum = Utils.sum(avgClassValues[j]);
totalCounts = Utils.sum(counts);
if (Utils.gr(totalCounts, 0)) {
for (int k = 0; k < att.numValues(); k++) {
if (Utils.gr(counts[k], 0)) {
avgClassValues[j][k] /= counts[k];
} else {
avgClassValues[j][k] = sum / totalCounts;
}
}
}
this.m_Indices[j] = Utils.sort(avgClassValues[j]);
}
}
}
/** Set the output format. */
private void setOutputFormat() {
if (this.getInputFormat().classAttribute().isNominal()) {
this.setOutputFormatNominal();
} else {
this.setOutputFormatNumeric();
}
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param inst the instance to convert
*/
private void convertInstance(final Instance inst) {
if (this.getInputFormat().classAttribute().isNominal()) {
this.convertInstanceNominal(inst);
} else {
this.convertInstanceNumeric(inst);
}
}
/**
* Set the output format if the class is nominal.
*/
private void setOutputFormatNominal() {
ArrayList<Attribute> newAtts;
int newClassIndex;
StringBuffer attributeName;
Instances outputFormat;
ArrayList<String> vals;
// Compute new attributes
this.m_needToTransform = false;
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
Attribute att = this.getInputFormat().attribute(i);
if (att.isNominal() && i != this.getInputFormat().classIndex() && (att.numValues() > 2 || this.m_TransformAll || this.m_Numeric)) {
this.m_needToTransform = true;
break;
}
}
if (!this.m_needToTransform) {
this.setOutputFormat(this.getInputFormat());
return;
}
newClassIndex = this.getInputFormat().classIndex();
newAtts = new ArrayList<Attribute>();
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
Attribute att = this.getInputFormat().attribute(j);
if ((!att.isNominal()) || (j == this.getInputFormat().classIndex())) {
newAtts.add((Attribute) att.copy());
} else {
if ((att.numValues() <= 2) && (!this.m_TransformAll)) {
if (this.m_Numeric) {
String value = "";
if (att.numValues() == 2) {
value = "=" + att.value(1);
}
Attribute a = new Attribute(att.name() + value);
a.setWeight(att.weight());
newAtts.add(a);
} else {
newAtts.add((Attribute) att.copy());
}
} else {
if (j < this.getInputFormat().classIndex()) {
newClassIndex += att.numValues() - 1;
}
// Compute values for new attributes
for (int k = 0; k < att.numValues(); k++) {
attributeName = new StringBuffer(att.name() + "=");
attributeName.append(att.value(k));
if (this.m_Numeric) {
Attribute a = new Attribute(attributeName.toString());
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / att.numValues());
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
} else {
vals = new ArrayList<String>(2);
vals.add("f");
vals.add("t");
Attribute a = new Attribute(attributeName.toString(), vals);
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / att.numValues());
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
}
}
}
}
}
outputFormat = new Instances(this.getInputFormat().relationName(), newAtts, 0);
outputFormat.setClassIndex(newClassIndex);
this.setOutputFormat(outputFormat);
}
/**
* Set the output format if the class is numeric.
*/
private void setOutputFormatNumeric() {
if (this.m_Indices == null) {
this.setOutputFormat(null);
return;
}
ArrayList<Attribute> newAtts;
int newClassIndex;
StringBuffer attributeName;
Instances outputFormat;
ArrayList<String> vals;
// Compute new attributes
this.m_needToTransform = false;
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
Attribute att = this.getInputFormat().attribute(i);
if (att.isNominal() && (att.numValues() > 2 || this.m_Numeric || this.m_TransformAll)) {
this.m_needToTransform = true;
break;
}
}
if (!this.m_needToTransform) {
this.setOutputFormat(this.getInputFormat());
return;
}
newClassIndex = this.getInputFormat().classIndex();
newAtts = new ArrayList<Attribute>();
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
Attribute att = this.getInputFormat().attribute(j);
if ((!att.isNominal()) || (j == this.getInputFormat().classIndex())) {
newAtts.add((Attribute) att.copy());
} else {
if (j < this.getInputFormat().classIndex()) {
newClassIndex += att.numValues() - 2;
}
// Compute values for new attributes
for (int k = 1; k < att.numValues(); k++) {
attributeName = new StringBuffer(att.name() + "=");
for (int l = k; l < att.numValues(); l++) {
if (l > k) {
attributeName.append(',');
}
attributeName.append(att.value(this.m_Indices[j][l]));
}
if (this.m_Numeric) {
Attribute a = new Attribute(attributeName.toString());
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / (att.numValues() - 1));
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
} else {
vals = new ArrayList<String>(2);
vals.add("f");
vals.add("t");
Attribute a = new Attribute(attributeName.toString(), vals);
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / (att.numValues() - 1));
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
}
}
}
}
outputFormat = new Instances(this.getInputFormat().relationName(), newAtts, 0);
outputFormat.setClassIndex(newClassIndex);
this.setOutputFormat(outputFormat);
}
/**
* Convert a single instance over if the class is nominal. The converted
* instance is added to the end of the output queue.
*
* @param instance the instance to convert
*/
private void convertInstanceNominal(final Instance instance) {
if (!this.m_needToTransform) {
this.push(instance, false); // No need to copy instance
return;
}
double[] vals = new double[this.outputFormatPeek().numAttributes()];
int attSoFar = 0;
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
Attribute att = this.getInputFormat().attribute(j);
if ((!att.isNominal()) || (j == this.getInputFormat().classIndex())) {
vals[attSoFar] = instance.value(j);
attSoFar++;
} else {
if ((att.numValues() <= 2) && (!this.m_TransformAll)) {
vals[attSoFar] = instance.value(j);
attSoFar++;
} else {
if (instance.isMissing(j)) {
for (int k = 0; k < att.numValues(); k++) {
vals[attSoFar + k] = instance.value(j);
}
} else {
for (int k = 0; k < att.numValues(); k++) {
if (k == (int) instance.value(j)) {
vals[attSoFar + k] = 1;
} else {
vals[attSoFar + k] = 0;
}
}
}
attSoFar += att.numValues();
}
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
this.copyValues(inst, false, instance.dataset(), this.outputFormatPeek());
this.push(inst); // No need to copy instance
}
/**
* Convert a single instance over if the class is numeric. The converted
* instance is added to the end of the output queue.
*
* @param instance the instance to convert
*/
private void convertInstanceNumeric(final Instance instance) {
if (!this.m_needToTransform) {
this.push(instance, false); // No need to copy instance
return;
}
double[] vals = new double[this.outputFormatPeek().numAttributes()];
int attSoFar = 0;
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
Attribute att = this.getInputFormat().attribute(j);
if ((!att.isNominal()) || (j == this.getInputFormat().classIndex())) {
vals[attSoFar] = instance.value(j);
attSoFar++;
} else {
if (instance.isMissing(j)) {
for (int k = 0; k < att.numValues() - 1; k++) {
vals[attSoFar + k] = instance.value(j);
}
} else {
int k = 0;
while ((int) instance.value(j) != this.m_Indices[j][k]) {
vals[attSoFar + k] = 1;
k++;
}
while (k < att.numValues() - 1) {
vals[attSoFar + k] = 0;
k++;
}
}
attSoFar += att.numValues() - 1;
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
this.copyValues(inst, false, instance.dataset(), this.outputFormatPeek());
this.push(inst); // No need to copy instance
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new NominalToBinary(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/attribute/PartitionMembership.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* PartitionMembership.java
* Copyright (C) 2012 Eibe Frank
*
*/
package weka.filters.supervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.trees.J48;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start -->
* * A filter that uses a PartitionGenerator to generate partition membership values; filtered instances are composed of these values plus the class attribute (if set in the input data) and rendered as sparse instances. See Section 3 of<br>
* * Eibe Frank, Bernhard Pfahringer: Propositionalisation of Multi-instance Data Using Random Forests. In: AI 2013: Advances in Artificial Intelligence, 362-373, 2013.
* * <br><br>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* * Valid options are: <p>
* *
* * <pre> -W <name of partition generator>
* * Full name of partition generator to use, e.g.:
* * weka.classifiers.trees.J48
* * Additional options after the '--'.
* * (default: weka.classifiers.trees.J48)</pre>
* *
* <!-- options-end -->
*
* Options after the -- are passed on to the clusterer.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public class PartitionMembership extends Filter implements SupervisedFilter,
OptionHandler, RevisionHandler, TechnicalInformationHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 333532554667754026L;
/** The partition generator */
protected PartitionGenerator m_partitionGenerator = new J48();
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = m_partitionGenerator.getCapabilities();
result.setMinimumNumberInstances(0);
return result;
}
/**
* Tests the data whether the filter can actually handle it
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
@Override
protected void testInputFormat(Instances instanceInfo) throws Exception {
getCapabilities().testWithFail(instanceInfo);
}
/**
* 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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
return false;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (outputFormatPeek() == null) {
Instances toFilter = getInputFormat();
// Build the partition generator
m_partitionGenerator.generatePartition(toFilter);
// Create output dataset
ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
for (int i = 0; i < m_partitionGenerator.numElements(); i++) {
attInfo.add(new Attribute("partition_" + i));
}
if (toFilter.classIndex() >= 0) {
attInfo.add((Attribute) toFilter.classAttribute().copy());
}
attInfo.trimToSize();
Instances filtered = new Instances(toFilter.relationName()
+ "_partitionMembership", attInfo, 0);
if (toFilter.classIndex() >= 0) {
filtered.setClassIndex(filtered.numAttributes() - 1);
}
setOutputFormat(filtered);
// build new dataset
for (int i = 0; i < toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
* @throws Exception if something goes wrong
*/
protected void convertInstance(Instance instance) throws Exception {
// Make copy and set weight to one
Instance cp = (Instance) instance.copy();
cp.setWeight(1.0);
// Set up values
double[] instanceVals = new double[outputFormatPeek().numAttributes()];
double[] vals = m_partitionGenerator.getMembershipValues(cp);
System.arraycopy(vals, 0, instanceVals, 0, vals.length);
if (instance.classIndex() >= 0) {
instanceVals[instanceVals.length - 1] = instance.classValue();
}
push(new SparseInstance(instance.weight(), instanceVals));
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(1);
newVector.addElement(new Option(
"\tFull name of partition generator to use, e.g.:\n"
+ "\t\tweka.classifiers.trees.J48\n"
+ "\tAdditional options after the '--'.\n"
+ "\t(default: weka.classifiers.trees.J48)", "W", 1,
"-W <name of partition generator>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start -->
* * Valid options are: <p>
* *
* * <pre> -W <name of partition generator>
* * Full name of partition generator to use, e.g.:
* * weka.classifiers.trees.J48
* * Additional options after the '--'.
* * (default: weka.classifiers.trees.J48)</pre>
* *
* <!-- options-end -->
*
* Options after the -- are passed on to the clusterer.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String generatorString = Utils.getOption('W', options);
if (generatorString.length() == 0) {
generatorString = J48.class.getName();
}
setPartitionGenerator((PartitionGenerator) Utils.forName(
PartitionGenerator.class, generatorString,
Utils.partitionOptions(options)));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (m_partitionGenerator != null) {
options.add("-W");
options.add(getPartitionGenerator().getClass().getName());
}
if ((m_partitionGenerator != null)
&& (m_partitionGenerator instanceof OptionHandler)) {
String[] generatorOptions = ((OptionHandler) m_partitionGenerator)
.getOptions();
if (generatorOptions.length > 0) {
options.add("--");
Collections.addAll(options, generatorOptions);
}
}
return options.toArray(new String[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 "A filter that uses a PartitionGenerator to generate partition "
+ "membership values; filtered instances are composed of these values "
+ "plus the class attribute (if set in the input data) and rendered "
+ "as sparse instances. See Section 3 of\n" + getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(TechnicalInformation.Type.INPROCEEDINGS);
result.setValue(TechnicalInformation.Field.AUTHOR, "Eibe Frank and Bernhard Pfahringer");
result.setValue(TechnicalInformation.Field.TITLE,
"Propositionalisation of Multi-instance Data Using Random Forests");
result.setValue(TechnicalInformation.Field.BOOKTITLE, "AI 2013: Advances in Artificial Intelligence");
result.setValue(TechnicalInformation.Field.YEAR, "2013");
result.setValue(TechnicalInformation.Field.PUBLISHER, "Springer");
result.setValue(TechnicalInformation.Field.PAGES, "362-373");
return result;
}
/**
* Returns a description of this option suitable for display as a tip text in
* the gui.
*
* @return description of this option
*/
public String partitionGeneratorTipText() {
return "The partition generator that will generate membership values for the instances.";
}
/**
* Set the generator for use in filtering
*
* @param newPartitionGenerator the generator to use
*/
public void setPartitionGenerator(PartitionGenerator newPartitionGenerator) {
m_partitionGenerator = newPartitionGenerator;
}
/**
* Get the generator used by this filter
*
* @return the generator used
*/
public PartitionGenerator getPartitionGenerator() {
return m_partitionGenerator;
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new PartitionMembership(), argv);
}
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/instance/ClassBalancer.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ClassBalancer.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.instance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.SimpleBatchFilter;
import weka.filters.SupervisedFilter;
import weka.filters.unsupervised.attribute.Discretize;
/**
* <!-- globalinfo-start -->
* Reweights the instances in the data so that each class has the same total weight. The total sum of weights accross all instances will be maintained. Only the weights in the first batch of data received by this filter are changed, so it can be used with the FilteredClassifier. If the class is numeric, it is discretized using equal-width discretization to establish pseudo classes for weighting.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -num-intervals <positive integer>
* The number of discretization intervals to use when the class is numeric (default of weka.attribute.unsupervised.Discretize).</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked when input format is set
* (use with caution).</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank
* @version $Revision: 10215 $
*/
public class ClassBalancer extends SimpleBatchFilter implements SupervisedFilter,
WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 6237337831221353842L;
/** number of discretization intervals to use if the class is numeric */
protected int m_NumIntervals = 10;
/**
* Gets the number of discretization intervals to use when the class is numeric.
*
* @return the number of discretization intervals
*/
@OptionMetadata(
displayName = "Number of discretization intervals",
description = "The number of discretization intervals to use when the class is numeric.",
displayOrder = 1,
commandLineParamName = "num-intervals",
commandLineParamSynopsis = "-num-intervals <int>",
commandLineParamIsFlag = false)
public int getNumIntervals() { return m_NumIntervals; }
/**
* Sets the number of discretization intervals to use.
*
* @param num the number of discretization intervals to use.
*/
public void setNumIntervals(int num) { m_NumIntervals = num; }
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Reweights the instances in the data so that each class has the same total "
+ "weight. The total sum of weights across all instances will be maintained. Only "
+ "the weights in the first batch of data received by this filter are changed, so "
+ "it can be used with the FilteredClassifier. If the class is numeric, the class is "
+ "discretized using equal-width discretization to establish pseudo classes for weighting.";
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) {
return new Instances(inputFormat, 0);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Processes the given data.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instances process(Instances instances) throws Exception {
// Only change first batch of data
if (isFirstBatchDone()) {
return new Instances(instances);
}
Instances dataToUseForMakingWeights = instances;
if (instances.classAttribute().isNumeric()) {
Discretize discretizer = new Discretize();
discretizer.setBins(m_NumIntervals);
discretizer.setIgnoreClass(true);
int[] indices = new int[] {instances.classIndex()};
discretizer.setAttributeIndicesArray(indices);
discretizer.setInputFormat(instances);
dataToUseForMakingWeights = Filter.useFilter(instances, discretizer);
}
// Calculate the sum of weights per class and in total
double[] sumOfWeightsPerClass = new double[dataToUseForMakingWeights.numClasses()];
for (int i = 0; i < dataToUseForMakingWeights.numInstances(); i++) {
Instance inst = dataToUseForMakingWeights.instance(i);
sumOfWeightsPerClass[(int)inst.classValue()] += inst.weight();
}
double sumOfWeights = Utils.sum(sumOfWeightsPerClass);
// Copy data and rescale weights
Instances result = new Instances(instances);
double factor = sumOfWeights / (double)dataToUseForMakingWeights.numClasses();
for (int i = 0; i < result.numInstances(); i++) {
result.instance(i).setWeight(factor * result.instance(i).weight() /
sumOfWeightsPerClass[(int)dataToUseForMakingWeights.instance(i).classValue()]);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 10215 $");
}
/**
* runs the filter with the given arguments
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new ClassBalancer(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/instance/Resample.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Resample.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.instance;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
import weka.gui.ProgrammaticProperty;
/**
* <!-- globalinfo-start --> Produces a random subsample of a dataset using
* either sampling with replacement or without replacement.<br/>
* The original dataset must fit entirely in memory. The number of instances in
* the generated dataset may be specified. The dataset must have a nominal class
* attribute. If not, use the unsupervised version. The filter can be made to
* maintain the class distribution in the subsample, or to bias the class
* distribution toward a uniform distribution. When used in batch mode (i.e. in
* the FilteredClassifier), subsequent batches are NOT resampled.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -Z <num>
* The size of the output dataset, as a percentage of
* the input dataset (default 100)
* </pre>
*
* <pre>
* -B <num>
* Bias factor towards uniform class distribution.
* 0 = distribution in input data -- 1 = uniform distribution.
* (default 0)
* </pre>
*
* <pre>
* -no-replacement
* Disables replacement of instances
* (default: with replacement)
* </pre>
*
* <pre>
* -V
* Inverts the selection - only available with '-no-replacement'.
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (len@reeltwo.com)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @author Eibe Frank
* @version $Revision$
*/
public class Resample extends Filter
implements SupervisedFilter, OptionHandler, Randomizable, WeightedAttributesHandler {
/** for serialization. */
static final long serialVersionUID = 7079064953548300681L;
/** The subsample size, percent of original set, default 100%. */
protected double m_SampleSizePercent = 100;
/** The random number generator seed. */
protected int m_RandomSeed = 1;
/** The degree of bias towards uniform (nominal) class distribution. */
protected double m_BiasToUniformClass = 0;
/** Whether to perform sampling with replacement or without. */
protected boolean m_NoReplacement = false;
/**
* Whether to invert the selection (only if instances are drawn WITHOUT
* replacement).
*
* @see #m_NoReplacement
*/
protected boolean m_InvertSelection = false;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Produces a random subsample of a dataset using either sampling "
+ "with replacement or without replacement.\n"
+ "The original dataset must "
+ "fit entirely in memory. The number of instances in the generated "
+ "dataset may be specified. The dataset must have a nominal class "
+ "attribute. If not, use the unsupervised version. The filter can be "
+ "made to maintain the class distribution in the subsample, or to bias "
+ "the class distribution toward a uniform distribution. When used in batch "
+ "mode (i.e. in the FilteredClassifier), subsequent batches are NOT resampled.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(5);
result.addElement(new Option(
"\tSpecify the random number seed (default 1)", "S", 1, "-S <num>"));
result.addElement(new Option(
"\tThe size of the output dataset, as a percentage of\n"
+ "\tthe input dataset (default 100)", "Z", 1, "-Z <num>"));
result.addElement(new Option(
"\tBias factor towards uniform class distribution.\n"
+ "\t0 = distribution in input data -- 1 = uniform distribution.\n"
+ "\t(default 0)", "B", 1, "-B <num>"));
result
.addElement(new Option("\tDisables replacement of instances\n"
+ "\t(default: with replacement)", "no-replacement", 0,
"-no-replacement"));
result.addElement(new Option(
"\tInverts the selection - only available with '-no-replacement'.", "V",
0, "-V"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -Z <num>
* The size of the output dataset, as a percentage of
* the input dataset (default 100)
* </pre>
*
* <pre>
* -B <num>
* Bias factor towards uniform class distribution.
* 0 = distribution in input data -- 1 = uniform distribution.
* (default 0)
* </pre>
*
* <pre>
* -no-replacement
* Disables replacement of instances
* (default: with replacement)
* </pre>
*
* <pre>
* -V
* Inverts the selection - only available with '-no-replacement'.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0) {
setRandomSeed(Integer.parseInt(tmpStr));
} else {
setRandomSeed(1);
}
tmpStr = Utils.getOption('B', options);
if (tmpStr.length() != 0) {
setBiasToUniformClass(Double.parseDouble(tmpStr));
} else {
setBiasToUniformClass(0);
}
tmpStr = Utils.getOption('Z', options);
if (tmpStr.length() != 0) {
setSampleSizePercent(Double.parseDouble(tmpStr));
} else {
setSampleSizePercent(100);
}
setNoReplacement(Utils.getFlag("no-replacement", options));
if (getNoReplacement()) {
setInvertSelection(Utils.getFlag('V', options));
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-B");
result.add("" + getBiasToUniformClass());
result.add("-S");
result.add("" + getRandomSeed());
result.add("-Z");
result.add("" + getSampleSizePercent());
if (getNoReplacement()) {
result.add("-no-replacement");
if (getInvertSelection()) {
result.add("-V");
}
}
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String biasToUniformClassTipText() {
return "Whether to use bias towards a uniform class. A value of 0 leaves the class "
+ "distribution as-is, a value of 1 ensures the class distribution is "
+ "uniform in the output data.";
}
/**
* Gets the bias towards a uniform class. A value of 0 leaves the class
* distribution as-is, a value of 1 ensures the class distributions are
* uniform in the output data.
*
* @return the current bias
*/
public double getBiasToUniformClass() {
return m_BiasToUniformClass;
}
/**
* Sets the bias towards a uniform class. A value of 0 leaves the class
* distribution as-is, a value of 1 ensures the class distributions are
* uniform in the output data.
*
* @param newBiasToUniformClass the new bias value, between 0 and 1.
*/
public void setBiasToUniformClass(double newBiasToUniformClass) {
m_BiasToUniformClass = newBiasToUniformClass;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String randomSeedTipText() {
return "Sets the random number seed for subsampling.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed(int newSeed) {
m_RandomSeed = newSeed;
}
@ProgrammaticProperty
public void setSeed(int seed) {
setRandomSeed(seed);
}
@ProgrammaticProperty
public int getSeed() {
return getRandomSeed();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String sampleSizePercentTipText() {
return "The subsample size as a percentage of the original set.";
}
/**
* Gets the subsample size as a percentage of the original set.
*
* @return the subsample size
*/
public double getSampleSizePercent() {
return m_SampleSizePercent;
}
/**
* Sets the size of the subsample, as a percentage of the original set.
*
* @param newSampleSizePercent the subsample set size, between 0 and 100.
*/
public void setSampleSizePercent(double newSampleSizePercent) {
m_SampleSizePercent = newSampleSizePercent;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String noReplacementTipText() {
return "Disables the replacement of instances.";
}
/**
* Gets whether instances are drawn with or without replacement.
*
* @return true if the replacement is disabled
*/
public boolean getNoReplacement() {
return m_NoReplacement;
}
/**
* Sets whether instances are drawn with or with out replacement.
*
* @param value if true then the replacement of instances is disabled
*/
public void setNoReplacement(boolean value) {
m_NoReplacement = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Inverts the selection (only if instances are drawn WITHOUT replacement).";
}
/**
* Gets whether selection is inverted (only if instances are drawn WIHTOUT
* replacement).
*
* @return true if the replacement is disabled
* @see #m_NoReplacement
*/
public boolean getInvertSelection() {
return m_InvertSelection;
}
/**
* Sets whether the selection is inverted (only if instances are drawn WIHTOUT
* replacement).
*
* @param value if true then selection is inverted
*/
public void setInvertSelection(boolean value) {
m_InvertSelection = value;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify 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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isFirstBatchDone()) {
// Do the subsample, and clear the input instances.
createSubsample();
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Creates a subsample of the current set of input instances. The output
* instances are pushed onto the output queue for collection.
*/
protected void createSubsample() {
Instances data = getInputFormat();
// Figure out how much data there is per class
double[] numInstancesPerClass = new double[data.numClasses()];
for (Instance instance : data) {
numInstancesPerClass[(int)instance.classValue()]++;
}
// Collect data per class
Instance[][] instancesPerClass = new Instance[data.numClasses()][];
int numActualClasses = 0;
for (int i = 0; i < data.numClasses(); i++) {
instancesPerClass[i] = new Instance[(int)numInstancesPerClass[i]];
if (numInstancesPerClass[i] > 0) {
numActualClasses++;
}
}
int[] counterPerClass = new int[data.numClasses()];
for (Instance instance : data) {
int classValue = (int)instance.classValue();
instancesPerClass[classValue][counterPerClass[classValue]++] = instance;
}
// Determine how much data we want for each class
int[] numInstancesToSample = new int[data.numClasses()];
for (int i = 0; i < data.numClasses(); i++) {
// Can't sample any data if there is no data for the class
if (numInstancesPerClass[i] == 0) {
continue;
}
// Blend observed prior and uniform prior based on user-defined blending parameter
int sampleSize = (int)((m_SampleSizePercent / 100.0) * ((1 - m_BiasToUniformClass) * numInstancesPerClass[i] +
m_BiasToUniformClass * data.numInstances() / numActualClasses));
if (getNoReplacement() && sampleSize > numInstancesPerClass[i]) {
System.err.println("WARNING: Not enough instances of " + data.classAttribute().value(i) +
" for selected value of bias parameter in supervised Resample filter when sampling without replacement.");
sampleSize = (int)numInstancesPerClass[i];
}
numInstancesToSample[i] = (int)sampleSize;
}
// Sample data
Random random = new Random(m_RandomSeed);
if (!getNoReplacement()) {
for (int i = 0; i < data.numClasses(); i++) {
int numEligible = (int)numInstancesPerClass[i];
for (int j = 0; j < numInstancesToSample[i]; j++) {
// Sampling with replacement
push(instancesPerClass[i][random.nextInt(numEligible)]);
}
}
} else {
for (int i = 0; i < data.numClasses(); i++) {
int numEligible = (int)numInstancesPerClass[i];
// Set up array of indices
int[] selected = new int[numEligible];
for (int j = 0; j < numEligible; j++) {
selected[j] = j;
}
for (int j = 0; j < numInstancesToSample[i]; j++) {
// Sampling without replacement
int chosenLocation = random.nextInt(numEligible);
int chosen = selected[chosenLocation];
numEligible--;
selected[chosenLocation] = selected[numEligible];
selected[numEligible] = chosen;
}
// Do we need to invert the selection?
if (getInvertSelection()) {
// Take the first numEligible instances
// because they have not been selected
for (int j = 0; j < numEligible; j++) {
push(instancesPerClass[i][selected[j]]);
}
} else {
// Take the elements that have been selected
for (int j = numEligible; j < (int)numInstancesPerClass[i]; j++) {
push(instancesPerClass[i][selected[j]]);
}
}
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Resample(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/instance/SpreadSubsample.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SpreadSubsample.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.instance;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Random;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Randomizable;
import weka.core.RevisionUtils;
import weka.core.UnassignedClassException;
import weka.core.UnsupportedClassTypeException;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
import weka.gui.ProgrammaticProperty;
/**
* <!-- globalinfo-start --> Produces a random subsample of a dataset. The
* original dataset must fit entirely in memory. This filter allows you to
* specify the maximum "spread" between the rarest and most common class. For
* example, you may specify that there be at most a 2:1 difference in class
* frequencies. When used in batch mode, subsequent batches are NOT resampled.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -M <num>
* The maximum class distribution spread.
* 0 = no maximum spread, 1 = uniform distribution, 10 = allow at most
* a 10:1 ratio between the classes (default 0)
* </pre>
*
* <pre>
* -W
* Adjust weights so that total weight per class is maintained.
* Individual instance weighting is not preserved. (default no
* weights adjustment
* </pre>
*
* <pre>
* -X <num>
* The maximum count for any class value (default 0 = unlimited).
* </pre>
*
* <!-- options-end -->
*
* @author Stuart Inglis (stuart@reeltwo.com)
* @version $Revision$
**/
public class SpreadSubsample extends Filter implements SupervisedFilter, OptionHandler, Randomizable, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -3947033795243930016L;
/** The random number generator seed */
private int m_RandomSeed = 1;
/** The maximum count of any class */
private int m_MaxCount;
/** True if the first batch has been done */
private double m_DistributionSpread = 0;
/**
* True if instance weights will be adjusted to maintain total weight per
* class.
*/
private boolean m_AdjustWeights = false;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Produces a random subsample of a dataset. The original dataset must " + "fit entirely in memory. This filter allows you to specify the maximum " + "\"spread\" between the rarest and most common class. For example, you may "
+ "specify that there be at most a 2:1 difference in class frequencies. " + "When used in batch mode, subsequent batches are NOT resampled.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String adjustWeightsTipText() {
return "Wether instance weights will be adjusted to maintain total weight per " + "class.";
}
/**
* Returns true if instance weights will be adjusted to maintain total weight
* per class.
*
* @return true if instance weights will be adjusted to maintain total weight
* per class.
*/
public boolean getAdjustWeights() {
return this.m_AdjustWeights;
}
/**
* Sets whether the instance weights will be adjusted to maintain total weight
* per class.
*
* @param newAdjustWeights whether to adjust weights
*/
public void setAdjustWeights(final boolean newAdjustWeights) {
this.m_AdjustWeights = newAdjustWeights;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tSpecify the random number seed (default 1)", "S", 1, "-S <num>"));
newVector.addElement(new Option("\tThe maximum class distribution spread.\n" + "\t0 = no maximum spread, 1 = uniform distribution, 10 = allow at most\n" + "\ta 10:1 ratio between the classes (default 0)", "M", 1, "-M <num>"));
newVector.addElement(new Option("\tAdjust weights so that total weight per class is maintained.\n" + "\tIndividual instance weighting is not preserved. (default no\n" + "\tweights adjustment", "W", 0, "-W"));
newVector.addElement(new Option("\tThe maximum count for any class value (default 0 = unlimited).\n", "X", 0, "-X <num>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -M <num>
* The maximum class distribution spread.
* 0 = no maximum spread, 1 = uniform distribution, 10 = allow at most
* a 10:1 ratio between the classes (default 0)
* </pre>
*
* <pre>
* -W
* Adjust weights so that total weight per class is maintained.
* Individual instance weighting is not preserved. (default no
* weights adjustment
* </pre>
*
* <pre>
* -X <num>
* The maximum count for any class value (default 0 = unlimited).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
this.setRandomSeed(Integer.parseInt(seedString));
} else {
this.setRandomSeed(1);
}
String maxString = Utils.getOption('M', options);
if (maxString.length() != 0) {
this.setDistributionSpread(Double.valueOf(maxString).doubleValue());
} else {
this.setDistributionSpread(0);
}
String maxCount = Utils.getOption('X', options);
if (maxCount.length() != 0) {
this.setMaxCount(Double.valueOf(maxCount).doubleValue());
} else {
this.setMaxCount(0);
}
this.setAdjustWeights(Utils.getFlag('W', options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-M");
options.add("" + this.getDistributionSpread());
options.add("-X");
options.add("" + this.getMaxCount());
options.add("-S");
options.add("" + this.getRandomSeed());
if (this.getAdjustWeights()) {
options.add("-W");
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String distributionSpreadTipText() {
return "The maximum class distribution spread. " + "(0 = no maximum spread, 1 = uniform distribution, 10 = allow at most a " + "10:1 ratio between the classes).";
}
/**
* Sets the value for the distribution spread
*
* @param spread the new distribution spread
*/
public void setDistributionSpread(final double spread) {
this.m_DistributionSpread = spread;
}
/**
* Gets the value for the distribution spread
*
* @return the distribution spread
*/
public double getDistributionSpread() {
return this.m_DistributionSpread;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxCountTipText() {
return "The maximum count for any class value (0 = unlimited).";
}
/**
* Sets the value for the max count
*
* @param maxcount the new max count
*/
public void setMaxCount(final double maxcount) {
this.m_MaxCount = (int) maxcount;
}
/**
* Gets the value for the max count
*
* @return the max count
*/
public double getMaxCount() {
return this.m_MaxCount;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String randomSeedTipText() {
return "Sets the random number seed for subsampling.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return this.m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed(final int newSeed) {
this.m_RandomSeed = newSeed;
}
@Override
@ProgrammaticProperty
public void setSeed(final int seed) {
this.setRandomSeed(seed);
}
@Override
@ProgrammaticProperty
public int getSeed() {
return this.getRandomSeed();
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_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 UnassignedClassException if no class attribute has been set.
* @throws UnsupportedClassTypeException if the class attribute is not
* nominal.
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isFirstBatchDone()) {
this.push(instance);
return true;
} else {
this.bufferInput(instance);
return false;
}
}
/**
* Signify 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 InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!this.isFirstBatchDone()) {
// Do the subsample, and clear the input instances.
this.createSubsample();
}
this.flushInput();
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
return (this.numPendingOutput() != 0);
}
/**
* Creates a subsample of the current set of input instances. The output
* instances are pushed onto the output queue for collection.
* @throws InterruptedException
*/
private void createSubsample() throws InterruptedException {
int classI = this.getInputFormat().classIndex();
// Sort according to class attribute.
this.getInputFormat().sort(classI);
// Determine where each class starts in the sorted dataset
int[] classIndices = this.getClassIndices();
// Get the existing class distribution
int[] counts = new int[this.getInputFormat().numClasses()];
double[] weights = new double[this.getInputFormat().numClasses()];
int min = -1;
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
Instance current = this.getInputFormat().instance(i);
if (current.classIsMissing() == false) {
counts[(int) current.classValue()]++;
weights[(int) current.classValue()] += current.weight();
}
}
// Convert from total weight to average weight
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0) {
weights[i] = weights[i] / counts[i];
}
/*
* System.err.println("Class:" + i + " " +
* getInputFormat().classAttribute().value(i) + " Count:" + counts[i] +
* " Total:" + weights[i] * counts[i] + " Avg:" + weights[i]);
*/
}
// find the class with the minimum number of instances
int minIndex = -1;
for (int i = 0; i < counts.length; i++) {
if ((min < 0) && (counts[i] > 0)) {
min = counts[i];
minIndex = i;
} else if ((counts[i] < min) && (counts[i] > 0)) {
min = counts[i];
minIndex = i;
}
}
if (min < 0) {
System.err.println("SpreadSubsample: *warning* none of the classes have any values in them.");
return;
}
// determine the new distribution
int[] new_counts = new int[this.getInputFormat().numClasses()];
for (int i = 0; i < counts.length; i++) {
new_counts[i] = (int) Math.abs(Math.min(counts[i], min * this.m_DistributionSpread));
if (i == minIndex) {
if (this.m_DistributionSpread > 0 && this.m_DistributionSpread < 1.0) {
// don't undersample the minority class!
new_counts[i] = counts[i];
}
}
if (this.m_DistributionSpread == 0) {
new_counts[i] = counts[i];
}
if (this.m_MaxCount > 0) {
new_counts[i] = Math.min(new_counts[i], this.m_MaxCount);
}
}
// Sample without replacement
Random random = new Random(this.m_RandomSeed);
Hashtable<String, String> t = new Hashtable<String, String>();
for (int j = 0; j < new_counts.length; j++) {
double newWeight = 1.0;
if (this.m_AdjustWeights && (new_counts[j] > 0)) {
newWeight = weights[j] * counts[j] / new_counts[j];
/*
* System.err.println("Class:" + j + " " +
* getInputFormat().classAttribute().value(j) + " Count:" + counts[j] +
* " Total:" + weights[j] * counts[j] + " Avg:" + weights[j] +
* " NewCount:" + new_counts[j] + " NewAvg:" + newWeight);
*/
}
for (int k = 0; k < new_counts[j]; k++) {
boolean ok = false;
do {
int index = classIndices[j] + random.nextInt(classIndices[j + 1] - classIndices[j]);
// Have we used this instance before?
if (t.get("" + index) == null) {
// if not, add it to the hashtable and use it
t.put("" + index, "");
ok = true;
if (index >= 0) {
Instance newInst = (Instance) this.getInputFormat().instance(index).copy();
if (this.m_AdjustWeights) {
newInst.setWeight(newWeight);
}
this.push(newInst, false); // No need to copy instance
}
}
} while (!ok);
}
}
}
/**
* Creates an index containing the position where each class starts in the
* getInputFormat(). m_InputFormat must be sorted on the class attribute.
*
* @return the positions
*/
private int[] getClassIndices() {
// Create an index of where each class value starts
int[] classIndices = new int[this.getInputFormat().numClasses() + 1];
int currentClass = 0;
classIndices[currentClass] = 0;
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
Instance current = this.getInputFormat().instance(i);
if (current.classIsMissing()) {
for (int j = currentClass + 1; j < classIndices.length; j++) {
classIndices[j] = i;
}
break;
} else if (current.classValue() != currentClass) {
for (int j = currentClass + 1; j <= current.classValue(); j++) {
classIndices[j] = i;
}
currentClass = (int) current.classValue();
}
}
if (currentClass <= this.getInputFormat().numClasses()) {
for (int j = currentClass + 1; j < classIndices.length; j++) {
classIndices[j] = this.getInputFormat().numInstances();
}
}
return classIndices;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new SpreadSubsample(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/supervised/instance/StratifiedRemoveFolds.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* StratifiedRemoveFolds.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.supervised.instance;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
* <!-- globalinfo-start --> This filter takes a dataset and outputs a specified
* fold for cross validation. If you do not want the folds to be stratified use
* the unsupervised version.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <pre>
* -N <number of folds>
* Specifies number of folds dataset is split into.
* (default 10)
* </pre>
*
* <pre>
* -F <fold>
* Specifies which fold is selected. (default 1)
* </pre>
*
* <pre>
* -S <seed>
* Specifies random number seed. (default 0, no randomizing)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class StratifiedRemoveFolds extends Filter implements SupervisedFilter, OptionHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -7069148179905814324L;
/** Indicates if inverse of selection is to be output. */
private boolean m_Inverse = false;
/** Number of folds to split dataset into */
private int m_NumFolds = 10;
/** Fold to output */
private int m_Fold = 1;
/** Random number seed. */
private long m_Seed = 0;
/**
* Gets an enumeration describing the available options..
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tSpecifies if inverse of selection is to be output.\n", "V", 0, "-V"));
newVector.addElement(new Option("\tSpecifies number of folds dataset is split into. \n" + "\t(default 10)\n", "N", 1, "-N <number of folds>"));
newVector.addElement(new Option("\tSpecifies which fold is selected. (default 1)\n", "F", 1, "-F <fold>"));
newVector.addElement(new Option("\tSpecifies random number seed. (default 0, no randomizing)\n", "S", 1, "-S <seed>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <pre>
* -N <number of folds>
* Specifies number of folds dataset is split into.
* (default 10)
* </pre>
*
* <pre>
* -F <fold>
* Specifies which fold is selected. (default 1)
* </pre>
*
* <pre>
* -S <seed>
* Specifies random number seed. (default 0, no randomizing)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setInvertSelection(Utils.getFlag('V', options));
String numFolds = Utils.getOption('N', options);
if (numFolds.length() != 0) {
this.setNumFolds(Integer.parseInt(numFolds));
} else {
this.setNumFolds(10);
}
String fold = Utils.getOption('F', options);
if (fold.length() != 0) {
this.setFold(Integer.parseInt(fold));
} else {
this.setFold(1);
}
String seed = Utils.getOption('S', options);
if (seed.length() != 0) {
this.setSeed(Integer.parseInt(seed));
} else {
this.setSeed(0);
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-S");
options.add("" + this.getSeed());
if (this.getInvertSelection()) {
options.add("-V");
}
options.add("-N");
options.add("" + this.getNumFolds());
options.add("-F");
options.add("" + this.getFold());
return options.toArray(new String[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 "This filter takes a dataset and outputs a specified fold for " + "cross validation. If you do not want the folds to be stratified " + "use the unsupervised version.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to invert the selection.";
}
/**
* Gets if selection is to be inverted.
*
* @return true if the selection is to be inverted
*/
public boolean getInvertSelection() {
return this.m_Inverse;
}
/**
* Sets if selection is to be inverted.
*
* @param inverse true if inversion is to be performed
*/
public void setInvertSelection(final boolean inverse) {
this.m_Inverse = inverse;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numFoldsTipText() {
return "The number of folds to split the dataset into.";
}
/**
* Gets the number of folds in which dataset is to be split into.
*
* @return the number of folds the dataset is to be split into.
*/
public int getNumFolds() {
return this.m_NumFolds;
}
/**
* Sets the number of folds the dataset is split into. If the number of folds
* is zero, it won't split it into folds.
*
* @param numFolds number of folds dataset is to be split into
* @throws IllegalArgumentException if number of folds is negative
*/
public void setNumFolds(final int numFolds) {
if (numFolds < 0) {
throw new IllegalArgumentException("Number of folds has to be positive or zero.");
}
this.m_NumFolds = numFolds;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String foldTipText() {
return "The fold which is selected.";
}
/**
* Gets the fold which is selected.
*
* @return the fold which is selected
*/
public int getFold() {
return this.m_Fold;
}
/**
* Selects a fold.
*
* @param fold the fold to be selected.
* @throws IllegalArgumentException if fold's index is smaller than 1
*/
public void setFold(final int fold) {
if (fold < 1) {
throw new IllegalArgumentException("Fold's index has to be greater than 0.");
}
this.m_Fold = fold;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "the random number seed for shuffling the dataset. If seed is negative, shuffling will not be performed.";
}
/**
* Gets the random number seed used for shuffling the dataset.
*
* @return the random number seed
*/
public long getSeed() {
return this.m_Seed;
}
/**
* Sets the random number seed for shuffling the dataset. If seed is negative,
* shuffling won't be performed.
*
* @param seed the random number seed
*/
public void setSeed(final long seed) {
this.m_Seed = seed;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 because outputFormat can be collected immediately
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
if ((this.m_NumFolds > 0) && (this.m_NumFolds < this.m_Fold)) {
throw new IllegalArgumentException("Fold has to be smaller or equal to " + "number of folds.");
}
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isFirstBatchDone()) {
this.push(instance);
return true;
} else {
this.bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished. Output() may
* now be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @throws InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
Instances instances;
if (!this.isFirstBatchDone()) {
if (this.m_Seed > 0) {
// User has provided a random number seed.
this.getInputFormat().randomize(new Random(this.m_Seed));
}
// Select out a fold
this.getInputFormat().stratify(this.m_NumFolds);
if (!this.m_Inverse) {
instances = this.getInputFormat().testCV(this.m_NumFolds, this.m_Fold - 1);
} else {
instances = this.getInputFormat().trainCV(this.m_NumFolds, this.m_Fold - 1);
}
} else {
instances = this.getInputFormat();
}
this.flushInput();
for (int i = 0; i < instances.numInstances(); i++) {
this.push(instances.instance(i), false); // No need to copy instance
}
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new StratifiedRemoveFolds(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AbstractTimeSeries.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AbstractTimeSeries.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* An abstract instance filter that assumes instances form time-series data and
* performs some merging of attribute values in the current instance with
* attribute attribute values of some previous (or future) instance. For
* instances where the desired value is unknown either the instance may be
* dropped, or missing values used.
* <p>
*
* Valid filter-specific options are:
* <p>
*
* -R index1,index2-index4,...<br>
* Specify list of columns to calculate new values for. First and last are valid
* indexes. (default none)
* <p>
*
* -V <br>
* Invert matching sense (i.e. calculate for all non-specified columns)
* <p>
*
* -I num <br>
* The number of instances forward to merge values between. A negative number
* indicates taking values from a past instance. (default -1)
* <p>
*
* -M <br>
* For instances at the beginning or end of the dataset where the translated
* values are not known, remove those instances (default is to use missing
* values).
* <p>
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class AbstractTimeSeries extends Filter implements
UnsupervisedFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -3795656792078022357L;
/** Stores which columns to copy */
protected Range m_SelectedCols = new Range();
/**
* True if missing values should be used rather than removing instances where
* the translated value is not known (due to border effects).
*/
protected boolean m_FillWithMissing = true;
/**
* The number of instances forward to translate values between. A negative
* number indicates taking values from a past instance.
*/
protected int m_InstanceRange = -1;
/** Stores the historical instances to copy values between */
protected Queue m_History;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option(
"\tSpecify list of columns to translate in time. First and\n"
+ "\tlast are valid indexes. (default none)", "R", 1,
"-R <index1,index2-index4,...>"));
newVector.addElement(new Option(
"\tInvert matching sense (i.e. calculate for all non-specified columns)",
"V", 0, "-V"));
newVector.addElement(new Option(
"\tThe number of instances forward to translate values\n"
+ "\tbetween. A negative number indicates taking values from\n"
+ "\ta past instance. (default -1)", "I", 1, "-I <num>"));
newVector.addElement(new Option(
"\tFor instances at the beginning or end of the dataset where\n"
+ "\tthe translated values are not known, remove those instances\n"
+ "\t(default is to use missing values).", "M", 0, "-M"));
return newVector.elements();
}
/**
* Parses a given list of options controlling the behaviour of this object.
* Valid options are:
* <p>
*
* -R index1,index2-index4,...<br>
* Specify list of columns to copy. First and last are valid indexes. (default
* none)
* <p>
*
* -V<br>
* Invert matching sense (i.e. calculate for all non-specified columns)
* <p>
*
* -I num <br>
* The number of instances forward to translate values between. A negative
* number indicates taking values from a past instance. (default -1)
* <p>
*
* -M <br>
* For instances at the beginning or end of the dataset where the translated
* values are not known, remove those instances (default is to use missing
* values).
* <p>
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String copyList = Utils.getOption('R', options);
if (copyList.length() != 0) {
setAttributeIndices(copyList);
} else {
setAttributeIndices("");
}
setInvertSelection(Utils.getFlag('V', options));
setFillWithMissing(!Utils.getFlag('M', options));
String instanceRange = Utils.getOption('I', options);
if (instanceRange.length() != 0) {
setInstanceRange(Integer.parseInt(instanceRange));
} else {
setInstanceRange(-1);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
if (getInvertSelection()) {
options.add("-V");
}
options.add("-I");
options.add("" + getInstanceRange());
if (!getFillWithMissing()) {
options.add("-M");
}
return options.toArray(new String[0]);
}
/**
* 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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
resetHistory();
m_SelectedCols.setUpper(instanceInfo.numAttributes() - 1);
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 Exception if the input instance was not of the correct format or if
* there was a problem with the filtering.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new NullPointerException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
resetHistory();
}
Instance newInstance = historyInput(instance);
if (newInstance != null) {
push(newInstance);
return true;
} else {
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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (getFillWithMissing() && (m_InstanceRange > 0)) {
while (!m_History.empty()) {
push(mergeInstances(null, (Instance) m_History.pop()));
}
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String fillWithMissingTipText() {
return "For instances at the beginning or end of the dataset where the translated "
+ "values are not known, use missing values (default is to remove those "
+ "instances)";
}
/**
* Gets whether missing values should be used rather than removing instances
* where the translated value is not known (due to border effects).
*
* @return true if so
*/
public boolean getFillWithMissing() {
return m_FillWithMissing;
}
/**
* Sets whether missing values should be used rather than removing instances
* where the translated value is not known (due to border effects).
*
* @param newFillWithMissing true if so
*/
public void setFillWithMissing(boolean newFillWithMissing) {
m_FillWithMissing = newFillWithMissing;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String instanceRangeTipText() {
return "The number of instances forward/backward to merge values between. "
+ "A negative number indicates taking values from a past instance.";
}
/**
* Gets the number of instances forward to translate values between. A
* negative number indicates taking values from a past instance.
*
* @return Value of InstanceRange.
*/
public int getInstanceRange() {
return m_InstanceRange;
}
/**
* Sets the number of instances forward to translate values between. A
* negative number indicates taking values from a past instance.
*
* @param newInstanceRange Value to assign to InstanceRange.
*/
public void setInstanceRange(int newInstanceRange) {
m_InstanceRange = newInstanceRange;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Invert matching sense. ie calculate for all non-specified columns.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_SelectedCols.getInvert();
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are copied. If false
* selected columns are copied and unselected columns are kept.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_SelectedCols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_SelectedCols.getRanges();
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String rangeList) {
m_SelectedCols.setRanges(rangeList);
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/** Clears any instances from the history queue. */
protected void resetHistory() {
if (m_History == null) {
m_History = new Queue();
} else {
m_History.removeAllElements();
}
}
/**
* Adds an instance to the history buffer. If enough instances are in the
* buffer, a new instance may be output, with selected attribute values copied
* from one to another.
*
* @param instance the input instance
* @return a new instance with translated values, or null if no output
* instance is produced
*/
protected Instance historyInput(Instance instance) {
m_History.push(instance);
if (m_History.size() <= Math.abs(m_InstanceRange)) {
if (getFillWithMissing() && (m_InstanceRange < 0)) {
return mergeInstances(null, instance);
} else {
return null;
}
}
if (m_InstanceRange < 0) {
return mergeInstances((Instance) m_History.pop(), instance);
} else {
return mergeInstances(instance, (Instance) m_History.pop());
}
}
/**
* Creates a new instance the same as one instance (the "destination") but
* with some attribute values copied from another instance (the "source")
*
* @param source the source instance
* @param dest the destination instance
* @return the new merged instance
*/
protected abstract Instance mergeInstances(Instance source, Instance dest);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Add.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Add.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that adds a new attribute to the
* dataset. The new attribute will contain all missing values.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -T <NUM|NOM|STR|DAT>
* The type of attribute to create:
* NUM = Numeric attribute
* NOM = Nominal attribute
* STR = String attribute
* DAT = Date attribute
* (default: NUM)
* </pre>
*
* <pre>
* -C <index>
* Specify where to insert the column. First and last
* are valid indexes.(default: last)
* </pre>
*
* <pre>
* -N <name>
* Name of the new attribute.
* (default: 'Unnamed')
* </pre>
*
* <pre>
* -L <label1,label2,...>
* Create nominal attribute with given labels
* (default: numeric attribute)
* </pre>
*
* <pre>
* -F <format>
* The format of the date values (see ISO-8601)
* (default: yyyy-MM-dd'T'HH:mm:ss)
* </pre>
*
* <pre>
* -W <double>
* The weight for the new attribute (default: 1.0)
* </pre>
* *
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Add extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
static final long serialVersionUID = 761386447332932389L;
/** the attribute type. */
public static final Tag[] TAGS_TYPE = {
new Tag(Attribute.NUMERIC, "NUM", "Numeric attribute"),
new Tag(Attribute.NOMINAL, "NOM", "Nominal attribute"),
new Tag(Attribute.STRING, "STR", "String attribute"),
new Tag(Attribute.DATE, "DAT", "Date attribute") };
/** Record the type of attribute to insert. */
protected int m_AttributeType = Attribute.NUMERIC;
/** The name for the new attribute. */
protected String m_Name = "unnamed";
/** The location to insert the new attribute. */
private final SingleIndex m_Insert = new SingleIndex("last");
/** The list of labels for nominal attribute. */
protected ArrayList<String> m_Labels = new ArrayList<String>();
/** The date format. */
protected String m_DateFormat = "yyyy-MM-dd'T'HH:mm:ss";
/** The weight for the new attribute. */
protected double m_Weight = 1.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 adds a new attribute to the dataset."
+ " The new attribute will contain all missing values.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector;
String desc;
SelectedTag tag;
int i;
newVector = new Vector<Option>();
desc = "";
for (i = 0; i < TAGS_TYPE.length; i++) {
tag = new SelectedTag(TAGS_TYPE[i].getID(), TAGS_TYPE);
desc += "\t" + tag.getSelectedTag().getIDStr() + " = "
+ tag.getSelectedTag().getReadable() + "\n";
}
newVector.addElement(new Option("\tThe type of attribute to create:\n"
+ desc + "\t(default: " + new SelectedTag(Attribute.NUMERIC, TAGS_TYPE)
+ ")", "T", 1, "-T " + Tag.toOptionList(TAGS_TYPE)));
newVector.addElement(new Option(
"\tSpecify where to insert the column. First and last\n"
+ "\tare valid indexes.(default: last)", "C", 1, "-C <index>"));
newVector.addElement(new Option("\tName of the new attribute.\n"
+ "\t(default: 'Unnamed')", "N", 1, "-N <name>"));
newVector.addElement(new Option(
"\tCreate nominal attribute with given labels\n"
+ "\t(default: numeric attribute)", "L", 1, "-L <label1,label2,...>"));
newVector.addElement(new Option(
"\tThe format of the date values (see ISO-8601)\n"
+ "\t(default: yyyy-MM-dd'T'HH:mm:ss)", "F", 1, "-F <format>"));
newVector.addElement(new Option(
"\tThe weight for the new attribute\n"
+ "\t(default: 1.0)", "W", 1, "-W <double>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -T <NUM|NOM|STR|DAT>
* The type of attribute to create:
* NUM = Numeric attribute
* NOM = Nominal attribute
* STR = String attribute
* DAT = Date attribute
* (default: NUM)
* </pre>
*
* <pre>
* -C <index>
* Specify where to insert the column. First and last
* are valid indexes.(default: last)
* </pre>
*
* <pre>
* -N <name>
* Name of the new attribute.
* (default: 'Unnamed')
* </pre>
*
* <pre>
* -L <label1,label2,...>
* Create nominal attribute with given labels
* (default: numeric attribute)
* </pre>
*
* <pre>
* -F <format>
* The format of the date values (see ISO-8601)
* (default: yyyy-MM-dd'T'HH:mm:ss)
* </pre>
*
* <pre>
* -W <double>
* The weight for the new attribute (default: 1.0)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('T', options);
if (tmpStr.length() != 0) {
setAttributeType(new SelectedTag(tmpStr, TAGS_TYPE));
} else {
setAttributeType(new SelectedTag(Attribute.NUMERIC, TAGS_TYPE));
}
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() == 0) {
tmpStr = "last";
}
setAttributeIndex(tmpStr);
setAttributeName(Utils.unbackQuoteChars(Utils.getOption('N', options)));
if (m_AttributeType == Attribute.NOMINAL) {
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0) {
setNominalLabels(tmpStr);
}
} else if (m_AttributeType == Attribute.DATE) {
tmpStr = Utils.getOption('F', options);
if (tmpStr.length() != 0) {
setDateFormat(tmpStr);
}
}
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() == 0) {
setWeight(1.0);
} else {
setWeight(Double.parseDouble(tmpStr));
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
if (m_AttributeType != Attribute.NUMERIC) {
result.add("-T");
result.add("" + getAttributeType());
}
result.add("-N");
result.add(Utils.backQuoteChars(getAttributeName()));
if (m_AttributeType == Attribute.NOMINAL) {
result.add("-L");
result.add(getNominalLabels());
} else if (m_AttributeType == Attribute.NOMINAL) {
result.add("-F");
result.add(getDateFormat());
}
result.add("-C");
result.add("" + getAttributeIndex());
result.add("-W");
result.add("" + getWeight());
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_Insert.setUpper(instanceInfo.numAttributes());
Instances outputFormat = new Instances(instanceInfo, 0);
Attribute newAttribute = null;
switch (m_AttributeType) {
case Attribute.NUMERIC:
newAttribute = new Attribute(m_Name);
break;
case Attribute.NOMINAL:
newAttribute = new Attribute(m_Name, m_Labels);
break;
case Attribute.STRING:
newAttribute = new Attribute(m_Name, (ArrayList<String>) null);
break;
case Attribute.DATE:
newAttribute = new Attribute(m_Name, m_DateFormat);
break;
default:
throw new IllegalArgumentException("Unknown attribute type in Add");
}
newAttribute.setWeight(getWeight());
if ((m_Insert.getIndex() < 0)
|| (m_Insert.getIndex() > getInputFormat().numAttributes())) {
throw new IllegalArgumentException("Index out of range");
}
outputFormat.insertAttributeAt(newAttribute, m_Insert.getIndex());
setOutputFormat(outputFormat);
// all attributes, except index of added attribute
// (otherwise the length of the input/output indices differ)
Range atts = new Range(m_Insert.getSingleIndex());
atts.setInvert(true);
atts.setUpper(outputFormat.numAttributes() - 1);
initOutputLocators(outputFormat, atts.getSelection());
return true;
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instance inst = (Instance) instance.copy();
// First copy string values from input to output
copyValues(inst, true, inst.dataset(), outputFormatPeek());
// Insert the new attribute and reassign to output
inst.setDataset(null);
inst.insertAttributeAt(m_Insert.getIndex());
push(inst); // No need to copy instance
return true;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeNameTipText() {
return "Set the new attribute's name.";
}
/**
* Get the name of the attribute to be created.
*
* @return the new attribute name
*/
public String getAttributeName() {
return m_Name;
}
/**
* Set the new attribute's name.
*
* @param name the new name
*/
public void setAttributeName(String name) {
if (name.trim().equals("")) {
m_Name = "unnamed";
} else {
m_Name = name;
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "The position (starting from 1) where the attribute will be inserted "
+ "(first and last are valid indices).";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_Insert.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_Insert.setSingleIndex(attIndex);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String weightTipText() {
return "The weight for the new attribute.";
}
/**
* Get the weight of the attribute used.
*
* @return the weight of the attribute
*/
public double getWeight() {
return m_Weight;
}
/**
* Sets weight of the attribute used.
*
* @param weight the weight of the attribute
*/
public void setWeight(double weight) {
m_Weight = weight;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String nominalLabelsTipText() {
return "The list of value labels (nominal attribute creation only). "
+ " The list must be comma-separated, eg: \"red,green,blue\"."
+ " If this is empty, the created attribute will be numeric.";
}
/**
* Get the list of labels for nominal attribute creation.
*
* @return the list of labels for nominal attribute creation
*/
public String getNominalLabels() {
String labelList = "";
for (int i = 0; i < m_Labels.size(); i++) {
if (i == 0) {
labelList = m_Labels.get(i);
} else {
labelList += "," + m_Labels.get(i);
}
}
return labelList;
}
/**
* Set the labels for nominal attribute creation.
*
* @param labelList a comma separated list of labels
* @throws IllegalArgumentException if the labelList was invalid
*/
public void setNominalLabels(String labelList) {
ArrayList<String> labels = new ArrayList<String>(10);
// Split the labelList up into the vector
int commaLoc;
while ((commaLoc = labelList.indexOf(',')) >= 0) {
String label = labelList.substring(0, commaLoc).trim();
if (!label.equals("")) {
labels.add(label);
} else {
throw new IllegalArgumentException("Invalid label list at "
+ labelList.substring(commaLoc));
}
labelList = labelList.substring(commaLoc + 1);
}
String label = labelList.trim();
if (!label.equals("")) {
labels.add(label);
}
// If everything is OK, make the type change
m_Labels = labels;
if (labels.size() == 0) {
m_AttributeType = Attribute.NUMERIC;
} else {
m_AttributeType = Attribute.NOMINAL;
}
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeTypeTipText() {
return "Defines the type of the attribute to generate.";
}
/**
* Sets the type of attribute to generate.
*
* @param value the attribute type
*/
public void setAttributeType(SelectedTag value) {
if (value.getTags() == TAGS_TYPE) {
m_AttributeType = value.getSelectedTag().getID();
}
}
/**
* Gets the type of attribute to generate.
*
* @return the current attribute type.
*/
public SelectedTag getAttributeType() {
return new SelectedTag(m_AttributeType, TAGS_TYPE);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dateFormatTipText() {
return "The format of the date values (see ISO-8601).";
}
/**
* Get the date format, complying to ISO-8601.
*
* @return the date format
*/
public String getDateFormat() {
return m_DateFormat;
}
/**
* Set the date format, complying to ISO-8601.
*
* @param value a comma separated list of labels
*/
public void setDateFormat(String value) {
try {
new SimpleDateFormat(value);
m_DateFormat = value;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Add(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddCluster.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddCluster.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.clusterers.AbstractClusterer;
import weka.clusterers.Clusterer;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that adds a new nominal attribute
* representing the cluster assigned to each instance by the specified
* clustering algorithm.<br/>
* Either the clustering algorithm gets built with the first batch of data or
* one specifies are serialized clusterer model file to use instead.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <clusterer specification>
* Full class name of clusterer to use, followed
* by scheme options. eg:
* "weka.clusterers.SimpleKMeans -N 3"
* (default: weka.clusterers.SimpleKMeans)
* </pre>
*
* <pre>
* -serialized <file>
* Instead of building a clusterer on the data, one can also provide
* a serialized model and use that for adding the clusters.
* </pre>
*
* <pre>
* -I <att1,att2-att4,...>
* The range of attributes the clusterer should ignore.
* </pre>
*
* <!-- options-end -->
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class AddCluster extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization. */
static final long serialVersionUID = 7414280611943807337L;
/** The clusterer used to do the cleansing. */
protected Clusterer m_Clusterer = new weka.clusterers.SimpleKMeans();
/** The file from which to load a serialized clusterer. */
protected File m_SerializedClustererFile = new File(
System.getProperty("user.dir"));
/** The actual clusterer used to do the clustering. */
protected Clusterer m_ActualClusterer = null;
/** Range of attributes to ignore. */
protected Range m_IgnoreAttributesRange = null;
/** Filter for removing attributes. */
protected Filter m_removeAttributes = new Remove();
/**
* Returns the Capabilities of this filter, makes sure that the class is never
* set (for the clusterer).
*
* @param data the data to use for customization
* @return the capabilities of this object, based on the data
* @see #getCapabilities()
*/
@Override
public Capabilities getCapabilities(Instances data) {
Instances newData;
newData = new Instances(data, 0);
newData.setClassIndex(-1);
return super.getCapabilities(newData);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = m_Clusterer.getCapabilities();
result.enableAllClasses();
result.setMinimumNumberInstances(0);
return result;
}
/**
* tests the data whether the filter can actually handle it.
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
@Override
protected void testInputFormat(Instances instanceInfo) throws Exception {
getCapabilities(instanceInfo).testWithFail(removeIgnored(instanceInfo));
}
/**
* 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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_removeAttributes = null;
return false;
}
/**
* filters all attributes that should be ignored.
*
* @param data the data to filter
* @return the filtered data
* @throws Exception if filtering fails
*/
protected Instances removeIgnored(Instances data) throws Exception {
Instances result = data;
if (m_IgnoreAttributesRange != null || data.classIndex() >= 0) {
m_removeAttributes = new Remove();
String rangeString = "";
if (m_IgnoreAttributesRange != null) {
rangeString += m_IgnoreAttributesRange.getRanges();
}
if (data.classIndex() >= 0) {
if (rangeString.length() > 0) {
rangeString += "," + (data.classIndex() + 1);
} else {
rangeString = "" + (data.classIndex() + 1);
}
}
((Remove) m_removeAttributes).setAttributeIndices(rangeString);
((Remove) m_removeAttributes).setInvertSelection(false);
m_removeAttributes.setInputFormat(data);
result = Filter.useFilter(data, m_removeAttributes);
}
return result;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
Instances toFilter = getInputFormat();
if (!isFirstBatchDone()) {
// filter out attributes if necessary
Instances toFilterIgnoringAttributes = removeIgnored(toFilter);
// serialized model or build clusterer from scratch?
File file = getSerializedClustererFile();
if (!file.isDirectory()) {
ObjectInputStream ois = //new ObjectInputStream(new FileInputStream(file));
SerializationHelper.getObjectInputStream(new FileInputStream(file));
m_ActualClusterer = (Clusterer) ois.readObject();
Instances header = null;
// let's see whether there's an Instances header stored as well
try {
header = (Instances) ois.readObject();
} catch (Exception e) {
// ignored
}
ois.close();
// same dataset format?
if ((header != null)
&& (!header.equalHeaders(toFilterIgnoringAttributes))) {
throw new WekaException(
"Training header of clusterer and filter dataset don't match:\n"
+ header.equalHeadersMsg(toFilterIgnoringAttributes));
}
} else {
m_ActualClusterer = AbstractClusterer.makeCopy(m_Clusterer);
m_ActualClusterer.buildClusterer(toFilterIgnoringAttributes);
}
// create output dataset with new attribute
Instances filtered = new Instances(toFilter, 0);
ArrayList<String> nominal_values = new ArrayList<String>(
m_ActualClusterer.numberOfClusters());
for (int i = 0; i < m_ActualClusterer.numberOfClusters(); i++) {
nominal_values.add("cluster" + (i + 1));
}
filtered.insertAttributeAt(new Attribute("cluster", nominal_values),
filtered.numAttributes());
setOutputFormat(filtered);
}
// build new dataset
for (int i = 0; i < toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
* @throws Exception if something goes wrong
*/
protected void convertInstance(Instance instance) throws Exception {
Instance original, processed;
original = instance;
// copy values
double[] instanceVals = new double[instance.numAttributes() + 1];
for (int j = 0; j < instance.numAttributes(); j++) {
instanceVals[j] = original.value(j);
}
Instance filteredI = null;
if (m_removeAttributes != null) {
m_removeAttributes.input(instance);
filteredI = m_removeAttributes.output();
} else {
filteredI = instance;
}
// add cluster to end
try {
instanceVals[instance.numAttributes()] = m_ActualClusterer
.clusterInstance(filteredI);
} catch (Exception e) {
// clusterer couldn't cluster instance -> missing
instanceVals[instance.numAttributes()] = Utils.missingValue();
}
// create new instance
if (original instanceof SparseInstance) {
processed = new SparseInstance(original.weight(), instanceVals);
} else {
processed = new DenseInstance(original.weight(), instanceVals);
}
copyValues(processed, false, instance.dataset(), outputFormatPeek());
push(processed); // No need to copy instance
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(3);
result.addElement(new Option(
"\tFull class name of clusterer to use, followed\n"
+ "\tby scheme options. eg:\n"
+ "\t\t\"weka.clusterers.SimpleKMeans -N 3\"\n"
+ "\t(default: weka.clusterers.SimpleKMeans)", "W", 1,
"-W <clusterer specification>"));
result.addElement(new Option(
"\tInstead of building a clusterer on the data, one can also provide\n"
+ "\ta serialized model and use that for adding the clusters.",
"serialized", 1, "-serialized <file>"));
result.addElement(new Option(
"\tThe range of attributes the clusterer should ignore.\n", "I", 1,
"-I <att1,att2-att4,...>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <clusterer specification>
* Full class name of clusterer to use, followed
* by scheme options. eg:
* "weka.clusterers.SimpleKMeans -N 3"
* (default: weka.clusterers.SimpleKMeans)
* </pre>
*
* <pre>
* -serialized <file>
* Instead of building a clusterer on the data, one can also provide
* a serialized model and use that for adding the clusters.
* </pre>
*
* <pre>
* -I <att1,att2-att4,...>
* The range of attributes the clusterer should ignore.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
String[] tmpOptions;
File file;
boolean serializedModel;
serializedModel = false;
tmpStr = Utils.getOption("serialized", options);
if (tmpStr.length() != 0) {
file = new File(tmpStr);
if (!file.exists()) {
throw new FileNotFoundException("File '" + file.getAbsolutePath()
+ "' not found!");
}
if (file.isDirectory()) {
throw new FileNotFoundException("'" + file.getAbsolutePath()
+ "' points to a directory not a file!");
}
setSerializedClustererFile(file);
serializedModel = true;
} else {
setSerializedClustererFile(null);
}
if (!serializedModel) {
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() == 0) {
tmpStr = weka.clusterers.SimpleKMeans.class.getName();
}
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length == 0) {
throw new Exception("Invalid clusterer specification string");
}
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setClusterer(AbstractClusterer.forName(tmpStr, tmpOptions));
}
setIgnoredAttributeIndices(Utils.getOption('I', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
File file;
result = new Vector<String>();
file = getSerializedClustererFile();
if ((file != null) && (!file.isDirectory())) {
result.add("-serialized");
result.add(file.getAbsolutePath());
} else {
result.add("-W");
result.add(getClustererSpec());
}
if (!getIgnoredAttributeIndices().equals("")) {
result.add("-I");
result.add(getIgnoredAttributeIndices());
}
return result.toArray(new String[result.size()]);
}
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that adds a new nominal attribute representing the cluster "
+ "assigned to each instance by the specified clustering algorithm.\n"
+ "Either the clustering algorithm gets built with the first batch of "
+ "data or one specifies are serialized clusterer model file to use "
+ "instead.";
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String clustererTipText() {
return "The clusterer to assign clusters with.";
}
/**
* Sets the clusterer to assign clusters with.
*
* @param clusterer The clusterer to be used (with its options set).
*/
public void setClusterer(Clusterer clusterer) {
m_Clusterer = clusterer;
}
/**
* Gets the clusterer used by the filter.
*
* @return The clusterer being used.
*/
public Clusterer getClusterer() {
return m_Clusterer;
}
/**
* Gets the clusterer specification string, which contains the class name of
* the clusterer and any options to the clusterer.
*
* @return the clusterer string.
*/
protected String getClustererSpec() {
Clusterer c = getClusterer();
if (c instanceof OptionHandler) {
return c.getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler) c).getOptions());
}
return c.getClass().getName();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoredAttributeIndicesTipText() {
return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last";
}
/**
* Gets ranges of attributes to be ignored.
*
* @return a string containing a comma-separated list of ranges
*/
public String getIgnoredAttributeIndices() {
if (m_IgnoreAttributesRange == null) {
return "";
} else {
return m_IgnoreAttributesRange.getRanges();
}
}
/**
* Sets the ranges of attributes to be ignored. If provided string is null, no
* attributes will be ignored.
*
* @param rangeList a string representing the list of attributes. eg:
* first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setIgnoredAttributeIndices(String rangeList) {
if ((rangeList == null) || (rangeList.length() == 0)) {
m_IgnoreAttributesRange = null;
} else {
m_IgnoreAttributesRange = new Range();
m_IgnoreAttributesRange.setRanges(rangeList);
}
}
/**
* Gets the file pointing to a serialized, built clusterer. If it is null or
* pointing to a directory it will not be used.
*
* @return the file the serialized, built clusterer is located in
*/
public File getSerializedClustererFile() {
return m_SerializedClustererFile;
}
/**
* Sets the file pointing to a serialized, built clusterer. If the argument is
* null, doesn't exist or pointing to a directory, then the value is ignored.
*
* @param value the file pointing to the serialized, built clusterer
*/
public void setSerializedClustererFile(File value) {
if ((value == null) || (!value.exists())) {
value = new File(System.getProperty("user.dir"));
}
m_SerializedClustererFile = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String serializedClustererFileTipText() {
return "A file containing the serialized model of a built clusterer.";
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new AddCluster(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddExpression.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddExpression.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.core.expressionlanguage.common.IfElseMacro;
import weka.core.expressionlanguage.common.JavaMacro;
import weka.core.expressionlanguage.common.MacroDeclarationsCompositor;
import weka.core.expressionlanguage.common.MathFunctions;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.parser.Parser;
import weka.core.expressionlanguage.weka.InstancesHelper;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that creates a new attribute by
* applying a mathematical expression to existing attributes. The expression can
* contain attribute references and numeric constants. Supported operators are :<br/>
* +, -, *, /, ^, log, abs, cos, exp, sqrt, floor, ceil, rint, tan, sin, (, )<br/>
* Attributes are specified by prefixing with 'a', eg. a7 is attribute number 7
* (starting from 1).<br/>
* Example expression : a1^2*a5/log(a7*4.0).
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -E <expression>
* Specify the expression to apply. Eg a1^2*a5/log(a7*4.0).
* Supported opperators: ,+, -, *, /, ^, log, abs, cos,
* exp, sqrt, floor, ceil, rint, tan, sin, (, )
* (default: 0.0)
* </pre>
*
* <pre>
* -N <name>
* Specify the name for the new attribute. (default is the expression provided with -E)
* </pre>
*
* <pre>
* -D
* Debug. Names attribute with the postfix parse of the expression.
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public class AddExpression extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 402130384261736245L;
/** The infix expression */
private String m_infixExpression = "0.0";
/**
* Name of the new attribute. "expression" length string will use the provided
* expression as the new attribute name
*/
private String m_attributeName = "expression";
/**
* If true, makes the attribute name equal to the postfix parse of the
* expression
*/
private boolean m_Debug = false;
private DoubleExpression m_Expression = null;
private InstancesHelper m_InstancesHelper;
/**
* 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 creates a new attribute by applying a "
+ "mathematical expression to existing attributes. The expression "
+ "can contain attribute references and numeric constants. Supported "
+ "operators are :\n"
+ "+, -, *, /, ^, log, abs, cos, exp, sqrt, floor, ceil, rint, tan, "
+ "sin, (, )\n"
+ "Attributes are specified by prefixing with 'a', eg. a7 is "
+ "attribute number 7 (starting from 1).\n"
+ "Example expression : a1^2*a5/log(a7*4.0).";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(3);
newVector.addElement(new Option(
"\tSpecify the expression to apply. Eg a1^2*a5/log(a7*4.0)."
+ "\n\tSupported opperators: ,+, -, *, /, ^, log, abs, cos, "
+ "\n\texp, sqrt, floor, ceil, rint, tan, sin, (, )"
+ "\n\t(default: a1^2)", "E", 1, "-E <expression>"));
newVector.addElement(new Option(
"\tSpecify the name for the new attribute. (default is the "
+ "expression provided with -E)", "N", 1, "-N <name>"));
newVector
.addElement(new Option(
"\tDebug. Names attribute with the postfix parse of the "
+ "expression.", "D", 0, "-D"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -E <expression>
* Specify the expression to apply. Eg a1^2*a5/log(a7*4.0).
* Supported opperators: ,+, -, *, /, ^, log, abs, cos,
* exp, sqrt, floor, ceil, rint, tan, sin, (, )
* (default: a1^2)
* </pre>
*
* <pre>
* -N <name>
* Specify the name for the new attribute. (default is the expression provided with -E)
* </pre>
*
* <pre>
* -D
* Debug. Names attribute with the postfix parse of the expression.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String expString = Utils.getOption('E', options);
if (expString.length() != 0) {
setExpression(expString);
} else {
setExpression("a1^2");
}
String name = Utils.getOption('N', options);
if (name.length() != 0) {
setName(name);
}
setDebug(Utils.getFlag('D', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-E");
options.add(getExpression());
options.add("-N");
options.add(getName());
if (getDebug()) {
options.add("-D");
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String nameTipText() {
return "Set the name of the new attribute.";
}
/**
* Set the name for the new attribute. The string "expression" can be used to
* make the name of the new attribute equal to the expression provided.
*
* @param name the name of the new attribute
*/
public void setName(String name) {
m_attributeName = name;
}
/**
* Returns the name of the new attribute
*
* @return the name of the new attribute
*/
public String getName() {
return m_attributeName;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String debugTipText() {
return "Set debug mode. If true then the new attribute will be named with "
+ "the postfix parse of the supplied expression.";
}
/**
* Set debug mode. Causes the new attribute to be named with the postfix parse
* of the expression
*
* @param d true if debug mode is to be used
*/
public void setDebug(boolean d) {
m_Debug = d;
}
/**
* Gets whether debug is set
*
* @return true if debug is set
*/
public boolean getDebug() {
return m_Debug;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String expressionTipText() {
return "Set the math expression to apply. Eg. a1^2*a5/log(a7*4.0)";
}
/**
* Set the expression to apply
*
* @param expr a mathematical expression to apply
*/
public void setExpression(String expr) {
m_infixExpression = expr;
}
/**
* Get the expression
*
* @return the expression
*/
public String getExpression() {
return m_infixExpression;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
m_InstancesHelper = new InstancesHelper(instanceInfo);
Node node = Parser.parse(
// expressions string
m_infixExpression,
// variables
m_InstancesHelper,
// macros
new MacroDeclarationsCompositor(
m_InstancesHelper,
new MathFunctions(),
new IfElseMacro(),
new JavaMacro()
)
);
if (!(node instanceof DoubleExpression))
throw new Exception("Expression must be of double type!");
m_Expression = (DoubleExpression) node;
super.setInputFormat(instanceInfo);
Instances outputFormat = new Instances(instanceInfo, 0);
Attribute newAttribute;
if (m_attributeName.compareTo("expression") != 0) {
newAttribute = new Attribute(m_attributeName);
} else {
newAttribute = new Attribute(m_infixExpression);
}
outputFormat.insertAttributeAt(newAttribute, instanceInfo.numAttributes());
setOutputFormat(outputFormat);
return true;
}
/**
* 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.
* @throws Exception if there was a problem during the filtering.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
double[] vals = new double[instance.numAttributes() + 1];
System.arraycopy(instance.toDoubleArray(), 0, vals, 0, instance.numAttributes());
m_InstancesHelper.setInstance(instance);
vals[vals.length - 1] = m_Expression.evaluate();
if (m_InstancesHelper.missingAccessed())
vals[vals.length - 1] = Utils.missingValue();
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy instance
return true;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new AddExpression(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddID.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddID.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that adds an ID attribute to the
* dataset. The new attribute contains a unique ID for each instance.<br/>
* Note: The ID is not reset for the second batch of instances when batch mode
* is used from the command-line, or the FilteredClassifier.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <index>
* Specify where to insert the ID. First and last
* are valid indexes.(default first)
* </pre>
*
* <pre>
* -N <name>
* Name of the new attribute.
* (default = 'ID')
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class AddID extends Filter
implements UnsupervisedFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler{
/** for serialization */
static final long serialVersionUID = 4734383199819293390L;
/** the index of the attribute */
protected SingleIndex m_Index = new SingleIndex("first");
/** the name of the attribute */
protected String m_Name = "ID";
/** the counter for the ID */
protected int m_Counter = -1;
/**
* 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 adds an ID attribute to the dataset. "
+ "The new attribute contains a unique ID for each instance.\n\n"
+ "Note: The ID is not reset for the second batch of instances "
+ "when batch mode is used from the command-line, or the FilteredClassifier.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSpecify where to insert the ID. First and last\n"
+ "\tare valid indexes.(default first)", "C", 1, "-C <index>"));
result.addElement(new Option("\tName of the new attribute.\n"
+ "\t(default = 'ID')", "N", 1, "-N <name>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <index>
* Specify where to insert the ID. First and last
* are valid indexes.(default first)
* </pre>
*
* <pre>
* -N <name>
* Name of the new attribute.
* (default = 'ID')
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
m_Index.setSingleIndex(tmpStr);
} else {
m_Index.setSingleIndex("first");
}
tmpStr = Utils.getOption('N', options);
if (tmpStr.length() != 0) {
m_Name = tmpStr;
} else {
m_Name = "ID";
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-C");
result.add(getIDIndex());
result.add("-N");
result.add(getAttributeName());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeNameTipText() {
return "Set the new attribute's name.";
}
/**
* Get the name of the attribute to be created
*
* @return the current attribute name
*/
public String getAttributeName() {
return m_Name;
}
/**
* Set the new attribute's name
*
* @param value the new name
*/
public void setAttributeName(String value) {
m_Name = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String IDIndexTipText() {
return "The position (starting from 1) where the attribute will be inserted "
+ "(first and last are valid indices).";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getIDIndex() {
return m_Index.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param value the index of the attribute
*/
public void setIDIndex(String value) {
m_Index.setSingleIndex(value);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
Instances outputFormat;
Attribute newAttribute;
super.setInputFormat(instanceInfo);
m_Counter = -1;
m_Index.setUpper(instanceInfo.numAttributes());
outputFormat = new Instances(instanceInfo, 0);
newAttribute = new Attribute(m_Name);
if ((m_Index.getIndex() < 0)
|| (m_Index.getIndex() > getInputFormat().numAttributes())) {
throw new IllegalArgumentException("Index out of range");
}
outputFormat.insertAttributeAt(newAttribute, m_Index.getIndex());
setOutputFormat(outputFormat);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (!isFirstBatchDone()) {
bufferInput(instance);
return false;
} else {
convertInstance(instance);
return true;
}
}
/**
* Signify 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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isFirstBatchDone()) {
m_Counter = 0;
// Convert pending input instances
for (int i = 0; i < getInputFormat().numInstances(); i++) {
convertInstance(getInputFormat().instance(i));
}
}
// Free memory
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
*/
protected void convertInstance(Instance instance) {
Instance inst;
m_Counter++;
// build instance
try {
inst = (Instance) instance.copy();
// First copy string values from input to output
copyValues(inst, true, inst.dataset(), outputFormatPeek());
// Insert the new attribute and reassign to output
inst.setDataset(null);
inst.insertAttributeAt(m_Index.getIndex());
inst.setValue(m_Index.getIndex(), m_Counter);
push(inst); // No need to copy instance
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new AddID(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddNoise.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddNoise.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
import weka.gui.ProgrammaticProperty;
/**
* <!-- globalinfo-start --> An instance filter that changes a percentage of a
* given attribute's values. The attribute must be nominal. Missing value can be
* treated as a distinct separate value.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Index of the attribute to be changed
* (default last attribute)
* </pre>
*
* <pre>
* -M
* Treat missing values as an extra value
* </pre>
*
* <pre>
* -P <num>
* Specify the percentage of values that are changed (default 10)
* </pre>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <!-- options-end -->
*
* @author Gabi Schmidberger (gabi@cs.waikato.ac.nz)
* @version $Revision$
*/
public class AddNoise extends Filter implements UnsupervisedFilter,
OptionHandler, Randomizable, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -8499673222857299082L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** Flag if missing values are taken as value. */
private boolean m_UseMissing = false;
/** The subsample size, percent of original set, default 10% */
private int m_Percent = 10;
/** The random number generator seed */
private int m_RandomSeed = 1;
/**
* 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 changes a percentage of a given"
+ " attribute's values. The attribute must be nominal."
+ " Missing value can be treated as as a distinct separate value.";
}
/**
* Returns an enumeration describing the available options
*
* @return an enumeration of all the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tIndex of the attribute to be changed \n"
+ "\t(default last attribute)", "C", 1, "-C <col>"));
newVector.addElement(new Option(
"\tTreat missing values as an extra value \n", "M", 1, "-M"));
newVector.addElement(new Option(
"\tSpecify the percentage of values that are changed (default 10)", "P", 1, "-P <num>"));
newVector.addElement(new Option(
"\tSpecify the random number seed (default 1)", "S", 1, "-S <num>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Index of the attribute to be changed
* (default last attribute)
* </pre>
*
* <pre>
* -M
* Treat missing values as an extra value
* </pre>
*
* <pre>
* -P <num>
* Specify the percentage of values that are changed (default 10)
* </pre>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String indexString = Utils.getOption('C', options);
if (indexString.length() != 0) {
setAttributeIndex(indexString);
} else {
setAttributeIndex("last");
}
if (Utils.getFlag('M', options)) {
setUseMissing(true);
}
String percentString = Utils.getOption('P', options);
if (percentString.length() != 0) {
setPercent((int) Double.valueOf(percentString).doubleValue());
} else {
setPercent(10);
}
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
setRandomSeed(Integer.parseInt(seedString));
} else {
setRandomSeed(1);
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + getAttributeIndex());
if (getUseMissing()) {
options.add("-M");
}
options.add("-P");
options.add("" + getPercent());
options.add("-S");
options.add("" + getRandomSeed());
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useMissingTipText() {
return "Flag to set if missing values are treated as separate values.";
}
/**
* Gets the flag if missing values are treated as extra values.
*
* @return the flag missing values.
*/
public boolean getUseMissing() {
return m_UseMissing;
}
/**
* Sets the flag if missing values are treated as extra values.
*
* @param newUseMissing the new flag value.
*/
public void setUseMissing(boolean newUseMissing) {
m_UseMissing = newUseMissing;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String randomSeedTipText() {
return "Random number seed.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed(int newSeed) {
m_RandomSeed = newSeed;
}
@ProgrammaticProperty
public void setSeed(int seed) {
setRandomSeed(seed);
}
@ProgrammaticProperty
public int getSeed() {
return getRandomSeed();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String percentTipText() {
return "Percentage of values that are changed.";
}
/**
* Gets the size of noise data as a percentage of the original set.
*
* @return the noise data size
*/
public int getPercent() {
return m_Percent;
}
/**
* Sets the size of noise data, as a percentage of the original set.
*
* @param newPercent the subsample set size, between 0 and 100.
*/
public void setPercent(int newPercent) {
m_Percent = newPercent;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Index of the attribute that is to changed.";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
// set input format
// m_InputFormat = new Instances(instanceInfo, 0);
m_AttIndex.setUpper(getInputFormat().numAttributes() - 1);
// set index of attribute to be changed
// test if nominal
if (!getInputFormat().attribute(m_AttIndex.getIndex()).isNominal()) {
throw new Exception("Adding noise is not possible:"
+ "Chosen attribute is numeric.");
}
// test if two values are given
if ((getInputFormat().attribute(m_AttIndex.getIndex()).numValues() < 2)
&& (!m_UseMissing)) {
throw new Exception("Adding noise is not possible:"
+ "Chosen attribute has less than two values.");
}
setOutputFormat(getInputFormat());
m_NewBatch = true;
return false;
}
/**
* Input an instance for filtering.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws Exception if the input format was not set
*/
@Override
public boolean input(Instance instance) throws Exception {
// check if input format is defined
if (getInputFormat() == null) {
throw new Exception("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify 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 Exception if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new Exception("No input instance format defined");
}
// Do the subsample, and clear the input instances.
addNoise(getInputFormat(), m_RandomSeed, m_Percent, m_AttIndex.getIndex(),
m_UseMissing);
for (int i = 0; i < getInputFormat().numInstances(); i++) {
push((Instance) getInputFormat().instance(i).copy(), false); // No need to copy instance
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* add noise to the dataset
*
* a given percentage of the instances are changed in the way that a set of
* instances are randomly selected using seed. The attribute given by its
* index is changed from its current value to one of the other possibly ones,
* also randomly. This is done while leaving the proportion the same. If
* m_UseMissing is true, missing value is used as a value of its own
*
* @param instances is the dataset
* @param seed used for random function
* @param percent percentage of instances that are changed
* @param attIndex index of the attribute changed
* @param useMissing if true missing values are treated as extra value
*/
public void addNoise(Instances instances, int seed, int percent,
int attIndex, boolean useMissing) {
int indexList[];
int partition_count[];
int partition_max[];
double splitPercent = percent; // percentage used for splits
// fill array with the indexes
indexList = new int[instances.numInstances()];
for (int i = 0; i < instances.numInstances(); i++) {
indexList[i] = i;
}
// randomize list of indexes
Random random = new Random(seed);
for (int i = instances.numInstances() - 1; i >= 0; i--) {
int hValue = indexList[i];
int hIndex = (int) (random.nextDouble() * i);
indexList[i] = indexList[hIndex];
indexList[hIndex] = hValue;
}
// initialize arrays that are used to count instances
// of each value and to keep the amount of instances of that value
// that has to be changed
// this is done for the missing values in the two variables
// missing_count and missing_max
int numValues = instances.attribute(attIndex).numValues();
partition_count = new int[numValues];
partition_max = new int[numValues];
int missing_count = 0;
int missing_max = 0;
for (int i = 0; i < numValues; i++) {
partition_count[i] = 0;
partition_max[i] = 0;
}
// go through the dataset and count all occurrences of values
// and all missing values using temporarily .._max arrays and
// variable missing_max
for (Object element : instances) {
Instance instance = (Instance) element;
if (instance.isMissing(attIndex)) {
missing_max++;
} else {
instance.value(attIndex);
partition_max[(int) instance.value(attIndex)]++;
}
}
// use given percentage to calculate
// how many have to be changed per split and
// how many of the missing values
if (!useMissing) {
missing_max = missing_count;
} else {
missing_max = (int) (((double) missing_max / 100) * splitPercent + 0.5);
}
int sum_max = missing_max;
for (int i = 0; i < numValues; i++) {
partition_max[i] = (int) (((double) partition_max[i] / 100)
* splitPercent + 0.5);
sum_max = sum_max + partition_max[i];
}
// initialize sum_count to zero, use this variable to see if
// everything is done already
int sum_count = 0;
// add noise
// using the randomized index-array
//
Random randomValue = new Random(seed);
int numOfValues = instances.attribute(attIndex).numValues();
for (int i = 0; i < instances.numInstances(); i++) {
if (sum_count >= sum_max) {
break;
} // finished
Instance currInstance = instances.instance(indexList[i]);
// if value is missing then...
if (currInstance.isMissing(attIndex)) {
if (missing_count < missing_max) {
changeValueRandomly(randomValue, numOfValues, attIndex, currInstance,
useMissing);
missing_count++;
sum_count++;
}
} else {
int vIndex = (int) currInstance.value(attIndex);
if (partition_count[vIndex] < partition_max[vIndex]) {
changeValueRandomly(randomValue, numOfValues, attIndex, currInstance,
useMissing);
partition_count[vIndex]++;
sum_count++;
}
}
}
}
/**
* method to set a new value
*
* @param r random function
* @param numOfValues
* @param instance
* @param useMissing
*/
private void changeValueRandomly(Random r, int numOfValues, int indexOfAtt,
Instance instance, boolean useMissing) {
int currValue;
// get current value
// if value is missing set current value to number of values
// whiche is the highest possible value plus one
if (instance.isMissing(indexOfAtt)) {
currValue = numOfValues;
} else {
currValue = (int) instance.value(indexOfAtt);
}
// with only two possible values it is easier
if ((numOfValues == 2) && (!instance.isMissing(indexOfAtt))) {
instance.setValue(indexOfAtt, (currValue + 1) % 2);
} else {
// get randomly a new value not equal to the current value
// if missing values are used as values they must be treated
// in a special way
while (true) {
int newValue;
if (useMissing) {
newValue = (int) (r.nextDouble() * (numOfValues + 1));
} else {
newValue = (int) (r.nextDouble() * numOfValues);
}
// have we found a new value?
if (newValue != currValue) {
// the value 1 above the highest possible value (=numOfValues)
// is used as missing value
if (newValue == numOfValues) {
instance.setMissing(indexOfAtt);
} else {
instance.setValue(indexOfAtt, newValue);
}
break;
}
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new AddNoise(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddUserFields.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddUserFields.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that adds new attributes with user
* specified type and constant value. Numeric, nominal, string and date
* attributes can be created. Attribute name, and value can be set with
* environment variables. Date attributes can also specify a formatting string
* by which to parse the supplied date value. Alternatively, a current time
* stamp can be specified by supplying the special string "now" as the value for
* a date attribute.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -A <name:type:value>
* New field specification (name@type@value).
* Environment variables may be used for any/all parts of the
* specification. Type can be one of (numeric, nominal, string or date).
* The value for date be a specific date string or the special string
* "now" to indicate the current date-time. A specific date format
* string for parsing specific date values can be specified by suffixing
* the type specification - e.g. "myTime@date:MM-dd-yyyy@08-23-2009".This option may be specified multiple times
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class AddUserFields extends Filter implements OptionHandler,
EnvironmentHandler, UnsupervisedFilter, WeightedInstancesHandler, WeightedAttributesHandler {
/** For serialization */
private static final long serialVersionUID = -2761427344847891585L;
/** The new attributes to create */
protected List<AttributeSpec> m_attributeSpecs;
protected transient Environment m_env;
/**
* Inner class encapsulating a new user-specified attribute to create.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
*/
public static class AttributeSpec implements Serializable {
/** For serialization */
private static final long serialVersionUID = -617328946241474608L;
/** The name of the new attribute */
protected String m_name = "";
/** The constant value it should assume */
protected String m_value = "";
/** The type of the new attribute */
protected String m_type = "";
/** The name after resolving any environment variables */
protected String m_nameS;
/** The value after resolving any environment variables */
protected String m_valueS;
/** The type after resolving any environment variables */
protected String m_typeS;
/** The date format to use (if the new attribute is a date) */
protected SimpleDateFormat m_dateFormat;
/** Holds the parsed date value */
protected Date m_parsedDate;
/**
* Default constructor
*/
public AttributeSpec() {
}
/**
* Constructor that takes an attribute specification in internal format
*
* @param spec the attribute spec to use
*/
public AttributeSpec(String spec) {
parseFromInternal(spec);
}
/**
* Set the name of the new attribute
*
* @param name the name of the new attribute
*/
public void setName(String name) {
m_name = name;
}
/**
* Get the name of the new attribute
*
* @return the name of the new attribute
*/
public String getName() {
return m_name;
}
/**
* Set the type of the new attribute
*
* @param type the type of the new attribute
*/
public void setType(String type) {
m_type = type;
}
/**
* Get the type of the new attribute
*
* @return the type of the new attribute
*/
public String getType() {
return m_type;
}
/**
* Set the value of the new attribute. Date attributes can assume a supplied
* date value (parseable by either the default date format or a user
* specified one) or the current time stamp if the user specifies the
* special string "now".
*
* @param value the value of the new attribute
*/
public void setValue(String value) {
m_value = value;
}
/**
* Get the value of the new attribute. Date attributes can assume a supplied
* date value (parseable by either the default date format or a user
* specified one) or the current time stamp if the user specifies the
* special string "now".
*
* @return the value of the new attribute
*/
public String getValue() {
return m_value;
}
/**
* Get the name of the attribute after substituting any environment
* variables
*
* @return the name of the attribute after environment variables have been
* substituted
*/
public String getResolvedName() {
return m_nameS;
}
/**
* Get the value of the attribute after substituting any environment
* variables
*
* @return the value of the attribute after environment variables have been
* substituted
*/
public String getResolvedValue() {
return m_valueS;
}
/**
* Get the type of the attribute after substituting any environment
* variables
*
* @return the tyep of the attribute after environment variables have been
* substituted
*/
public String getResolvedType() {
return m_typeS;
}
/**
* Get the date formatting string (if any)
*
* @return the date formatting string
*/
public String getDateFormat() {
if (m_dateFormat != null) {
return m_dateFormat.toPattern();
} else {
return null;
}
}
/**
* Get the value of the attribute as a date or null if the attribute isn't
* of type date.
*
* @return the value as a date
*/
public Date getDateValue() {
if (m_parsedDate != null) {
return m_parsedDate;
}
if (getResolvedType().toLowerCase().startsWith("date")) {
return new Date(); // now
}
return null; // not a date attribute
}
/**
* Get the value of the attribute as a number or Utils.missingValue() if the
* attribute is not numeric.
*
* @return the value of the attribute as a number
*/
public double getNumericValue() {
if (getResolvedType().toLowerCase().startsWith("numeric")) {
return Double.parseDouble(getResolvedValue());
}
return Utils.missingValue(); // not a numeric attribute
}
/**
* Get the value of the attribute as a string (nominal and string attribute)
* or null if the attribute is not nominal or string
*
* @return the value of the attribute as a string
*/
public String getNominalOrStringValue() {
if (getResolvedType().toLowerCase().startsWith("nominal")
|| getResolvedType().toLowerCase().startsWith("string")) {
return getResolvedValue();
}
return null; // not a nominal or string attribute
}
protected void parseFromInternal(String spec) {
String[] parts = spec.split("@");
if (parts.length > 0) {
m_name = parts[0].trim();
}
if (parts.length > 1) {
m_type = parts[1].trim();
}
if (parts.length > 2) {
m_value = parts[2].trim();
}
}
/**
* Initialize this attribute spec by resolving any environment variables and
* setting up the date format (if necessary)
*
* @param env environment variables to use
*/
public void init(Environment env) {
m_nameS = m_name;
m_typeS = m_type;
m_valueS = m_value;
try {
m_nameS = env.substitute(m_nameS);
m_typeS = env.substitute(m_typeS);
m_valueS = env.substitute(m_valueS);
} catch (Exception ex) {
}
if (m_typeS.toLowerCase().startsWith("date") && m_typeS.indexOf(":") > 0) {
String format = m_typeS.substring(m_typeS.indexOf(":") + 1,
m_typeS.length());
m_dateFormat = new SimpleDateFormat(format);
if (!m_valueS.toLowerCase().equals("now")) {
try {
m_parsedDate = m_dateFormat.parse(m_valueS);
} catch (ParseException e) {
throw new IllegalArgumentException("Date value \"" + m_valueS
+ " \" can't be parsed with formatting string \"" + format + "\"");
}
}
}
}
/**
* Return a nicely formatted string for display
*
* @return a textual description
*/
@Override
public String toString() {
StringBuffer buff = new StringBuffer();
buff.append("Name: ").append(m_name).append(" ");
String type = m_type;
if (type.toLowerCase().startsWith("date") && type.indexOf(":") > 0) {
type = type.substring(0, type.indexOf(":"));
String format = m_type.substring(m_type.indexOf(":" + 1,
m_type.length()));
buff.append("Type: ").append(type).append(" [").append(format)
.append("] ");
} else {
buff.append("Type: ").append(type).append(" ");
}
buff.append("Value: ").append(m_value);
return buff.toString();
}
public String toStringInternal() {
StringBuffer buff = new StringBuffer();
buff.append(m_name).append("@").append(m_type).append("@")
.append(m_value);
return buff.toString();
}
}
/**
* Constructs a new AddUserFields
*/
public AddUserFields() {
m_attributeSpecs = new ArrayList<AttributeSpec>();
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that adds new attributes with user specified type and constant value. "
+ "Numeric, nominal, string and date attributes can be created. "
+ "Attribute name, and value can be set with environment variables. Date "
+ "attributes can also specify a formatting string by which to parse "
+ "the supplied date value. Alternatively, a current time stamp can "
+ "be specified by supplying the special string \"now\" as the value "
+ "for a date attribute.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Clear the list of attribute specifications
*/
public void clearAttributeSpecs() {
if (m_attributeSpecs == null) {
m_attributeSpecs = new ArrayList<AttributeSpec>();
}
m_attributeSpecs.clear();
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(1);
newVector
.addElement(new Option(
"\tNew field specification (name@type:value).\n"
+ "\t Environment variables may be used for any/all parts of the\n"
+ "\tspecification. Type can be one of (numeric, nominal, string or date).\n"
+ "\tThe value for date be a specific date string or the special string\n"
+ "\t\"now\" to indicate the current date-time. A specific date format\n"
+ "\tstring for parsing specific date values can be specified by suffixing\n"
+ "\tthe type specification - e.g. \"myTime@date:MM-dd-yyyy@08-23-2009\"."
+ "This option may be specified multiple times", "A", 1,
"-A <name@type@value>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> * Valid options are:
* <p/>
* * *
*
* <pre>
* -A <name:type:value>
* * New field specification (name@type@value).
* * Environment variables may be used for any/all parts of the
* * specification. Type can be one of (numeric, nominal, string or date).
* * The value for date be a specific date string or the special string
* * "now" to indicate the current date-time. A specific date format
* * string for parsing specific date values can be specified by suffixing
* * the type specification - e.g. "myTime@date:MM-dd-yyyy@08-23-2009".This option may be specified multiple times
* </pre>
*
* * <!-- options-end -->
*
* @param options the list of options as an array of string
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
clearAttributeSpecs();
String attS = "";
while ((attS = Utils.getOption('A', options)).length() > 0) {
addAttributeSpec(attS);
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
ArrayList<String> options = new ArrayList<String>();
for (int i = 0; i < m_attributeSpecs.size(); i++) {
options.add("-A");
options.add(m_attributeSpecs.get(i).toStringInternal());
}
if (options.size() == 0) {
return new String[0];
}
return options.toArray(new String[1]);
}
/**
* Add an attribute spec to the list
*
* @param spec the attribute spec to add
*/
public void addAttributeSpec(String spec) {
AttributeSpec newSpec = new AttributeSpec(spec);
m_attributeSpecs.add(newSpec);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeSpecsTipText() {
return "Specifications of the new attributes to create";
}
/**
* Set the list of attribute specs to use to create the new attributes.
*
* @param specs the list of attribute specs to use
*/
public void setAttributeSpecs(List<AttributeSpec> specs) {
m_attributeSpecs = specs;
}
/**
* Get the list of attribute specs to use to create the new attributes.
*
* @return the list of attribute specs to use
*/
public List<AttributeSpec> getAttributeSpecs() {
return m_attributeSpecs;
}
/**
* Set environment varialbes to use
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* 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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat();
return true;
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() == null) {
setOutputFormat();
}
Instance inst = (Instance) instance.copy();
// First copy string values from input to output
copyValues(inst, true, inst.dataset(), outputFormatPeek());
convertInstance(inst);
return true;
}
/**
* Add the new attribute values to an instance
*
* @param instance the instance to process
*/
protected void convertInstance(Instance instance) {
double[] vals = new double[outputFormatPeek().numAttributes()];
// original values first
for (int i = 0; i < instance.numAttributes(); i++) {
vals[i] = instance.value(i);
}
// new user values
Instances outputFormat = getOutputFormat();
for (int i = instance.numAttributes(); i < outputFormatPeek()
.numAttributes(); i++) {
AttributeSpec spec = m_attributeSpecs.get(i - instance.numAttributes());
Attribute outAtt = outputFormat.attribute(i);
if (outAtt.isDate()) {
vals[i] = spec.getDateValue().getTime();
} else if (outAtt.isNumeric()) {
vals[i] = spec.getNumericValue();
} else if (outAtt.isNominal()) {
String nomVal = spec.getNominalOrStringValue();
vals[i] = outAtt.indexOfValue(nomVal);
} else {
// string attribute
String nomVal = spec.getNominalOrStringValue();
vals[i] = outAtt.addStringValue(nomVal);
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(outputFormat);
push(inst, false); // No need to copy instance
}
/**
* Create and set the output format
*/
protected void setOutputFormat() {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
Instances inputF = getInputFormat();
ArrayList<Attribute> newAtts = new ArrayList<Attribute>();
// existing attributes
for (int i = 0; i < inputF.numAttributes(); i++) {
newAtts.add((Attribute) inputF.attribute(i).copy());
}
// new user-defined attributes
for (int i = 0; i < m_attributeSpecs.size(); i++) {
AttributeSpec a = m_attributeSpecs.get(i);
a.init(m_env);
String type = a.getResolvedType();
Attribute newAtt = null;
if (type.toLowerCase().startsWith("date")) {
String format = a.getDateFormat();
if (format == null) {
format = "yyyy-MM-dd'T'HH:mm:ss";
}
newAtt = new Attribute(a.getResolvedName(), format);
} else if (type.toLowerCase().startsWith("string")) {
newAtt = new Attribute(a.getResolvedName(), (List<String>) null);
} else if (type.toLowerCase().startsWith("nominal")) {
List<String> vals = new ArrayList<String>();
vals.add(a.getResolvedValue());
newAtt = new Attribute(a.getResolvedName(), vals);
} else {
// numeric
newAtt = new Attribute(a.getResolvedName());
}
newAtts.add(newAtt);
}
Instances outputFormat = new Instances(inputF.relationName(), newAtts, 0);
outputFormat.setClassIndex(inputF.classIndex());
setOutputFormat(outputFormat);
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new AddUserFields(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddUserFieldsBeanInfo.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddUserFieldsBeanInfo.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.beans.BeanDescriptor;
import java.beans.SimpleBeanInfo;
/**
* Bean info class for the AddUserFields filter.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class AddUserFieldsBeanInfo extends SimpleBeanInfo {
/**
* Get the bean descriptor for this bean
*
* @return a <code>BeanDescriptor</code> value
*/
@Override
public BeanDescriptor getBeanDescriptor() {
return new BeanDescriptor(
weka.filters.unsupervised.attribute.AddUserFields.class,
weka.gui.filters.AddUserFieldsCustomizer.class);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/AddValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* AddValues.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Adds the labels from the given list to an attribute
* if they are missing. The labels can also be sorted in an ascending manner. If
* no labels are provided then only the (optional) sorting applies.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index
* (default last).
* </pre>
*
* <pre>
* -L <label1,label2,...>
* Comma-separated list of labels to add.
* (default: none)
* </pre>
*
* <pre>
* -S
* Turns on the sorting of the labels.
* </pre>
*
* <!-- options-end -->
*
* Based on code from AddValues.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see AddValues
*/
public class AddValues extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -8100622241742393656L;
/** The attribute's index setting. */
protected SingleIndex m_AttIndex = new SingleIndex("last");
/** The values to add. */
protected ArrayList<String> m_Labels = new ArrayList<String>();
/** Whether to sort the values. */
protected boolean m_Sort = false;
/** the array with the sorted label indices */
protected int[] m_SortedIndices;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Adds the labels from the given list to an attribute if they are "
+ "missing. The labels can also be sorted in an ascending manner. "
+ "If no labels are provided then only the (optional) sorting applies.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tSets the attribute index\n"
+ "\t(default last).", "C", 1, "-C <col>"));
result.addElement(new Option("\tComma-separated list of labels to add.\n"
+ "\t(default: none)", "L", 1, "-L <label1,label2,...>"));
result.addElement(new Option("\tTurns on the sorting of the labels.", "S",
0, "-S"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index
* (default last).
* </pre>
*
* <pre>
* -L <label1,label2,...>
* Comma-separated list of labels to add.
* (default: none)
* </pre>
*
* <pre>
* -S
* Turns on the sorting of the labels.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
setAttributeIndex(tmpStr);
} else {
setAttributeIndex("last");
}
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0) {
setLabels(tmpStr);
} else {
setLabels("");
}
setSort(Utils.getFlag('S', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-C");
result.add("" + getAttributeIndex());
result.add("-L");
result.add("" + getLabels());
if (getSort()) {
result.add("-S");
}
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
Attribute att;
Attribute attNew;
ArrayList<String> allLabels;
Enumeration<Object> enm;
int i;
ArrayList<String> values;
ArrayList<Attribute> atts;
Instances instNew;
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
att = instanceInfo.attribute(m_AttIndex.getIndex());
if (!att.isNominal()) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute not nominal.");
}
// merge labels
allLabels = new ArrayList<String>();
enm = att.enumerateValues();
while (enm.hasMoreElements()) {
Object o = enm.nextElement();
if (o instanceof SerializedObject) {
o = ((SerializedObject) o).getObject();
}
allLabels.add((String) o);
}
for (i = 0; i < m_Labels.size(); i++) {
if (!allLabels.contains(m_Labels.get(i))) {
allLabels.add(m_Labels.get(i));
}
}
// generate index array
if (getSort()) {
Collections.sort(allLabels);
}
m_SortedIndices = new int[att.numValues()];
enm = att.enumerateValues();
i = 0;
while (enm.hasMoreElements()) {
m_SortedIndices[i] = allLabels.indexOf(enm.nextElement());
i++;
}
// generate new header
values = new ArrayList<String>();
for (i = 0; i < allLabels.size(); i++) {
values.add(allLabels.get(i));
}
attNew = new Attribute(att.name(), values);
attNew.setWeight(att.weight());
atts = new ArrayList<Attribute>();
for (i = 0; i < instanceInfo.numAttributes(); i++) {
if (i == m_AttIndex.getIndex()) {
atts.add(attNew);
} else {
atts.add(instanceInfo.attribute(i));
}
}
instNew = new Instances(instanceInfo.relationName(), atts, 0);
instNew.setClassIndex(instanceInfo.classIndex());
// set new format
setOutputFormat(instNew);
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @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 set.
*/
@Override
public boolean input(Instance instance) {
Instance newInstance;
double[] values;
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
// generate new Instance
values = instance.toDoubleArray();
if (!instance.isMissing(m_AttIndex.getIndex())) {
values[m_AttIndex.getIndex()] = m_SortedIndices[(int) values[m_AttIndex
.getIndex()]];
}
newInstance = new DenseInstance(instance.weight(), values);
// copy string values etc. from input to output
copyValues(instance, false, instance.dataset(), outputFormatPeek());
push(newInstance); // No need to copy instance
return true;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute to process. This "
+ "attribute must be nominal (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String labelsTipText() {
return "Comma-separated list of lables to add.";
}
/**
* Get the comma-separated list of labels that are added.
*
* @return the list of labels
*/
public String getLabels() {
String result;
int i;
result = "";
for (i = 0; i < m_Labels.size(); i++) {
if (i > 0) {
result += ",";
}
result += Utils.quote(m_Labels.get(i));
}
return result;
}
/**
* Sets the comma-separated list of labels.
*
* @param value the list
*/
public void setLabels(String value) {
int i;
String label;
boolean quoted;
boolean add;
m_Labels.clear();
label = "";
quoted = false;
add = false;
for (i = 0; i < value.length(); i++) {
// quotes?
if (value.charAt(i) == '"') {
quoted = !quoted;
if (!quoted) {
add = true;
}
}
// comma
else if ((value.charAt(i) == ',') && (!quoted)) {
add = true;
}
// normal character
else {
label += value.charAt(i);
// last character?
if (i == value.length() - 1) {
add = true;
}
}
if (add) {
if (label.length() != 0) {
m_Labels.add(label);
}
label = "";
add = false;
}
}
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String sortTipText() {
return "Whether to sort the labels alphabetically.";
}
/**
* Gets whether the labels are sorted or not.
*
* @return true if the labels are sorted
*/
public boolean getSort() {
return m_Sort;
}
/**
* Sets whether the labels are sorted.
*
* @param value if true the labels are sorted
*/
public void setSort(boolean value) {
m_Sort = value;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing and running this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new AddValues(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/CartesianProduct.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* CartesianProduct.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
/**
* <!-- globalinfo-start -->
* A filter for performing the Cartesian product of a set of nominal attributes. The weight of the new Cartesian
* product attribute is the sum of the weights of the combined attributes.
* <br><br>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are: <p>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of nominal attributes to use to form the product.
* (default none)</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank
* @version $Revision: 12037 $
*/
public class CartesianProduct extends SimpleBatchFilter {
/** for serialization */
private static final long serialVersionUID = -227979753639722020L;
/** the attribute range to work on */
protected Range m_Attributes = new Range("");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for performing the Cartesian product of a set of nominal attributes. " +
"The weight of the new Cartesian product attribute is the sum of the weights of the combined attributes.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSpecifies list of nominal attributes to use to form the product.\n" + "\t(default none)", "R",
1, "-R <col1,col2-col4,...>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start -->
* Valid options are: <p>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of nominal attributes to use to form the product.
* (default none)</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption("R", options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("");
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (!getAttributeIndices().equals("")) {
result.add("-R");
result.add(getAttributeIndices());
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on; "
+ " this is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values; specify an inclusive"
+ " range with \"-\", eg: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Attributes.getRanges();
}
/**
* Sets which attributes are to be used for interquartile calculations and
* outlier/extreme value detection (only numeric attributes among the
* selection will be used).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Attributes.setRanges(value);
}
/**
* Sets which attributes are to be used.
*
* @param value an array containing indexes of attributes to work on. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.MISSING_VALUES);
result.enableAllAttributes();
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) throws Exception {
// attributes must be numeric
m_Attributes.setUpper(inputFormat.numAttributes() - 1);
ArrayList<Attribute> atts = new ArrayList<Attribute>(inputFormat.numAttributes() + 1);
ArrayList<String> values = new ArrayList<String>();
String name = "";
double sumOfWeights = 0;
for (int i = 0; i < inputFormat.numAttributes(); i++) {
atts.add(inputFormat.attribute(i)); // Can just copy reference because index remains unchanged.
if (inputFormat.attribute(i).isNominal() && m_Attributes.isInRange(i) && i != inputFormat.classIndex()) {
sumOfWeights += inputFormat.attribute(i).weight();
if (values.size() == 0) {
values = new ArrayList<String>(inputFormat.attribute(i).numValues());
for (int j = 0; j < inputFormat.attribute(i).numValues(); j++) {
values.add(inputFormat.attribute(i).value(j));
}
name = inputFormat.attribute(i).name();
} else {
ArrayList<String> newValues = new ArrayList<String>(values.size() * inputFormat.attribute(i).numValues());
for (String value : values) {
for (int j = 0; j < inputFormat.attribute(i).numValues(); j++) {
newValues.add(value + "_x_" + inputFormat.attribute(i).value(j));
}
}
name += "_x_" + inputFormat.attribute(i).name();
values = newValues;
}
}
}
if (values.size() > 0) {
Attribute a = new Attribute(name, values);
a.setWeight(sumOfWeights);
atts.add(a);
}
// generate header
Instances result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished(). This
* implementation only calls process(Instance) for each instance in the given
* dataset.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result = getOutputFormat();
for (Instance inst : instances) {
if (instances.numAttributes() < result.numAttributes()) { // Do we actually need to add an attribute?
double[] newVals = new double[result.numAttributes()];
for (int i = 0; i < inst.numValues(); i++) {
newVals[inst.index(i)] = inst.valueSparse(i);
}
String value = "";
for (int i = 0; i < inst.numAttributes(); i++) {
if (instances.attribute(i).isNominal() && m_Attributes.isInRange(i) && i != instances.classIndex()) {
if (Utils.isMissingValue(newVals[i])) {
value = null;
break;
} else {
value += (value.length() > 0) ? "_x_" + instances.attribute(i).value((int) newVals[i]) :
instances.attribute(i).value((int) newVals[i]);
}
}
}
if (value == null) {
newVals[newVals.length - 1] = Double.NaN;
} else {
newVals[newVals.length - 1] = result.attribute(result.numAttributes() - 1).indexOfValue(value);;
}
if (inst instanceof DenseInstance) {
result.add(new DenseInstance(inst.weight(), newVals));
} else {
result.add(new SparseInstance(inst.weight(), newVals));
}
} else {
result.add(inst);
}
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 12037 $");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new CartesianProduct(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Center.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Center.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Sourcable;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Centers all numeric attributes in the given dataset to have zero mean (apart from 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>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Center
extends PotentialClassIgnorer
implements UnsupervisedFilter, Sourcable, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
private static final long serialVersionUID = -9101338448900581023L;
/** The means */
private double[] m_Means;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Centers all numeric attributes in the given dataset "
+ "to have zero mean (apart from the class attribute, if set).";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
m_Means = null;
return true;
}
/**
* Input an instance for filtering. Filter requires all
* training 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 set.
*/
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_Means == null) {
bufferInput(instance);
return false;
}
else {
convertInstance(instance);
return true;
}
}
/**
* Signify 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_Means == null) {
Instances input = getInputFormat();
m_Means = new double[input.numAttributes()];
for (int i = 0; i < input.numAttributes(); i++) {
if (input.attribute(i).isNumeric() &&
(input.classIndex() != i)) {
m_Means[i] = input.meanOrMode(i);
}
}
// Convert pending input instances
for (int i = 0; i < input.numInstances(); i++)
convertInstance(input.instance(i));
}
// Free memory
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is
* added to the end of the output queue.
*
* @param instance the instance to convert
*/
private void convertInstance(Instance instance) {
Instance inst = null;
if (instance instanceof SparseInstance) {
double[] newVals = new double[instance.numAttributes()];
int[] newIndices = new int[instance.numAttributes()];
double[] vals = instance.toDoubleArray();
int ind = 0;
for (int j = 0; j < instance.numAttributes(); j++) {
double value;
if (instance.attribute(j).isNumeric() &&
(!Utils.isMissingValue(vals[j])) &&
(getInputFormat().classIndex() != j)) {
value = vals[j] - m_Means[j];
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
} else {
value = vals[j];
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
}
}
double[] tempVals = new double[ind];
int[] tempInd = new int[ind];
System.arraycopy(newVals, 0, tempVals, 0, ind);
System.arraycopy(newIndices, 0, tempInd, 0, ind);
inst = new SparseInstance(instance.weight(), tempVals, tempInd,
instance.numAttributes());
} else {
double[] vals = instance.toDoubleArray();
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
if (instance.attribute(j).isNumeric() &&
(!Utils.isMissingValue(vals[j])) &&
(getInputFormat().classIndex() != j)) {
vals[j] = (vals[j] - m_Means[j]);
}
}
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
push(inst, false); // No need to copy instance
}
/**
* Returns a string that describes the filter as source. The
* filter will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain two methods with these signatures:
* <pre><code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
public String toSource(String className, Instances data) throws Exception {
StringBuffer result;
boolean[] process;
int i;
result = new StringBuffer();
// determine what attributes were processed
process = new boolean[data.numAttributes()];
for (i = 0; i < data.numAttributes(); i++) {
process[i] = (data.attribute(i).isNumeric() && (i != data.classIndex()));
}
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /** lists which attributes will be processed */\n");
result.append(" protected final static boolean[] PROCESS = new boolean[]{" + Utils.arrayToString(process) + "};\n");
result.append("\n");
result.append(" /** the computed means */\n");
result.append(" protected final static double[] MEANS = new double[]{" + Utils.arrayToString(m_Means) + "};\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" Object[] result;\n");
result.append("\n");
result.append(" result = new Object[i.length];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" if (PROCESS[n] && (i[n] != null))\n");
result.append(" result[n] = ((Double) i[n]) - MEANS[n];\n");
result.append(" else\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" Object[][] result;\n");
result.append("\n");
result.append(" result = new Object[i.length][];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" result[n] = filter(i[n]);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for running this filter.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String [] args) {
runFilter(new Center(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ChangeDateFormat.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ChangeDateFormat.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Changes the date format used by a date attribute.
* This is most useful for converting to a format with less precision, for
* example, from an absolute date to day of year, etc. This changes the format
* string, and changes the date values to those that would be parsed by the new
* format.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the output date format string (default corresponds to ISO-8601).
* </pre>
*
* <!-- options-end -->
*
* @author <a href="mailto:len@reeltwo.com">Len Trigg</a>
* @version $Revision$
*/
public class ChangeDateFormat extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -1609344074013448737L;
/** The default output date format. Corresponds to ISO-8601 format. */
private static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss");
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** The output date format. */
private SimpleDateFormat m_DateFormat = DEFAULT_FORMAT;
/** The output attribute. */
private Attribute m_OutputAttribute;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Changes the date format used by a date attribute. This is most "
+ "useful for converting to a format with less precision, for example, "
+ "from an absolute date to day of year, etc. This changes the format "
+ "string, and changes the date values to those that would be parsed "
+ "by the new format.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
if (!instanceInfo.attribute(m_AttIndex.getIndex()).isDate()) {
throw new UnsupportedAttributeTypeException("Chosen attribute not date.");
}
setOutputFormat();
return true;
}
/**
* Input an instance for filtering.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws Exception if the input format was not set or the date format cannot
* be parsed
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instance newInstance = (Instance) instance.copy();
int index = m_AttIndex.getIndex();
if (!newInstance.isMissing(index)) {
double value = instance.value(index);
try {
// Format and parse under the new format to force any required
// loss in precision.
value = m_OutputAttribute
.parseDate(m_OutputAttribute.formatDate(value));
} catch (ParseException pe) {
throw new RuntimeException(
"Output date format couldn't parse its own output!!");
}
newInstance.setValue(index, value);
}
push(newInstance, false); // No need to copy instance
return true;
}
/**
* Returns an enumeration describing the available options
*
* @return an enumeration of all the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option(
"\tSets the attribute index (default last).", "C", 1, "-C <col>"));
newVector
.addElement(new Option(
"\tSets the output date format string (default corresponds to ISO-8601).",
"F", 1, "-F <value index>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the output date format string (default corresponds to ISO-8601).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
setAttributeIndex(attIndex);
} else {
setAttributeIndex("last");
}
String formatString = Utils.getOption('F', options);
if (formatString.length() != 0) {
setDateFormat(formatString);
} else {
setDateFormat(DEFAULT_FORMAT);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + getAttributeIndex());
options.add("-F");
options.add("" + getDateFormat().toPattern());
return options.toArray(new String[0]);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute to process. This "
+ "attribute must be of type date (\"first\" and \"last\" are valid values)";
}
/**
* Gets the index of the attribute converted.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets the index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dateFormatTipText() {
return "The date format to change to. This should be a "
+ "format understood by Java's SimpleDateFormat class.";
}
/**
* Get the date format used in output.
*
* @return the output date format.
*/
public SimpleDateFormat getDateFormat() {
return m_DateFormat;
}
/**
* Sets the output date format.
*
* @param dateFormat the output date format.
*/
public void setDateFormat(String dateFormat) {
setDateFormat(new SimpleDateFormat(dateFormat));
}
/**
* Sets the output date format.
*
* @param dateFormat the output date format.
*/
public void setDateFormat(SimpleDateFormat dateFormat) {
if (dateFormat == null) {
throw new NullPointerException();
}
m_DateFormat = dateFormat;
}
/**
* Set the output format. Changes the format of the specified date attribute.
*/
private void setOutputFormat() {
// Create new attributes
ArrayList<Attribute> newAtts = new ArrayList<Attribute>(getInputFormat()
.numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (j == m_AttIndex.getIndex()) {
Attribute a = new Attribute(att.name(), getDateFormat().toPattern());
a.setWeight(att.weight());
newAtts.add(a);
} else {
newAtts.add((Attribute) att.copy());
}
}
// Create new header
Instances newData = new Instances(getInputFormat().relationName(), newAtts,
0);
newData.setClassIndex(getInputFormat().classIndex());
m_OutputAttribute = newData.attribute(m_AttIndex.getIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new ChangeDateFormat(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ClassAssigner.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ClassAssigner.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleStreamFilter;
/**
* <!-- globalinfo-start --> Filter that can set and unset the class index.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -C <num|first|last|0>
* The index of the class attribute. Index starts with 1, 'first'
* and 'last' are accepted, '0' unsets the class index.
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ClassAssigner extends SimpleStreamFilter implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
private static final long serialVersionUID = 1775780193887394115L;
/** use the first attribute as class. */
public final static int FIRST = 0;
/** use the last attribute as class. */
public final static int LAST = -2;
/** unset the class attribute. */
public final static int UNSET = -1;
/** the class index. */
protected int m_ClassIndex = LAST;
/**
* Returns a string describing this classifier.
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Filter that can set and unset the class index.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(1);
result.addElement(new Option(
"\tThe index of the class attribute. Index starts with 1, 'first'\n"
+ "\tand 'last' are accepted, '0' unsets the class index.\n"
+ "\t(default: last)", "C", 1, "-C <num|first|last|0>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -C <num|first|last|0>
* The index of the class attribute. Index starts with 1, 'first'
* and 'last' are accepted, '0' unsets the class index.
* (default: last)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption("C", options);
if (tmpStr.length() != 0) {
setClassIndex(tmpStr);
} else {
setClassIndex("last");
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-C");
result.add(getClassIndex());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "The index of the class attribute, starts with 1, 'first' and 'last' "
+ "are accepted as well, '0' unsets the class index.";
}
/**
* sets the class index.
*
* @param value the class index
*/
public void setClassIndex(String value) {
if (value.equalsIgnoreCase("first")) {
m_ClassIndex = FIRST;
} else if (value.equalsIgnoreCase("last")) {
m_ClassIndex = LAST;
} else if (value.equalsIgnoreCase("0")) {
m_ClassIndex = UNSET;
} else {
try {
m_ClassIndex = Integer.parseInt(value) - 1;
} catch (Exception e) {
System.err.println("Error parsing '" + value + "'!");
}
}
}
/**
* returns the class index.
*
* @return the class index
*/
public String getClassIndex() {
if (m_ClassIndex == FIRST) {
return "first";
} else if (m_ClassIndex == LAST) {
return "last";
} else if (m_ClassIndex == UNSET) {
return "0";
} else {
return "" + (m_ClassIndex + 1);
}
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.NO_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the class index is invalid
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result = new Instances(inputFormat, 0);
if (m_ClassIndex == FIRST) {
result.setClassIndex(0);
} else if (m_ClassIndex == LAST) {
result.setClassIndex(result.numAttributes() - 1);
} else if (m_ClassIndex == UNSET) {
result.setClassIndex(-1);
} else {
result.setClassIndex(m_ClassIndex);
}
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
return instance;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for executing this class.
*
* @param args should contain arguments for the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new ClassAssigner(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ClusterMembership.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ClusterMembership.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.clusterers.AbstractDensityBasedClusterer;
import weka.clusterers.DensityBasedClusterer;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that uses a density-based clusterer to
* generate cluster membership values; filtered instances are composed of these
* values plus the class attribute (if set in the input data). If a (nominal)
* class attribute is set, the clusterer is run separately for each class. The
* class attribute (if set) and any user-specified attributes are ignored during
* the clustering operation
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <clusterer name>
* Full name of clusterer to use. eg:
* weka.clusterers.EM
* Additional options after the '--'.
* (default: weka.clusterers.EM)
* </pre>
*
* <pre>
* -I <att1,att2-att4,...>
* The range of attributes the clusterer should ignore.
* (the class attribute is automatically ignored)
* </pre>
*
* <!-- options-end -->
*
* Options after the -- are passed on to the clusterer.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author Eibe Frank
* @version $Revision$
*/
public class ClusterMembership extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 6675702504667714026L;
/** The clusterer */
protected DensityBasedClusterer m_clusterer = new weka.clusterers.EM();
/** Array for storing the clusterers */
protected DensityBasedClusterer[] m_clusterers;
/** Range of attributes to ignore */
protected Range m_ignoreAttributesRange;
/** Filter for removing attributes */
protected Filter m_removeAttributes;
/** The prior probability for each class */
protected double[] m_priors;
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = m_clusterer.getCapabilities();
result.enableAllClasses();
result.setMinimumNumberInstances(0);
return result;
}
/**
* Returns the Capabilities of this filter, makes sure that the class is never
* set (for the clusterer).
*
* @param data the data to use for customization
* @return the capabilities of this object, based on the data
* @see #getCapabilities()
*/
@Override
public Capabilities getCapabilities(Instances data) {
Instances newData;
newData = new Instances(data, 0);
newData.setClassIndex(-1);
return super.getCapabilities(newData);
}
/**
* tests the data whether the filter can actually handle it
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
@Override
protected void testInputFormat(Instances instanceInfo) throws Exception {
getCapabilities(instanceInfo).testWithFail(removeIgnored(instanceInfo));
}
/**
* 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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_removeAttributes = null;
m_priors = null;
return false;
}
/**
* filters all attributes that should be ignored
*
* @param data the data to filter
* @return the filtered data
* @throws Exception if filtering fails
*/
protected Instances removeIgnored(Instances data) throws Exception {
Instances result = data;
if (m_ignoreAttributesRange != null || data.classIndex() >= 0) {
result = new Instances(data);
m_removeAttributes = new Remove();
String rangeString = "";
if (m_ignoreAttributesRange != null) {
rangeString += m_ignoreAttributesRange.getRanges();
}
if (data.classIndex() >= 0) {
if (rangeString.length() > 0) {
rangeString += "," + (data.classIndex() + 1);
} else {
rangeString = "" + (data.classIndex() + 1);
}
}
((Remove) m_removeAttributes).setAttributeIndices(rangeString);
((Remove) m_removeAttributes).setInvertSelection(false);
m_removeAttributes.setInputFormat(data);
result = Filter.useFilter(data, m_removeAttributes);
}
return result;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (outputFormatPeek() == null) {
Instances toFilter = getInputFormat();
Instances[] toFilterIgnoringAttributes;
// Make subsets if class is nominal
if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) {
toFilterIgnoringAttributes = new Instances[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i] = new Instances(toFilter,
toFilter.numInstances());
}
for (int i = 0; i < toFilter.numInstances(); i++) {
toFilterIgnoringAttributes[(int) toFilter.instance(i).classValue()]
.add(toFilter.instance(i));
}
m_priors = new double[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i].compactify();
m_priors[i] = toFilterIgnoringAttributes[i].sumOfWeights();
}
Utils.normalize(m_priors);
} else {
toFilterIgnoringAttributes = new Instances[1];
toFilterIgnoringAttributes[0] = toFilter;
m_priors = new double[1];
m_priors[0] = 1;
}
// filter out attributes if necessary
for (int i = 0; i < toFilterIgnoringAttributes.length; i++) {
toFilterIgnoringAttributes[i] = removeIgnored(toFilterIgnoringAttributes[i]);
}
// build the clusterers
if ((toFilter.classIndex() <= 0)
|| !toFilter.classAttribute().isNominal()) {
m_clusterers = AbstractDensityBasedClusterer.makeCopies(m_clusterer, 1);
m_clusterers[0].buildClusterer(toFilterIgnoringAttributes[0]);
} else {
m_clusterers = AbstractDensityBasedClusterer.makeCopies(m_clusterer,
toFilter.numClasses());
for (int i = 0; i < m_clusterers.length; i++) {
if (toFilterIgnoringAttributes[i].numInstances() == 0) {
m_clusterers[i] = null;
} else {
m_clusterers[i].buildClusterer(toFilterIgnoringAttributes[i]);
}
}
}
// create output dataset
ArrayList<Attribute> attInfo = new ArrayList<Attribute>();
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) {
attInfo.add(new Attribute("pCluster_" + j + "_" + i));
}
}
}
if (toFilter.classIndex() >= 0) {
attInfo.add((Attribute) toFilter.classAttribute().copy());
}
attInfo.trimToSize();
Instances filtered = new Instances(toFilter.relationName()
+ "_clusterMembership", attInfo, 0);
if (toFilter.classIndex() >= 0) {
filtered.setClassIndex(filtered.numAttributes() - 1);
}
setOutputFormat(filtered);
// build new dataset
for (int i = 0; i < toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Converts logs back to density values.
*
* @param j the index of the clusterer
* @param in the instance to convert the logs back
* @return the densities
* @throws Exception if something goes wrong
*/
protected double[] logs2densities(int j, Instance in) throws Exception {
double[] logs = m_clusterers[j].logJointDensitiesForInstance(in);
for (int i = 0; i < logs.length; i++) {
logs[i] += Math.log(m_priors[j]);
}
return logs;
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
* @throws Exception if something goes wrong
*/
protected void convertInstance(Instance instance) throws Exception {
// set up values
double[] instanceVals = new double[outputFormatPeek().numAttributes()];
double[] tempvals;
if (instance.classIndex() >= 0) {
tempvals = new double[outputFormatPeek().numAttributes() - 1];
} else {
tempvals = new double[outputFormatPeek().numAttributes()];
}
int pos = 0;
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
double[] probs;
if (m_removeAttributes != null) {
m_removeAttributes.input(instance);
probs = logs2densities(j, m_removeAttributes.output());
} else {
probs = logs2densities(j, instance);
}
System.arraycopy(probs, 0, tempvals, pos, probs.length);
pos += probs.length;
}
}
tempvals = Utils.logs2probs(tempvals);
System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length);
if (instance.classIndex() >= 0) {
instanceVals[instanceVals.length - 1] = instance.classValue();
}
push(new DenseInstance(instance.weight(), instanceVals));
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option("\tFull name of clusterer to use. eg:\n"
+ "\t\tweka.clusterers.EM\n" + "\tAdditional options after the '--'.\n"
+ "\t(default: weka.clusterers.EM)", "W", 1, "-W <clusterer name>"));
newVector.addElement(new Option(
"\tThe range of attributes the clusterer should ignore."
+ "\n\t(the class attribute is automatically ignored)", "I", 1,
"-I <att1,att2-att4,...>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <clusterer name>
* Full name of clusterer to use. eg:
* weka.clusterers.EM
* Additional options after the '--'.
* (default: weka.clusterers.EM)
* </pre>
*
* <pre>
* -I <att1,att2-att4,...>
* The range of attributes the clusterer should ignore.
* (the class attribute is automatically ignored)
* </pre>
*
* <!-- options-end -->
*
* Options after the -- are passed on to the clusterer.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String clustererString = Utils.getOption('W', options);
if (clustererString.length() == 0) {
clustererString = weka.clusterers.EM.class.getName();
}
setDensityBasedClusterer((DensityBasedClusterer) Utils.forName(
DensityBasedClusterer.class, clustererString,
Utils.partitionOptions(options)));
setIgnoredAttributeIndices(Utils.getOption('I', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (!getIgnoredAttributeIndices().equals("")) {
options.add("-I");
options.add(getIgnoredAttributeIndices());
}
if (m_clusterer != null) {
options.add("-W");
options.add(getDensityBasedClusterer().getClass().getName());
}
if ((m_clusterer != null) && (m_clusterer instanceof OptionHandler)) {
String[] clustererOptions = ((OptionHandler) m_clusterer).getOptions();
if (clustererOptions.length > 0) {
options.add("--");
Collections.addAll(options, clustererOptions);
}
}
return options.toArray(new String[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 "A filter that uses a density-based clusterer to generate cluster "
+ "membership values; filtered instances are composed of these values "
+ "plus the class attribute (if set in the input data). If a (nominal) "
+ "class attribute is set, the clusterer is run separately for each "
+ "class. The class attribute (if set) and any user-specified "
+ "attributes are ignored during the clustering operation";
}
/**
* Returns a description of this option suitable for display as a tip text in
* the gui.
*
* @return description of this option
*/
public String densityBasedClustererTipText() {
return "The clusterer that will generate membership values for the instances.";
}
/**
* Set the clusterer for use in filtering
*
* @param newClusterer the clusterer to use
*/
public void setDensityBasedClusterer(DensityBasedClusterer newClusterer) {
m_clusterer = newClusterer;
}
/**
* Get the clusterer used by this filter
*
* @return the clusterer used
*/
public DensityBasedClusterer getDensityBasedClusterer() {
return m_clusterer;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoredAttributeIndicesTipText() {
return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last";
}
/**
* Gets ranges of attributes to be ignored.
*
* @return a string containing a comma-separated list of ranges
*/
public String getIgnoredAttributeIndices() {
if (m_ignoreAttributesRange == null) {
return "";
} else {
return m_ignoreAttributesRange.getRanges();
}
}
/**
* Sets the ranges of attributes to be ignored. If provided string is null, no
* attributes will be ignored.
*
* @param rangeList a string representing the list of attributes. eg:
* first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setIgnoredAttributeIndices(String rangeList) {
if ((rangeList == null) || (rangeList.length() == 0)) {
m_ignoreAttributesRange = null;
} else {
m_ignoreAttributesRange = new Range();
m_ignoreAttributesRange.setRanges(rangeList);
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new ClusterMembership(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Copy.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Copy.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that copies a range of
* attributes in the dataset. This is used in conjunction with other filters
* that overwrite attribute values during the course of their operation -- this
* filter allows the original attributes to be kept as well as the new
* attributes.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to copy. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. copy all non-specified columns)
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Copy extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -8543707493627441566L;
/** Stores which columns to copy */
protected Range m_CopyCols = new Range();
/**
* Stores the indexes of the selected attributes in order, once the dataset is
* seen
*/
protected int[] m_SelectedAttributes;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector
.addElement(new Option(
"\tSpecify list of columns to copy. First and last are valid\n"
+ "\tindexes. (default none)", "R", 1,
"-R <index1,index2-index4,...>"));
newVector.addElement(new Option(
"\tInvert matching sense (i.e. copy all non-specified columns)", "V", 0,
"-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to copy. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. copy all non-specified columns)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String copyList = Utils.getOption('R', options);
if (copyList.length() != 0) {
setAttributeIndices(copyList);
}
setInvertSelection(Utils.getFlag('V', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
return options.toArray(new String[0]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 a problem occurs setting the input format
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_CopyCols.setUpper(instanceInfo.numAttributes() - 1);
// Create the output buffer
Instances outputFormat = new Instances(instanceInfo, 0);
m_SelectedAttributes = m_CopyCols.getSelection();
for (int current : m_SelectedAttributes) {
// Create a copy of the attribute with a different name
Attribute origAttribute = instanceInfo.attribute(current);
outputFormat.insertAttributeAt(
origAttribute.copy("Copy of " + origAttribute.name()),
outputFormat.numAttributes());
}
// adapt locators
int[] newIndices = new int[instanceInfo.numAttributes() + m_SelectedAttributes.length];
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
newIndices[i] = i;
}
for (int i = 0; i < m_SelectedAttributes.length; i++) {
newIndices[instanceInfo.numAttributes() + i] = m_SelectedAttributes[i];
}
initInputLocators(instanceInfo, newIndices);
setOutputFormat(outputFormat);
return true;
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
double[] vals = new double[outputFormatPeek().numAttributes()];
for (int i = 0; i < getInputFormat().numAttributes(); i++) {
vals[i] = instance.value(i);
}
int j = getInputFormat().numAttributes();
for (int i = 0; i < m_SelectedAttributes.length; i++) {
int current = m_SelectedAttributes[i];
vals[i + j] = instance.value(current);
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy instance
return true;
}
/**
* 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 copies a range of attributes in the"
+ " dataset. This is used in conjunction with other filters that"
+ " overwrite attribute values during the course of their operation --"
+ " this filter allows the original attributes to be kept as well"
+ " as the new attributes.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Sets copy selected vs unselected action."
+ " If set to false, only the specified attributes will be copied;"
+ " If set to true, non-specified attributes will be copied.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_CopyCols.getInvert();
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are copied. If false
* selected columns are copied and unselected columns are kept. <br>
* Note: use this method before you call
* <code>setInputFormat(Instances)</code>, since the output format is
* determined in that method.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_CopyCols.setInvert(invert);
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_CopyCols.getRanges();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last<br>
* Note: use this method before you call
* <code>setInputFormat(Instances)</code>, since the output format is
* determined in that method.
* @throws Exception if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) throws Exception {
m_CopyCols.setRanges(rangeList);
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.<br>
* Note: use this method before you call
* <code>setInputFormat(Instances)</code>, since the output format is
* determined in that method.
* @throws Exception if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) throws Exception {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Copy(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/DateToNumeric.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* DateToNumeric.java
* Copyright (C) 2006-2017 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.*;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
/**
* <!-- globalinfo-start -->
* A filter for turning date attributes into numeric ones.
* The numeric value will be the number of milliseconds since January 1, 1970, 00:00:00 GMT,
* corresponding to the given date."
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of attributes to turn into numeric ones. Only date attributes will be converted.
* First and last are valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <!-- options-end -->
*
* @author eibe (eibe at waikato dot ac dot nz)
* @version $Revision: 14274 $
*/
public class DateToNumeric extends SimpleBatchFilter implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
private static final long serialVersionUID = -6614650822291796239L;
/** Stores which columns to turn into numeric attributes */
protected Range m_Cols = new Range("first-last");
/** The default columns to turn into numeric attributes */
protected String m_DefaultCols = "first-last";
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for turning date attributes into numeric ones. The numeric value will be the number " +
"of milliseconds since January 1, 1970, 00:00:00 GMT, corresponding to the given date.";
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(2);
result.addElement(new Option(
"\tSpecifies list of columns to convert. 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"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of attributes to turn into numeric ones. Only date attributes will be converted.
* First and last are valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setInvertSelection(Utils.getFlag('V', options));
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices(m_DefaultCols);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (!getAttributeIndices().equals("")) {
result.add("-R");
result.add(getAttributeIndices());
}
if (getInvertSelection()) {
result.add("-V");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " (date) attributes in the range will be turned into numeric attributes; if"
+ " true, only non-selected attributes will be turned into numeric attributes.";
}
/**
* Gets whether the supplied columns are to be worked on or the others.
*
* @return true if the supplied columns will be worked on
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether selected columns should be worked on or all the others apart
* from these. If true all the other columns are considered for conversion.
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets which attributes are to be turned into numeric attributes (only date attributes
* among the selection will be transformed).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Sets which attributes are to be transformed to numeric attributes (only date
* attributes among the selection will be transformed).
*
* @param value an array containing indexes of attributes to turn into numeric ones. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param data the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances data) throws Exception {
m_Cols.setUpper(data.numAttributes() - 1);
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < data.numAttributes(); i++) {
if (!m_Cols.isInRange(i) || !data.attribute(i).isDate()) {
atts.add(data.attribute(i));
} else {
Attribute newAtt = new Attribute(data.attribute(i).name());
newAtt.setWeight(data.attribute(i).weight());
atts.add(newAtt);
}
}
Instances result = new Instances(data.relationName(), atts, 0);
result.setClassIndex(data.classIndex());
return result;
}
/**
* This filter's output format is immediately available
*/
@Override
protected boolean hasImmediateOutputFormat() {
return true;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result = getOutputFormat();
for (int i = 0; i < instances.numInstances(); i++) {
Instance newInst = (Instance)instances.instance(i).copy();
// copy possible string, relational values
copyValues(newInst, false, instances, outputFormatPeek());
result.add(newInst);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14274 $");
}
/**
* Runs the filter with the given parameters. Use -h to list options.
*
* @param args the commandline options
*/
public static void main(String[] args) {
runFilter(new DateToNumeric(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Discretize.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.UnsupervisedFilter;
/**
* <!-- 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>
*
* <pre>
* -Y
* Use bin numbers rather than ranges for discretized attributes.
* </pre>
*
* <pre> -precision <integer>
* Precision for bin boundary labels.
* (default = 6 decimal places).</pre>
*
* <pre>-spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.</pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Discretize extends PotentialClassIgnorer implements UnsupervisedFilter, WeightedInstancesHandler, WeightedAttributesHandler {
/** 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;
/** Use bin numbers rather than ranges for discretized attributes. */
protected boolean m_UseBinNumbers = 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;
/** Precision for bin range labels */
protected int m_BinRangePrecision = 6;
/** Whether to spread attribute weight when creating binary attributes */
protected boolean m_SpreadAttributeWeight = false;
/** Constructor - initialises the filter */
public Discretize() {
this.m_DefaultCols = "first-last";
this.setAttributeIndices("first-last");
}
/**
* Another constructor, sets the attribute indices immediately
*
* @param cols the attribute indices
*/
public Discretize(final String cols) {
this.m_DefaultCols = cols;
this.setAttributeIndices(cols);
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
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"));
result.addElement(new Option("\tUse bin numbers rather than ranges for discretized attributes.", "Y", 0, "-Y"));
result.addElement(new Option("\tPrecision for bin boundary labels.\n\t" + "(default = 6 decimal places).", "precision", 1, "-precision <integer>"));
result.addElement(
new Option("\tWhen generating binary attributes, spread weight of old " + "attribute across new attributes. Do not give each new attribute the old weight.\n\t", "spread-attribute-weight", 0, "-spread-attribute-weight"));
result.addAll(Collections.list(super.listOptions()));
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>
*
* <pre>
* -Y
* Use bin numbers rather than ranges for discretized attributes.
* </pre>
*
* <pre> -precision <integer>
* Precision for bin boundary labels.
* (default = 6 decimal places).</pre>
*
* <pre>-spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setMakeBinary(Utils.getFlag('D', options));
this.setUseBinNumbers(Utils.getFlag('Y', options));
this.setUseEqualFrequency(Utils.getFlag('F', options));
this.setFindNumBins(Utils.getFlag('O', options));
this.setInvertSelection(Utils.getFlag('V', options));
String weight = Utils.getOption('M', options);
if (weight.length() != 0) {
this.setDesiredWeightOfInstancesPerInterval((new Double(weight)).doubleValue());
} else {
this.setDesiredWeightOfInstancesPerInterval(-1);
}
String numBins = Utils.getOption('B', options);
if (numBins.length() != 0) {
this.setBins(Integer.parseInt(numBins));
} else {
this.setBins(10);
}
String convertList = Utils.getOption('R', options);
if (convertList.length() != 0) {
this.setAttributeIndices(convertList);
} else {
this.setAttributeIndices(this.m_DefaultCols);
}
String precisionS = Utils.getOption("precision", options);
if (precisionS.length() > 0) {
this.setBinRangePrecision(Integer.parseInt(precisionS));
}
this.setSpreadAttributeWeight(Utils.getFlag("spread-attribute-weight", options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (this.getMakeBinary()) {
result.add("-D");
}
if (this.getUseBinNumbers()) {
result.add("-Y");
}
if (this.getUseEqualFrequency()) {
result.add("-F");
}
if (this.getFindNumBins()) {
result.add("-O");
}
if (this.getInvertSelection()) {
result.add("-V");
}
result.add("-B");
result.add("" + this.getBins());
result.add("-M");
result.add("" + this.getDesiredWeightOfInstancesPerInterval());
if (!this.getAttributeIndices().equals("")) {
result.add("-R");
result.add(this.getAttributeIndices());
}
result.add("-precision");
result.add("" + this.getBinRangePrecision());
if (this.getSpreadAttributeWeight()) {
result.add("-spread-attribute-weight");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
if (!this.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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
if (this.m_MakeBinary && this.m_IgnoreClass) {
throw new IllegalArgumentException("Can't ignore class when " + "changing the number of attributes!");
}
super.setInputFormat(instanceInfo);
this.m_DiscretizeCols.setUpper(instanceInfo.numAttributes() - 1);
this.m_CutPoints = null;
if (this.getFindNumBins() && this.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.
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.m_CutPoints != null) {
this.convertInstance(instance);
return true;
}
this.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 InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_CutPoints == null) {
this.calculateCutPoints();
this.setOutputFormat();
// If we implement saving cutfiles, save the cuts here
// Convert pending input instances
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
this.convertInstance(this.getInputFormat().instance(i));
}
}
this.flushInput();
this.m_NewBatch = true;
return (this.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 this.m_FindNumBins;
}
/**
* Set the value of FindNumBins.
*
* @param newFindNumBins Value to assign to FindNumBins.
*/
public void setFindNumBins(final boolean newFindNumBins) {
this.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 this.m_MakeBinary;
}
/**
* Sets whether binary attributes should be made for discretized ones.
*
* @param makeBinary if binary attributes are to be made
*/
public void setMakeBinary(final boolean makeBinary) {
this.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 useBinNumbersTipText() {
return "Use bin numbers (eg BXofY) rather than ranges for for discretized attributes";
}
/**
* Gets whether bin numbers rather than ranges should be used for discretized
* attributes.
*
* @return true if bin numbers should be used
*/
public boolean getUseBinNumbers() {
return this.m_UseBinNumbers;
}
/**
* Sets whether bin numbers rather than ranges should be used for discretized
* attributes.
*
* @param useBinNumbers if bin numbers should be used
*/
public void setUseBinNumbers(final boolean useBinNumbers) {
this.m_UseBinNumbers = useBinNumbers;
}
/**
* 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 this.m_DesiredWeightOfInstancesPerInterval;
}
/**
* Set the DesiredWeightOfInstancesPerInterval value.
*
* @param newDesiredNumber The new DesiredNumber value.
*/
public void setDesiredWeightOfInstancesPerInterval(final double newDesiredNumber) {
this.m_DesiredWeightOfInstancesPerInterval = newDesiredNumber;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useEqualFrequencyTipText() {
return "If set to true, equal-frequency binning will be used instead of" + " equal-width binning.";
}
/**
* Get the value of UseEqualFrequency.
*
* @return Value of UseEqualFrequency.
*/
public boolean getUseEqualFrequency() {
return this.m_UseEqualFrequency;
}
/**
* Set the value of UseEqualFrequency.
*
* @param newUseEqualFrequency Value to assign to UseEqualFrequency.
*/
public void setUseEqualFrequency(final boolean newUseEqualFrequency) {
this.m_UseEqualFrequency = newUseEqualFrequency;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String binsTipText() {
return "Number of bins.";
}
/**
* Gets the number of bins numeric attributes will be divided into
*
* @return the number of bins.
*/
public int getBins() {
return this.m_NumBins;
}
/**
* Sets the number of bins to divide each selected numeric attribute into
*
* @param numBins the number of bins
*/
public void setBins(final int numBins) {
this.m_NumBins = numBins;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected" + " (numeric) attributes in the range will be discretized; if" + " true, only non-selected attributes will be discretized.";
}
/**
* Gets whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return this.m_DiscretizeCols.getInvert();
}
/**
* Sets whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are deleted. If false
* selected columns are deleted and unselected columns are kept.
*
* @param invert the new invert setting
*/
public void setInvertSelection(final boolean invert) {
this.m_DiscretizeCols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on." + " This is a comma separated list of attribute indices, with" + " \"first\" and \"last\" valid values. Specify an inclusive" + " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return this.m_DiscretizeCols.getRanges();
}
/**
* Sets which attributes are to be Discretized (only numeric attributes among
* the selection will be Discretized).
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(final String rangeList) {
this.m_DiscretizeCols.setRanges(rangeList);
}
/**
* Sets which attributes are to be Discretized (only numeric attributes among
* the selection will be Discretized).
*
* @param attributes an array containing indexes of attributes to Discretize.
* Since the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(final int[] attributes) {
this.setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String spreadAttributeWeightTipText() {
return "When generating binary attributes, spread weight of old attribute across new attributes. " + "Do not give each new attribute the old weight.";
}
/**
* If true, when generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @param p whether weight is spread
*/
public void setSpreadAttributeWeight(final boolean p) {
this.m_SpreadAttributeWeight = p;
}
/**
* If true, when generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
*
* @return whether weight is spread
*/
public boolean getSpreadAttributeWeight() {
return this.m_SpreadAttributeWeight;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String binRangePrecisionTipText() {
return "The number of decimal places for cut points to use when generating bin labels";
}
/**
* Set the precision for bin boundaries. Only affects the boundary values used
* in the labels for the converted attributes; internal cutpoints are at full
* double precision.
*
* @param p the precision for bin boundaries
*/
public void setBinRangePrecision(final int p) {
this.m_BinRangePrecision = p;
}
/**
* Get the precision for bin boundaries. Only affects the boundary values used
* in the labels for the converted attributes; internal cutpoints are at full
* double precision.
*
* @return the precision for bin boundaries
*/
public int getBinRangePrecision() {
return this.m_BinRangePrecision;
}
/**
* Gets the cut points for an attribute
*
* @param attributeIndex the index (from 0) of the attribute to get the cut
* points of
* @return an array containing the cutpoints (or null if the attribute
* requested has been discretized into only one interval.)
*/
public double[] getCutPoints(final int attributeIndex) {
if (this.m_CutPoints == null) {
return null;
}
return this.m_CutPoints[attributeIndex];
}
/**
* Gets the bin ranges string for an attribute
*
* @param attributeIndex the index (from 0) of the attribute to get the bin
* ranges string of
* @return the bin ranges string (or null if the attribute requested has been
* discretized into only one interval.)
*/
public String getBinRangesString(final int attributeIndex) {
if (this.m_CutPoints == null) {
return null;
}
double[] cutPoints = this.m_CutPoints[attributeIndex];
if (cutPoints == null) {
return "All";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
if (first) {
first = false;
} else {
sb.append(',');
}
sb.append(binRangeString(cutPoints, j, this.getBinRangePrecision()));
}
return sb.toString();
}
/**
* Get a bin range string for a specified bin of some attribute's cut points.
*
* @param cutPoints The attribute's cut points; never null.
* @param j The bin number (zero based); never out of range.
* @param precision the precision for the range values
*
* @return The bin range string.
*/
private static String binRangeString(final double[] cutPoints, final int j, final int precision) {
assert cutPoints != null;
int n = cutPoints.length;
assert 0 <= j && j <= n;
return j == 0 ? "" + "(" + "-inf" + "-" + Utils.doubleToString(cutPoints[0], precision) + "]"
: j == n ? "" + "(" + Utils.doubleToString(cutPoints[n - 1], precision) + "-" + "inf" + ")" : "" + "(" + Utils.doubleToString(cutPoints[j - 1], precision) + "-" + Utils.doubleToString(cutPoints[j], precision) + "]";
}
/** Generate the cutpoints for each attribute
* @throws InterruptedException */
protected void calculateCutPoints() throws InterruptedException {
this.m_CutPoints = new double[this.getInputFormat().numAttributes()][];
for (int i = this.getInputFormat().numAttributes() - 1; i >= 0; i--) {
if ((this.m_DiscretizeCols.isInRange(i)) && (this.getInputFormat().attribute(i).isNumeric()) && (this.getInputFormat().classIndex() != i)) {
if (this.m_FindNumBins) {
this.findNumBins(i);
} else if (!this.m_UseEqualFrequency) {
this.calculateCutPointsByEqualWidthBinning(i);
} else {
this.calculateCutPointsByEqualFrequencyBinning(i);
}
}
}
}
/**
* Set cutpoints for a single attribute.
*
* @param index the index of the attribute to set cutpoints for
*/
protected void calculateCutPointsByEqualWidthBinning(final int index) {
// Scan for max and min values
double max = 0, min = 1, currentVal;
Instance currentInstance;
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
currentInstance = this.getInputFormat().instance(i);
if (!currentInstance.isMissing(index)) {
currentVal = currentInstance.value(index);
if (max < min) {
max = min = currentVal;
}
if (currentVal > max) {
max = currentVal;
}
if (currentVal < min) {
min = currentVal;
}
}
}
double binWidth = (max - min) / this.m_NumBins;
double[] cutPoints = null;
if ((this.m_NumBins > 1) && (binWidth > 0)) {
cutPoints = new double[this.m_NumBins - 1];
for (int i = 1; i < this.m_NumBins; i++) {
cutPoints[i - 1] = min + binWidth * i;
}
}
this.m_CutPoints[index] = cutPoints;
}
/**
* Set cutpoints for a single attribute.
*
* @param index the index of the attribute to set cutpoints for
* @throws InterruptedException
*/
protected void calculateCutPointsByEqualFrequencyBinning(final int index) throws InterruptedException {
// Copy data so that it can be sorted
Instances data = new Instances(this.getInputFormat());
// Sort input data
data.sort(index);
// Compute weight of instances without missing values
double sumOfWeights = 0;
for (int i = 0; i < data.numInstances(); i++) {
if (data.instance(i).isMissing(index)) {
break;
} else {
sumOfWeights += data.instance(i).weight();
}
}
double freq;
double[] cutPoints = new double[this.m_NumBins - 1];
if (this.getDesiredWeightOfInstancesPerInterval() > 0) {
freq = this.getDesiredWeightOfInstancesPerInterval();
cutPoints = new double[(int) (sumOfWeights / freq)];
} else {
freq = sumOfWeights / this.m_NumBins;
cutPoints = new double[this.m_NumBins - 1];
}
// Compute break points
double counter = 0, last = 0;
int cpindex = 0, lastIndex = -1;
for (int i = 0; i < data.numInstances() - 1; i++) {
// Stop if value missing
if (data.instance(i).isMissing(index)) {
break;
}
counter += data.instance(i).weight();
sumOfWeights -= data.instance(i).weight();
// Do we have a potential breakpoint?
if (data.instance(i).value(index) < data.instance(i + 1).value(index)) {
// Have we passed the ideal size?
if (counter >= freq) {
// Is this break point worse than the last one?
if (((freq - last) < (counter - freq)) && (lastIndex != -1)) {
cutPoints[cpindex] = (data.instance(lastIndex).value(index) + data.instance(lastIndex + 1).value(index)) / 2;
counter -= last;
last = counter;
lastIndex = i;
} else {
cutPoints[cpindex] = (data.instance(i).value(index) + data.instance(i + 1).value(index)) / 2;
counter = 0;
last = 0;
lastIndex = -1;
}
cpindex++;
freq = (sumOfWeights + counter) / ((cutPoints.length + 1) - cpindex);
} else {
lastIndex = i;
last = counter;
}
}
}
// Check whether there was another possibility for a cut point
if ((cpindex < cutPoints.length) && (lastIndex != -1)) {
cutPoints[cpindex] = (data.instance(lastIndex).value(index) + data.instance(lastIndex + 1).value(index)) / 2;
cpindex++;
}
// Did we find any cutpoints?
if (cpindex == 0) {
this.m_CutPoints[index] = null;
} else {
double[] cp = new double[cpindex];
for (int i = 0; i < cpindex; i++) {
cp[i] = cutPoints[i];
}
this.m_CutPoints[index] = cp;
}
}
/**
* Optimizes the number of bins using leave-one-out cross-validation.
*
* @param index the attribute index
* @throws InterruptedException
*/
protected void findNumBins(final int index) throws InterruptedException {
double min = Double.MAX_VALUE, max = -Double.MAX_VALUE, binWidth = 0, entropy, bestEntropy = Double.MAX_VALUE, currentVal;
double[] distribution;
int bestNumBins = 1;
Instance currentInstance;
// Find minimum and maximum
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
currentInstance = this.getInputFormat().instance(i);
if (!currentInstance.isMissing(index)) {
currentVal = currentInstance.value(index);
if (currentVal > max) {
max = currentVal;
}
if (currentVal < min) {
min = currentVal;
}
}
}
// Find best number of bins
for (int i = 0; i < this.m_NumBins; i++) {
distribution = new double[i + 1];
binWidth = (max - min) / (i + 1);
// Compute distribution
for (int j = 0; j < this.getInputFormat().numInstances(); j++) {
currentInstance = this.getInputFormat().instance(j);
if (!currentInstance.isMissing(index)) {
for (int k = 0; k < i + 1; k++) {
if (currentInstance.value(index) <= (min + (((double) k + 1) * binWidth))) {
distribution[k] += currentInstance.weight();
break;
}
}
}
}
// Compute cross-validated entropy
entropy = 0;
for (int k = 0; k < i + 1; k++) {
if (distribution[k] < 2) {
entropy = Double.MAX_VALUE;
break;
}
entropy -= distribution[k] * Math.log((distribution[k] - 1) / binWidth);
}
// Best entropy so far?
if (entropy < bestEntropy) {
bestEntropy = entropy;
bestNumBins = i + 1;
}
}
// Compute cut points
double[] cutPoints = null;
if ((bestNumBins > 1) && (binWidth > 0)) {
cutPoints = new double[bestNumBins - 1];
for (int i = 1; i < bestNumBins; i++) {
cutPoints[i - 1] = min + binWidth * i;
}
}
this.m_CutPoints[index] = cutPoints;
}
/**
* Set the output format. Takes the currently defined cutpoints and
* m_InputFormat and calls setOutputFormat(Instances) appropriately.
*/
protected void setOutputFormat() {
if (this.m_CutPoints == null) {
this.setOutputFormat(null);
return;
}
ArrayList<Attribute> attributes = new ArrayList<Attribute>(this.getInputFormat().numAttributes());
int classIndex = this.getInputFormat().classIndex();
for (int i = 0, m = this.getInputFormat().numAttributes(); i < m; ++i) {
if ((this.m_DiscretizeCols.isInRange(i)) && (this.getInputFormat().attribute(i).isNumeric()) && (this.getInputFormat().classIndex() != i)) {
Set<String> cutPointsCheck = new HashSet<String>();
double[] cutPoints = this.m_CutPoints[i];
if (!this.m_MakeBinary) {
ArrayList<String> attribValues;
if (cutPoints == null) {
attribValues = new ArrayList<String>(1);
attribValues.add("'All'");
} else {
attribValues = new ArrayList<String>(cutPoints.length + 1);
if (this.m_UseBinNumbers) {
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
attribValues.add("'B" + (j + 1) + "of" + (n + 1) + "'");
}
} else {
for (int j = 0, n = cutPoints.length; j <= n; ++j) {
String newBinRangeString = binRangeString(cutPoints, j, this.getBinRangePrecision());
if (!cutPointsCheck.add(newBinRangeString)) {
throw new IllegalArgumentException("A duplicate bin range was detected. Try increasing the bin range precision.");
}
attribValues.add("'" + newBinRangeString + "'");
}
}
}
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name(), attribValues);
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
attributes.add(newAtt);
} else {
if (cutPoints == null) {
ArrayList<String> attribValues = new ArrayList<String>(1);
attribValues.add("'All'");
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name(), attribValues);
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
attributes.add(newAtt);
} else {
if (i < this.getInputFormat().classIndex()) {
classIndex += cutPoints.length - 1;
}
for (int j = 0, n = cutPoints.length; j < n; ++j) {
ArrayList<String> attribValues = new ArrayList<String>(2);
if (this.m_UseBinNumbers) {
attribValues.add("'B1of2'");
attribValues.add("'B2of2'");
} else {
double[] binaryCutPoint = { cutPoints[j] };
String newBinRangeString1 = binRangeString(binaryCutPoint, 0, this.m_BinRangePrecision);
String newBinRangeString2 = binRangeString(binaryCutPoint, 1, this.m_BinRangePrecision);
if (newBinRangeString1.equals(newBinRangeString2)) {
throw new IllegalArgumentException("A duplicate bin range was detected. Try increasing the bin range precision.");
}
attribValues.add("'" + newBinRangeString1 + "'");
attribValues.add("'" + newBinRangeString2 + "'");
}
Attribute newAtt = new Attribute(this.getInputFormat().attribute(i).name() + "_" + (j + 1), attribValues);
if (this.getSpreadAttributeWeight()) {
newAtt.setWeight(this.getInputFormat().attribute(i).weight() / cutPoints.length);
} else {
newAtt.setWeight(this.getInputFormat().attribute(i).weight());
}
attributes.add(newAtt);
}
}
}
} else {
attributes.add((Attribute) this.getInputFormat().attribute(i).copy());
}
}
Instances outputFormat = new Instances(this.getInputFormat().relationName(), attributes, 0);
outputFormat.setClassIndex(classIndex);
this.setOutputFormat(outputFormat);
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
*/
protected void convertInstance(final Instance instance) {
int index = 0;
double[] vals = new double[this.outputFormatPeek().numAttributes()];
// Copy and convert the values
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
if (this.m_DiscretizeCols.isInRange(i) && this.getInputFormat().attribute(i).isNumeric() && (this.getInputFormat().classIndex() != i)) {
int j;
double currentVal = instance.value(i);
if (this.m_CutPoints[i] == null) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else {
vals[index] = 0;
}
index++;
} else {
if (!this.m_MakeBinary) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else {
for (j = 0; j < this.m_CutPoints[i].length; j++) {
if (currentVal <= this.m_CutPoints[i][j]) {
break;
}
}
vals[index] = j;
}
index++;
} else {
for (j = 0; j < this.m_CutPoints[i].length; j++) {
if (instance.isMissing(i)) {
vals[index] = Utils.missingValue();
} else if (currentVal <= this.m_CutPoints[i][j]) {
vals[index] = 0;
} else {
vals[index] = 1;
}
index++;
}
}
}
} else {
vals[index] = instance.value(i);
index++;
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
this.copyValues(inst, false, instance.dataset(), this.outputFormatPeek());
this.push(inst); // No need to copy instance
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new Discretize(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/FirstOrder.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* FirstOrder.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> This instance filter takes a range of N numeric
* attributes and replaces them with N-1 numeric attributes, the values of which
* are the difference between consecutive attribute values from the original
* instance. eg: <br/>
* <br/>
* Original attribute values<br/>
* <br/>
* 0.1, 0.2, 0.3, 0.1, 0.3<br/>
* <br/>
* New attribute values<br/>
* <br/>
* 0.1, 0.1, -0.2, 0.2<br/>
* <br/>
* The range of attributes used is taken in numeric order. That is, a range spec
* of 7-11,3-5 will use the attribute ordering 3,4,5,7,8,9,10,11 for the
* differences, NOT 7,8,9,10,11,3,4,5.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to take the differences between.
* First and last are valid indexes.
* (default none)
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class FirstOrder extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -7500464545400454179L;
/** Stores which columns to take differences between */
protected Range m_DeltaCols = new Range();
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "This instance filter takes a range of N numeric attributes and replaces "
+ "them with N-1 numeric attributes, the values of which are the difference "
+ "between consecutive attribute values from the original instance. eg: \n\n"
+ "Original attribute values\n\n"
+ " 0.1, 0.2, 0.3, 0.1, 0.3\n\n"
+ "New attribute values\n\n"
+ " 0.1, 0.1, -0.2, 0.2\n\n"
+ "The range of attributes used is taken in numeric order. That is, a range "
+ "spec of 7-11,3-5 will use the attribute ordering 3,4,5,7,8,9,10,11 for the "
+ "differences, NOT 7,8,9,10,11,3,4,5.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(1);
newVector.addElement(new Option(
"\tSpecify list of columns to take the differences between.\n"
+ "\tFirst and last are valid indexes.\n" + "\t(default none)", "R", 1,
"-R <index1,index2-index4,...>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to take the differences between.
* First and last are valid indexes.
* (default none)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String deltaList = Utils.getOption('R', options);
if (deltaList.length() != 0) {
setAttributeIndices(deltaList);
} else {
setAttributeIndices("");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
return options.toArray(new String[0]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if any of the selected attributes
* are not numeric
* @throws Exception if only one attribute has been selected.
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_DeltaCols.setUpper(getInputFormat().numAttributes() - 1);
int selectedCount = 0;
for (int i = getInputFormat().numAttributes() - 1; i >= 0; i--) {
if (m_DeltaCols.isInRange(i)) {
selectedCount++;
if (!getInputFormat().attribute(i).isNumeric()) {
throw new UnsupportedAttributeTypeException(
"Selected attributes must be all numeric");
}
}
}
if (selectedCount == 1) {
throw new Exception("Cannot select only one attribute.");
}
// Create the output buffer
ArrayList<Attribute> newAtts = new ArrayList<Attribute>();
boolean inRange = false;
String foName = null;
int clsIndex = -1;
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_DeltaCols.isInRange(i) && (i != instanceInfo.classIndex())) {
if (inRange) {
Attribute newAttrib = new Attribute(foName);
newAtts.add(newAttrib);
}
foName = instanceInfo.attribute(i).name();
foName = "'FO " + foName.replace('\'', ' ').trim() + '\'';
inRange = true;
} else {
newAtts.add((Attribute) instanceInfo.attribute(i).copy());
if ((i == instanceInfo.classIndex())) {
clsIndex = newAtts.size() - 1;
}
}
}
Instances data = new Instances(instanceInfo.relationName(), newAtts, 0);
data.setClassIndex(clsIndex);
setOutputFormat(data);
return true;
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instances outputFormat = outputFormatPeek();
double[] vals = new double[outputFormat.numAttributes()];
boolean inRange = false;
double lastVal = Utils.missingValue();
int i, j;
for (i = 0, j = 0; j < outputFormat.numAttributes(); i++) {
if (m_DeltaCols.isInRange(i) && (i != instance.classIndex())) {
if (inRange) {
if (Utils.isMissingValue(lastVal) || instance.isMissing(i)) {
vals[j++] = Utils.missingValue();
} else {
vals[j++] = instance.value(i) - lastVal;
}
} else {
inRange = true;
}
lastVal = instance.value(i);
} else {
vals[j++] = instance.value(i);
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy instance
return true;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_DeltaCols.getRanges();
}
/**
* Set which attributes are to be deleted (or kept if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws Exception if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) throws Exception {
m_DeltaCols.setRanges(rangeList);
}
/**
* Set which attributes are to be deleted (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
* @throws Exception if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) throws Exception {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new FirstOrder(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/FixedDictionaryStringToWordVector.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* FixedDictionaryStringToWordVector.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import javax.swing.JFileChooser;
import weka.core.*;
import weka.core.stemmers.NullStemmer;
import weka.core.stemmers.Stemmer;
import weka.core.stopwords.Null;
import weka.core.stopwords.StopwordsHandler;
import weka.core.tokenizers.Tokenizer;
import weka.filters.SimpleStreamFilter;
import weka.filters.UnsupervisedFilter;
import weka.gui.FilePropertyMetadata;
/**
* <!-- globalinfo-start --> Converts String attributes into a set of attributes
* representing word occurrence (depending on the tokenizer) information from
* the text contained in the strings. The set of words (attributes) is taken
* from a user-supplied dictionary, either in plain text form or as a serialized
* java object. <br>
* <br>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p>
*
* <pre>
* -dictionary <path to dictionary file>
* The path to the dictionary to use
* </pre>
*
* <pre>
* -binary-dict
* Dictionary file contains a binary serialized dictionary
* </pre>
*
* <pre>
* -C
* Output word counts rather than boolean 0 or 1 (indicating presence or absence of a word
* </pre>
*
* <pre>
* -R <range>
* Specify range of attributes to act on. This is a comma separated list of attribute
* indices, with "first" and "last" valid values.
* </pre>
*
* <pre>
* -V
* Set attributes selection mode. If false, only selected attributes in the range will
* be worked on. If true, only non-selected attributes will be processed
* </pre>
*
* <pre>
* -P <attribute name prefix>
* Specify a prefix for the created attribute names (default: "")
* </pre>
*
* <pre>
* -T
* Set whether the word frequencies should be transformed into
* log(1+fij), where fij is the frequency of word i in document (instance) j.
* </pre>
*
* <pre>
* -I
* Set whether the word frequencies in a document should be transformed into
* fij*log(num of Docs/num of docs with word i), where fij is the frequency
* of word i in document (instance) j.
* </pre>
*
* <pre>
* -N
* Whether to normalize to average length of documents seen during dictionary construction
* </pre>
*
* <pre>
* -L
* Convert all tokens to lowercase when matching against dictionary entries.
* </pre>
*
* <pre>
* -stemmer <spec>
* The stemming algorithm (classname plus parameters) to use.
* </pre>
*
* <pre>
* -stopwords-handler <spec>
* The stopwords handler to use (default = Null)
* </pre>
*
* <pre>
* -tokenizer <spec>
* The tokenizing algorithm (classname plus parameters) to use.
* (default: weka.core.tokenizers.WordTokenizer)
* </pre>
*
* <pre>
* -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console
* </pre>
*
* <pre>
* -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class FixedDictionaryStringToWordVector extends SimpleStreamFilter
implements UnsupervisedFilter, EnvironmentHandler, WeightedInstancesHandler {
private static final long serialVersionUID = 7990892846966916757L;
protected DictionaryBuilder m_vectorizer = new DictionaryBuilder();
protected File m_dictionaryFile = new File("-- set me --");
/** Source stream to read a binary serialized dictionary from */
protected transient InputStream m_dictionarySource;
/** Source reader to read a textual dictionary from */
protected transient Reader m_textDictionarySource;
/**
* Whether the dictionary file contains a binary serialized dictionary, rather
* than plain text - used when loading from a file in order to differentiate
*/
protected boolean m_dictionaryIsBinary;
protected transient Environment m_env = Environment.getSystemWide();
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capabilities.Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
/**
* Get the dictionary builder used to manage the dictionary and perform the
* actual vectorization
*
* @return the DictionaryBuilder in use
*/
public DictionaryBuilder getDictionaryHandler() {
return m_vectorizer;
}
/**
* Set an input stream to load a binary serialized dictionary from, rather
* than source it from a file
*
* @param source the input stream to read the dictionary from
*/
public void setDictionarySource(InputStream source) {
m_dictionarySource = source;
}
/**
* Set an input reader to load a textual dictionary from, rather than source
* it from a file
*
* @param source the input reader to read the dictionary from
*/
public void setDictionarySource(Reader source) {
m_textDictionarySource = source;
}
/**
* Set the dictionary file to read from
*
* @param file the file to read from
*/
@OptionMetadata(displayName = "Dictionary file",
description = "The path to the dictionary to use",
commandLineParamName = "dictionary",
commandLineParamSynopsis = "-dictionary <path to dictionary file>",
displayOrder = 1)
@FilePropertyMetadata(fileChooserDialogType = JFileChooser.OPEN_DIALOG,
directoriesOnly = false)
public void setDictionaryFile(File file) {
m_dictionaryFile = file;
}
/**
* Get the dictionary file to read from
*
* @return the dictionary file to read from
*/
public File getDictionaryFile() {
return m_dictionaryFile;
}
/**
* Set whether the dictionary file contains a binary serialized dictionary,
* rather than a plain text one
*
* @param binary true if the dictionary is a binary serialized one
*/
@OptionMetadata(displayName = "Dictionary is binary",
description = "Dictionary file contains a binary serialized dictionary",
commandLineParamName = "binary-dict",
commandLineParamSynopsis = "-binary-dict", commandLineParamIsFlag = true,
displayOrder = 2)
public void setDictionaryIsBinary(boolean binary) {
m_dictionaryIsBinary = binary;
}
public boolean getDictionaryIsBinary() {
return m_dictionaryIsBinary;
}
/**
* Gets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @return true if word counts should be output.
*/
public boolean getOutputWordCounts() {
return m_vectorizer.getOutputWordCounts();
}
/**
* Sets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @param outputWordCounts true if word counts should be output.
*/
@OptionMetadata(displayName = "Output word counts",
description = "Output word counts rather than boolean 0 or 1 (indicating presence or absence of "
+ "a word",
commandLineParamName = "C", commandLineParamSynopsis = "-C",
commandLineParamIsFlag = true, displayOrder = 3)
public void setOutputWordCounts(boolean outputWordCounts) {
m_vectorizer.setOutputWordCounts(outputWordCounts);
}
/**
* Gets the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_vectorizer.getAttributeIndices();
}
/**
* Sets which attributes are to be worked on.
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
@OptionMetadata(displayName = "Range of attributes to operate on",
description = "Specify range of attributes to act on. This is a comma "
+ "separated list of attribute\nindices, with \"first\" and "
+ "\"last\" valid values.",
commandLineParamName = "R", commandLineParamSynopsis = "-R <range>",
displayOrder = 4)
public void setAttributeIndices(String rangeList) {
m_vectorizer.setAttributeIndices(rangeList);
}
/**
* Gets whether the supplied columns are to be processed or skipped.
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_vectorizer.getInvertSelection();
}
/**
* Sets whether selected columns should be processed or skipped.
*
* @param invert the new invert setting
*/
@OptionMetadata(displayName = "Invert selection",
description = "Set attributes selection mode. "
+ "If false, only selected attributes in the range will\nbe worked on. If true, "
+ "only non-selected attributes will be processed",
commandLineParamName = "V", commandLineParamSynopsis = "-V",
commandLineParamIsFlag = true, displayOrder = 5)
public void setInvertSelection(boolean invert) {
m_vectorizer.setInvertSelection(invert);
}
/**
* Get the attribute name prefix.
*
* @return The current attribute name prefix.
*/
public String getAttributeNamePrefix() {
return m_vectorizer.getAttributeNamePrefix();
}
/**
* Set the attribute name prefix.
*
* @param newPrefix String to use as the attribute name prefix.
*/
@OptionMetadata(displayName = "Prefix for created attribute names",
description = "Specify a prefix for the created attribute names "
+ "(default: \"\")",
commandLineParamName = "P",
commandLineParamSynopsis = "-P <attribute name prefix>", displayOrder = 6)
public void setAttributeNamePrefix(String newPrefix) {
m_vectorizer.setAttributeNamePrefix(newPrefix);
}
/**
* Gets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @return true if word frequencies are to be transformed.
*/
public boolean getTFTransform() {
return m_vectorizer.getTFTransform();
}
/**
* Sets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @param TFTransform true if word frequencies are to be transformed.
*/
@OptionMetadata(displayName = "TFT transform",
description = "Set whether the word frequencies should be transformed into\n"
+ "log(1+fij), where fij is the frequency of word i in document (instance) "
+ "j.",
commandLineParamName = "T", commandLineParamSynopsis = "-T",
displayOrder = 7)
public void setTFTransform(boolean TFTransform) {
m_vectorizer.setTFTransform(TFTransform);
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @return true if the word frequencies are to be transformed.
*/
public boolean getIDFTransform() {
return m_vectorizer.getIDFTransform();
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @param IDFTransform true if the word frequecies are to be transformed
*/
@OptionMetadata(displayName = "IDF transform",
description = "Set whether the word frequencies in a document should be "
+ "transformed into\nfij*log(num of Docs/num of docs with word i), "
+ "where fij is the frequency\nof word i in document (instance) j.",
commandLineParamName = "I", commandLineParamSynopsis = "-I",
displayOrder = 8)
public void setIDFTransform(boolean IDFTransform) {
m_vectorizer.setIDFTransform(IDFTransform);
}
/**
* Sets whether if the word frequencies for a document (instance) should be
* normalized or not.
*
* @param normalize the new type.
*/
@OptionMetadata(displayName = "Normalize word frequencies",
description = "Whether to normalize to average length of documents seen "
+ "during dictionary construction",
commandLineParamName = "N", commandLineParamSynopsis = "-N",
commandLineParamIsFlag = true, displayOrder = 9)
public void setNormalizeDocLength(boolean normalize) {
m_vectorizer.setNormalize(normalize);
}
/**
* Gets whether if the word frequencies for a document (instance) should be
* normalized or not.
*
* @return true if word frequencies are to be normalized.
*/
public boolean getNormalizeDocLength() {
return m_vectorizer.getNormalize();
}
/**
* Gets whether if the tokens are to be downcased or not.
*
* @return true if the tokens are to be downcased.
*/
public boolean getLowerCaseTokens() {
return m_vectorizer.getLowerCaseTokens();
}
/**
* Sets whether if the tokens are to be downcased or not. (Doesn't affect
* non-alphabetic characters in tokens).
*
* @param downCaseTokens should be true if only lower case tokens are to be
* formed.
*/
@OptionMetadata(displayName = "Lower case tokens",
description = "Convert all tokens to lowercase when matching against "
+ "dictionary entries.",
commandLineParamName = "L", commandLineParamSynopsis = "-L",
commandLineParamIsFlag = true, displayOrder = 10)
public void setLowerCaseTokens(boolean downCaseTokens) {
m_vectorizer.setLowerCaseTokens(downCaseTokens);
}
/**
* the stemming algorithm to use, null means no stemming at all (i.e., the
* NullStemmer is used).
*
* @param value the configured stemming algorithm, or null
* @see NullStemmer
*/
@OptionMetadata(displayName = "Stemmer to use",
description = "The stemming algorithm (classname plus parameters) to use.",
commandLineParamName = "stemmer",
commandLineParamSynopsis = "-stemmer <spec>", displayOrder = 11)
public void setStemmer(Stemmer value) {
if (value != null) {
m_vectorizer.setStemmer(value);
} else {
m_vectorizer.setStemmer(new NullStemmer());
}
}
/**
* Returns the current stemming algorithm, null if none is used.
*
* @return the current stemming algorithm, null if none set
*/
public Stemmer getStemmer() {
return m_vectorizer.getStemmer();
}
/**
* Sets the stopwords handler to use.
*
* @param value the stopwords handler, if null, Null is used
*/
@OptionMetadata(displayName = "Stop words handler",
description = "The stopwords handler to use (default = Null)",
commandLineParamName = "stopwords-handler",
commandLineParamSynopsis = "-stopwords-handler <spec>", displayOrder = 12)
public void setStopwordsHandler(StopwordsHandler value) {
if (value != null) {
m_vectorizer.setStopwordsHandler(value);
} else {
m_vectorizer.setStopwordsHandler(new Null());
}
}
/**
* Gets the stopwords handler.
*
* @return the stopwords handler
*/
public StopwordsHandler getStopwordsHandler() {
return m_vectorizer.getStopwordsHandler();
}
/**
* the tokenizer algorithm to use.
*
* @param value the configured tokenizing algorithm
*/
@OptionMetadata(displayName = "Tokenizer",
description = "The tokenizing algorithm (classname plus parameters) to use.\n"
+ "(default: weka.core.tokenizers.WordTokenizer)",
commandLineParamName = "tokenizer",
commandLineParamSynopsis = "-tokenizer <spec>", displayOrder = 13)
public void setTokenizer(Tokenizer value) {
m_vectorizer.setTokenizer(value);
}
/**
* Returns the current tokenizer algorithm.
*
* @return the current tokenizer algorithm
*/
public Tokenizer getTokenizer() {
return m_vectorizer.getTokenizer();
}
@Override
public String globalInfo() {
return "Converts String attributes into a set of attributes representing "
+ "word occurrence (depending on the tokenizer) information from the "
+ "text contained in the strings. The set of words (attributes) is "
+ "taken from a user-supplied dictionary, either in plain text form or "
+ "as a serialized java object.";
}
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
if (m_vectorizer.readyToVectorize()
&& inputFormat.equalHeaders(m_vectorizer.getInputFormat())) {
return m_vectorizer.getVectorizedFormat();
}
m_vectorizer.reset();
m_vectorizer.setup(inputFormat);
if (m_dictionaryFile == null && m_dictionarySource == null
&& m_textDictionarySource == null) {
throw new IOException("No dictionary file/source specified!");
}
if (m_dictionarySource != null) {
m_vectorizer.loadDictionary(m_dictionarySource);
} else if (m_textDictionarySource != null) {
m_vectorizer.loadDictionary(m_textDictionarySource);
} else {
String fString = m_dictionaryFile.toString();
if (fString.length() == 0) {
throw new IOException("No dictionary file specified!");
}
try {
fString = m_env.substitute(fString);
} catch (Exception ex) {
//
}
File dictFile = new File(fString);
if (!dictFile.exists()) {
throw new IOException("Specified dictionary file '" + fString
+ "' does not seem to exist!");
}
m_vectorizer.loadDictionary(dictFile, !m_dictionaryIsBinary);
}
return m_vectorizer.getVectorizedFormat();
}
@Override
protected Instance process(Instance instance) throws Exception {
return m_vectorizer.vectorizeInstance(instance);
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
public static void main(String[] args) {
runFilter(new FixedDictionaryStringToWordVector(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/InterquartileRange.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* InterquartileRange.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.filters.SimpleBatchFilter;
/**
* <!-- globalinfo-start --> A filter for detecting outliers and extreme values
* based on interquartile ranges. The filter skips the class attribute.<br/>
* <br/>
* Outliers:<br/>
* Q3 + OF*IQR < x <= Q3 + EVF*IQR<br/>
* or<br/>
* Q1 - EVF*IQR <= x < Q1 - OF*IQR<br/>
* <br/>
* Extreme values:<br/>
* x > Q3 + EVF*IQR<br/>
* or<br/>
* x < Q1 - EVF*IQR<br/>
* <br/>
* Key:<br/>
* Q1 = 25% quartile<br/>
* Q3 = 75% quartile<br/>
* IQR = Interquartile Range, difference between Q1 and Q3<br/>
* OF = Outlier Factor<br/>
* EVF = Extreme Value Factor
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to base outlier/extreme value detection
* on. If an instance is considered in at least one of those
* attributes an outlier/extreme value, it is tagged accordingly.
* 'first' and 'last' are valid indexes.
* (default none)
* </pre>
*
* <pre>
* -O <num>
* The factor for outlier detection.
* (default: 3)
* </pre>
*
* <pre>
* -E <num>
* The factor for extreme values detection.
* (default: 2*Outlier Factor)
* </pre>
*
* <pre>
* -E-as-O
* Tags extreme values also as outliers.
* (default: off)
* </pre>
*
* <pre>
* -P
* Generates Outlier/ExtremeValue pair for each numeric attribute in
* the range, not just a single indicator pair for all the attributes.
* (default: off)
* </pre>
*
* <pre>
* -M
* Generates an additional attribute 'Offset' per Outlier/ExtremeValue
* pair that contains the multiplier that the value is off the median.
* value = median + 'multiplier' * IQR
* Note: implicitely sets '-P'. (default: off)
* </pre>
*
* <!-- options-end -->
*
* Thanks to Dale for a few brainstorming sessions.
*
* @author Dale Fletcher (dale at cs dot waikato dot ac dot nz)
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class InterquartileRange extends SimpleBatchFilter implements WeightedAttributesHandler {
/** for serialization */
private static final long serialVersionUID = -227879653639723030L;
/** indicator for non-numeric attributes */
public final static int NON_NUMERIC = -1;
/** enum for obtaining the various determined IQR values. */
public enum ValueType {
UPPER_EXTREME_VALUES, UPPER_OUTLIER_VALUES, LOWER_OUTLIER_VALUES, LOWER_EXTREME_VALUES, MEDIAN, IQR
};
/** the attribute range to work on */
protected Range m_Attributes = new Range("first-last");
/** the generated indices (only for performance reasons) */
protected int[] m_AttributeIndices = null;
/** the factor for detecting outliers */
protected double m_OutlierFactor = 3;
/** the factor for detecting extreme values, by default 2*m_OutlierFactor */
protected double m_ExtremeValuesFactor = 2 * this.m_OutlierFactor;
/** whether extreme values are also tagged as outliers */
protected boolean m_ExtremeValuesAsOutliers = false;
/** the upper extreme value threshold (= Q3 + EVF*IQR) */
protected double[] m_UpperExtremeValue = null;
/** the upper outlier threshold (= Q3 + OF*IQR) */
protected double[] m_UpperOutlier = null;
/** the lower outlier threshold (= Q1 - OF*IQR) */
protected double[] m_LowerOutlier = null;
/** the interquartile range */
protected double[] m_IQR = null;
/** the median */
protected double[] m_Median = null;
/** the lower extreme value threshold (= Q1 - EVF*IQR) */
protected double[] m_LowerExtremeValue = null;
/**
* whether to generate Outlier/ExtremeValue attributes for each attribute
* instead of a general one
*/
protected boolean m_DetectionPerAttribute = false;
/** the position of the outlier attribute */
protected int[] m_OutlierAttributePosition = null;
/**
* whether to add another attribute called "Offset", that lists the
* 'multiplier' by which the outlier/extreme value is away from the median,
* i.e., value = median + 'multiplier' * IQR <br/>
* automatically enables m_DetectionPerAttribute!
*/
protected boolean m_OutputOffsetMultiplier = false;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for detecting outliers and extreme values based on " + "interquartile ranges. The filter skips the class attribute.\n\n" + "Outliers:\n" + " Q3 + OF*IQR < x <= Q3 + EVF*IQR\n" + " or\n"
+ " Q1 - EVF*IQR <= x < Q1 - OF*IQR\n" + "\n" + "Extreme values:\n" + " x > Q3 + EVF*IQR\n" + " or\n" + " x < Q1 - EVF*IQR\n" + "\n" + "Key:\n" + " Q1 = 25% quartile\n" + " Q3 = 75% quartile\n"
+ " IQR = Interquartile Range, difference between Q1 and Q3\n" + " OF = Outlier Factor\n" + " EVF = Extreme Value Factor";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tSpecifies list of columns to base outlier/extreme value detection\n" + "\ton. If an instance is considered in at least one of those\n"
+ "\tattributes an outlier/extreme value, it is tagged accordingly.\n" + " 'first' and 'last' are valid indexes.\n" + "\t(default none)", "R", 1, "-R <col1,col2-col4,...>"));
result.addElement(new Option("\tThe factor for outlier detection.\n" + "\t(default: 3)", "O", 1, "-O <num>"));
result.addElement(new Option("\tThe factor for extreme values detection.\n" + "\t(default: 2*Outlier Factor)", "E", 1, "-E <num>"));
result.addElement(new Option("\tTags extreme values also as outliers.\n" + "\t(default: off)", "E-as-O", 0, "-E-as-O"));
result.addElement(new Option("\tGenerates Outlier/ExtremeValue pair for each numeric attribute in\n" + "\tthe range, not just a single indicator pair for all the attributes.\n" + "\t(default: off)", "P", 0, "-P"));
result.addElement(new Option("\tGenerates an additional attribute 'Offset' per Outlier/ExtremeValue\n" + "\tpair that contains the multiplier that the value is off the median.\n" + "\t value = median + 'multiplier' * IQR\n"
+ "Note: implicitely sets '-P'." + "\t(default: off)", "M", 0, "-M"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to base outlier/extreme value detection
* on. If an instance is considered in at least one of those
* attributes an outlier/extreme value, it is tagged accordingly.
* 'first' and 'last' are valid indexes.
* (default none)
* </pre>
*
* <pre>
* -O <num>
* The factor for outlier detection.
* (default: 3)
* </pre>
*
* <pre>
* -E <num>
* The factor for extreme values detection.
* (default: 2*Outlier Factor)
* </pre>
*
* <pre>
* -E-as-O
* Tags extreme values also as outliers.
* (default: off)
* </pre>
*
* <pre>
* -P
* Generates Outlier/ExtremeValue pair for each numeric attribute in
* the range, not just a single indicator pair for all the attributes.
* (default: off)
* </pre>
*
* <pre>
* -M
* Generates an additional attribute 'Offset' per Outlier/ExtremeValue
* pair that contains the multiplier that the value is off the median.
* value = median + 'multiplier' * IQR
* Note: implicitely sets '-P'. (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr = Utils.getOption("R", options);
if (tmpStr.length() != 0) {
this.setAttributeIndices(tmpStr);
} else {
this.setAttributeIndices("first-last");
}
tmpStr = Utils.getOption("O", options);
if (tmpStr.length() != 0) {
this.setOutlierFactor(Double.parseDouble(tmpStr));
} else {
this.setOutlierFactor(3);
}
tmpStr = Utils.getOption("E", options);
if (tmpStr.length() != 0) {
this.setExtremeValuesFactor(Double.parseDouble(tmpStr));
} else {
this.setExtremeValuesFactor(2 * this.getOutlierFactor());
}
this.setExtremeValuesAsOutliers(Utils.getFlag("E-as-O", options));
this.setDetectionPerAttribute(Utils.getFlag("P", options));
this.setOutputOffsetMultiplier(Utils.getFlag("M", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
if (!this.getAttributeIndices().equals("")) {
result.add(this.getAttributeIndices());
} else {
result.add("first-last");
}
result.add("-O");
result.add("" + this.getOutlierFactor());
result.add("-E");
result.add("" + this.getExtremeValuesFactor());
if (this.getExtremeValuesAsOutliers()) {
result.add("-E-as-O");
}
if (this.getDetectionPerAttribute()) {
result.add("-P");
}
if (this.getOutputOffsetMultiplier()) {
result.add("-M");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on; " + " this is a comma separated list of attribute indices, with" + " \"first\" and \"last\" valid values; specify an inclusive" + " range with \"-\", eg: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return this.m_Attributes.getRanges();
}
/**
* Sets which attributes are to be used for interquartile calculations and
* outlier/extreme value detection (only numeric attributes among the
* selection will be used).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(final String value) {
this.m_Attributes.setRanges(value);
}
/**
* Sets which attributes are to be used for interquartile calculations and
* outlier/extreme value detection (only numeric attributes among the
* selection will be used).
*
* @param value an array containing indexes of attributes to work on. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(final int[] value) {
this.setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outlierFactorTipText() {
return "The factor for determining the thresholds for outliers.";
}
/**
* Sets the factor for determining the thresholds for outliers.
*
* @param value the factor.
*/
public void setOutlierFactor(final double value) {
if (value >= this.getExtremeValuesFactor()) {
System.err.println("OutlierFactor must be smaller than ExtremeValueFactor");
} else {
this.m_OutlierFactor = value;
}
}
/**
* Gets the factor for determining the thresholds for outliers.
*
* @return the factor.
*/
public double getOutlierFactor() {
return this.m_OutlierFactor;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String extremeValuesFactorTipText() {
return "The factor for determining the thresholds for extreme values.";
}
/**
* Sets the factor for determining the thresholds for extreme values.
*
* @param value the factor.
*/
public void setExtremeValuesFactor(final double value) {
if (value <= this.getOutlierFactor()) {
System.err.println("ExtremeValuesFactor must be greater than OutlierFactor!");
} else {
this.m_ExtremeValuesFactor = value;
}
}
/**
* Gets the factor for determining the thresholds for extreme values.
*
* @return the factor.
*/
public double getExtremeValuesFactor() {
return this.m_ExtremeValuesFactor;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String extremeValuesAsOutliersTipText() {
return "Whether to tag extreme values also as outliers.";
}
/**
* Set whether extreme values are also tagged as outliers.
*
* @param value whether or not to tag extreme values also as outliers.
*/
public void setExtremeValuesAsOutliers(final boolean value) {
this.m_ExtremeValuesAsOutliers = value;
}
/**
* Get whether extreme values are also tagged as outliers.
*
* @return true if extreme values are also tagged as outliers.
*/
public boolean getExtremeValuesAsOutliers() {
return this.m_ExtremeValuesAsOutliers;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String detectionPerAttributeTipText() {
return "Generates Outlier/ExtremeValue attribute pair for each numeric " + "attribute, not just a single pair for all numeric attributes together.";
}
/**
* Set whether an Outlier/ExtremeValue attribute pair is generated for each
* numeric attribute ("true") or just one pair for all numeric attributes
* together ("false").
*
* @param value whether or not to generate indicator attribute pairs for each
* numeric attribute.
*/
public void setDetectionPerAttribute(final boolean value) {
this.m_DetectionPerAttribute = value;
if (!this.m_DetectionPerAttribute) {
this.m_OutputOffsetMultiplier = false;
}
}
/**
* Gets whether an Outlier/ExtremeValue attribute pair is generated for each
* numeric attribute ("true") or just one pair for all numeric attributes
* together ("false").
*
* @return true if indicator attribute pairs are generated for each numeric
* attribute.
*/
public boolean getDetectionPerAttribute() {
return this.m_DetectionPerAttribute;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputOffsetMultiplierTipText() {
return "Generates an additional attribute 'Offset' that contains the " + "multiplier the value is off the median: " + "value = median + 'multiplier' * IQR";
}
/**
* Set whether an additional attribute "Offset" is generated per
* Outlier/ExtremeValue attribute pair that lists the multiplier the value is
* off the median: value = median + 'multiplier' * IQR.
*
* @param value whether or not to generate the additional attribute.
*/
public void setOutputOffsetMultiplier(final boolean value) {
this.m_OutputOffsetMultiplier = value;
if (this.m_OutputOffsetMultiplier) {
this.m_DetectionPerAttribute = true;
}
}
/**
* Gets whether an additional attribute "Offset" is generated per
* Outlier/ExtremeValue attribute pair that lists the multiplier the value is
* off the median: value = median + 'multiplier' * IQR.
*
* @return true if the additional attribute is generated.
*/
public boolean getOutputOffsetMultiplier() {
return this.m_OutputOffsetMultiplier;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(final Instances inputFormat) throws Exception {
ArrayList<Attribute> atts;
ArrayList<String> values;
Instances result;
int i;
// attributes must be numeric
this.m_Attributes.setUpper(inputFormat.numAttributes() - 1);
this.m_AttributeIndices = this.m_Attributes.getSelection();
for (i = 0; i < this.m_AttributeIndices.length; i++) {
// ignore class
if (this.m_AttributeIndices[i] == inputFormat.classIndex()) {
this.m_AttributeIndices[i] = NON_NUMERIC;
continue;
}
// not numeric -> ignore it
if (!inputFormat.attribute(this.m_AttributeIndices[i]).isNumeric()) {
this.m_AttributeIndices[i] = NON_NUMERIC;
}
}
// get old attributes
atts = new ArrayList<Attribute>();
for (i = 0; i < inputFormat.numAttributes(); i++) {
atts.add(inputFormat.attribute(i));
}
if (!this.getDetectionPerAttribute()) {
this.m_OutlierAttributePosition = new int[1];
this.m_OutlierAttributePosition[0] = atts.size();
// add 2 new attributes
values = new ArrayList<String>();
values.add("no");
values.add("yes");
atts.add(new Attribute("Outlier", values));
values = new ArrayList<String>();
values.add("no");
values.add("yes");
atts.add(new Attribute("ExtremeValue", values));
} else {
this.m_OutlierAttributePosition = new int[this.m_AttributeIndices.length];
for (i = 0; i < this.m_AttributeIndices.length; i++) {
if (this.m_AttributeIndices[i] == NON_NUMERIC) {
continue;
}
this.m_OutlierAttributePosition[i] = atts.size();
// add new attributes
values = new ArrayList<String>();
values.add("no");
values.add("yes");
Attribute aO = new Attribute(inputFormat.attribute(this.m_AttributeIndices[i]).name() + "_Outlier", values);
aO.setWeight(inputFormat.attribute(this.m_AttributeIndices[i]).weight());
atts.add(aO);
values = new ArrayList<String>();
values.add("no");
values.add("yes");
Attribute aE = new Attribute(inputFormat.attribute(this.m_AttributeIndices[i]).name() + "_ExtremeValue", values);
aE.setWeight(inputFormat.attribute(this.m_AttributeIndices[i]).weight());
atts.add(aE);
if (this.getOutputOffsetMultiplier()) {
Attribute aF = new Attribute(inputFormat.attribute(this.m_AttributeIndices[i]).name() + "_Offset");
aF.setWeight(inputFormat.attribute(this.m_AttributeIndices[i]).weight());
atts.add(aF);
}
}
}
// generate header
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
/**
* computes the thresholds for outliers and extreme values
*
* @param instances the data to work on
* @throws InterruptedException
*/
protected void computeThresholds(final Instances instances) throws InterruptedException {
int i;
double[] values;
int[] sortedIndices;
int half;
int quarter;
double q1;
double q2;
double q3;
this.m_UpperExtremeValue = new double[this.m_AttributeIndices.length];
this.m_UpperOutlier = new double[this.m_AttributeIndices.length];
this.m_LowerOutlier = new double[this.m_AttributeIndices.length];
this.m_LowerExtremeValue = new double[this.m_AttributeIndices.length];
this.m_Median = new double[this.m_AttributeIndices.length];
this.m_IQR = new double[this.m_AttributeIndices.length];
for (i = 0; i < this.m_AttributeIndices.length; i++) {
// non-numeric attribute?
if (this.m_AttributeIndices[i] == NON_NUMERIC) {
continue;
}
// sort attribute data
values = instances.attributeToDoubleArray(this.m_AttributeIndices[i]);
sortedIndices = Utils.sort(values);
// determine indices
half = sortedIndices.length / 2;
quarter = half / 2;
if (sortedIndices.length % 2 == 1) {
q2 = values[sortedIndices[half]];
} else {
q2 = (values[sortedIndices[half]] + values[sortedIndices[half + 1]]) / 2;
}
if (half % 2 == 1) {
q1 = values[sortedIndices[quarter]];
q3 = values[sortedIndices[sortedIndices.length - quarter - 1]];
} else {
q1 = (values[sortedIndices[quarter]] + values[sortedIndices[quarter + 1]]) / 2;
q3 = (values[sortedIndices[sortedIndices.length - quarter - 1]] + values[sortedIndices[sortedIndices.length - quarter]]) / 2;
}
// determine thresholds and other values
this.m_Median[i] = q2;
this.m_IQR[i] = q3 - q1;
this.m_UpperExtremeValue[i] = q3 + this.getExtremeValuesFactor() * this.m_IQR[i];
this.m_UpperOutlier[i] = q3 + this.getOutlierFactor() * this.m_IQR[i];
this.m_LowerOutlier[i] = q1 - this.getOutlierFactor() * this.m_IQR[i];
this.m_LowerExtremeValue[i] = q1 - this.getExtremeValuesFactor() * this.m_IQR[i];
}
}
/**
* Returns the values for the specified type.
*
* @param type the type of values to return
* @return the values
*/
public double[] getValues(final ValueType type) {
switch (type) {
case UPPER_EXTREME_VALUES:
return this.m_UpperExtremeValue;
case UPPER_OUTLIER_VALUES:
return this.m_UpperOutlier;
case LOWER_OUTLIER_VALUES:
return this.m_LowerOutlier;
case LOWER_EXTREME_VALUES:
return this.m_LowerExtremeValue;
case MEDIAN:
return this.m_Median;
case IQR:
return this.m_IQR;
default:
throw new IllegalArgumentException("Unhandled value type: " + type);
}
}
/**
* returns whether the instance has an outlier in the specified attribute or
* not
*
* @param inst the instance to test
* @param index the attribute index
* @return true if the instance is an outlier
*/
protected boolean isOutlier(final Instance inst, final int index) {
boolean result;
double value;
value = inst.value(this.m_AttributeIndices[index]);
result = ((this.m_UpperOutlier[index] < value) && (value <= this.m_UpperExtremeValue[index])) || ((this.m_LowerExtremeValue[index] <= value) && (value < this.m_LowerOutlier[index]));
return result;
}
/**
* returns whether the instance is an outlier or not
*
* @param inst the instance to test
* @return true if the instance is an outlier
*/
protected boolean isOutlier(final Instance inst) {
boolean result;
int i;
result = false;
for (i = 0; i < this.m_AttributeIndices.length; i++) {
// non-numeric attribute?
if (this.m_AttributeIndices[i] == NON_NUMERIC) {
continue;
}
result = this.isOutlier(inst, i);
if (result) {
break;
}
}
return result;
}
/**
* returns whether the instance has an extreme value in the specified
* attribute or not
*
* @param inst the instance to test
* @param index the attribute index
* @return true if the instance is an extreme value
*/
protected boolean isExtremeValue(final Instance inst, final int index) {
boolean result;
double value;
value = inst.value(this.m_AttributeIndices[index]);
result = (value > this.m_UpperExtremeValue[index]) || (value < this.m_LowerExtremeValue[index]);
return result;
}
/**
* returns whether the instance is an extreme value or not
*
* @param inst the instance to test
* @return true if the instance is an extreme value
*/
protected boolean isExtremeValue(final Instance inst) {
boolean result;
int i;
result = false;
for (i = 0; i < this.m_AttributeIndices.length; i++) {
// non-numeric attribute?
if (this.m_AttributeIndices[i] == NON_NUMERIC) {
continue;
}
result = this.isExtremeValue(inst, i);
if (result) {
break;
}
}
return result;
}
/**
* returns the mulitplier of the IQR the instance is off the median for this
* particular attribute.
*
* @param inst the instance to test
* @param index the attribute index
* @return the multiplier
*/
protected double calculateMultiplier(final Instance inst, final int index) {
double result;
double value;
value = inst.value(this.m_AttributeIndices[index]);
result = (value - this.m_Median[index]) / this.m_IQR[index];
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished(). This
* implementation only calls process(Instance) for each instance in the given
* dataset.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(final Instances instances) throws Exception {
Instances result;
Instance instOld;
Instance instNew;
int i;
int n;
double[] values;
int numAttNew;
int numAttOld;
if (!this.isFirstBatchDone()) {
this.computeThresholds(instances);
}
result = this.getOutputFormat();
numAttOld = instances.numAttributes();
numAttNew = result.numAttributes();
for (n = 0; n < instances.numInstances(); n++) {
instOld = instances.instance(n);
values = new double[numAttNew];
System.arraycopy(instOld.toDoubleArray(), 0, values, 0, numAttOld);
// per attribute?
if (!this.getDetectionPerAttribute()) {
// outlier?
if (this.isOutlier(instOld)) {
values[this.m_OutlierAttributePosition[0]] = 1;
}
// extreme value?
if (this.isExtremeValue(instOld)) {
values[this.m_OutlierAttributePosition[0] + 1] = 1;
// tag extreme values also as outliers?
if (this.getExtremeValuesAsOutliers()) {
values[this.m_OutlierAttributePosition[0]] = 1;
}
}
} else {
for (i = 0; i < this.m_AttributeIndices.length; i++) {
// non-numeric attribute?
if (this.m_AttributeIndices[i] == NON_NUMERIC) {
continue;
}
// outlier?
if (this.isOutlier(instOld, this.m_AttributeIndices[i])) {
values[this.m_OutlierAttributePosition[i]] = 1;
}
// extreme value?
if (this.isExtremeValue(instOld, this.m_AttributeIndices[i])) {
values[this.m_OutlierAttributePosition[i] + 1] = 1;
// tag extreme values also as outliers?
if (this.getExtremeValuesAsOutliers()) {
values[this.m_OutlierAttributePosition[i]] = 1;
}
}
// add multiplier?
if (this.getOutputOffsetMultiplier()) {
values[this.m_OutlierAttributePosition[i] + 2] = this.calculateMultiplier(instOld, this.m_AttributeIndices[i]);
}
}
}
// generate new instance
instNew = new DenseInstance(1.0, values);
instNew.setDataset(result);
// copy possible strings, relational values...
this.copyValues(instNew, false, instOld.dataset(), this.outputFormatPeek());
// add to output
result.add(instNew);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(final String[] args) {
runFilter(new InterquartileRange(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/KernelFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* KernelFilter.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.functions.supportVector.Kernel;
import weka.classifiers.functions.supportVector.PolyKernel;
import weka.classifiers.functions.supportVector.RBFKernel;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SingleIndex;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;
import weka.core.expressionlanguage.common.IfElseMacro;
import weka.core.expressionlanguage.common.JavaMacro;
import weka.core.expressionlanguage.common.MacroDeclarationsCompositor;
import weka.core.expressionlanguage.common.MathFunctions;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.SimpleVariableDeclarations;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.parser.Parser;
import weka.filters.AllFilter;
import weka.filters.Filter;
import weka.filters.SimpleBatchFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Converts the given set of data into
* a kernel matrix. The class value remains unchanged as long as the chosen
* preprocessing filter does not change it.<br/>
* By default, the data is preprocessed with the Center filter, but the user can
* choose any filter. (NB: one must be careful that the filter does not alter the
* class attribute unintentionally.) With weka.filters.AllFilter the
* preprocessing gets disabled.<br/>
* <br/>
* For more information regarding preprocessing the data, see:<br/>
* <br/>
* K.P. Bennett, M.J. Embrechts: An Optimization Perspective on Kernel Partial
* Least Squares Regression. In: Advances in Learning Theory: Methods, Models
* and Applications, 227-249, 2003.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Bennett2003,
* author = {K.P. Bennett and M.J. Embrechts},
* booktitle = {Advances in Learning Theory: Methods, Models and Applications},
* editor = {J. Suykens et al.},
* pages = {227-249},
* publisher = {IOS Press, Amsterdam, The Netherlands},
* series = {NATO Science Series, Series III: Computer and System Sciences},
* title = {An Optimization Perspective on Kernel Partial Least Squares Regression},
* volume = {190},
* year = {2003}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -output-debug-info
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -no-checks
* Turns off all checks - use with caution!
* Turning them off assumes that data is purely numeric, doesn't
* contain any missing values, and has a nominal class. Turning them
* off also means that no header information will be stored if the
* machine is linear. Finally, it also assumes that no instance has
* a weight equal to 0.
* (default: checks on)
* </pre>
*
* <pre>
* -F <filename>
* The file to initialize the filter with (optional).
* </pre>
*
* <pre>
* -C <num>
* The class index for the file to initialize with,
* First and last are valid (optional, default: last).
* </pre>
*
* <pre>
* -K <classname and parameters>
* The Kernel to use.
* (default: weka.classifiers.functions.supportVector.PolyKernel)
* </pre>
*
* <pre>
* -kernel-factor
* Defines a factor for the kernel.
* - RBFKernel: a factor for gamma
* Standardize: 1/(2*N)
* Normalize..: 6/N
* Available parameters are:
* N for # of instances, A for # of attributes
* (default: 1)
* </pre>
*
* <pre>
* -P <classname and parameters>
* The Filter used for preprocessing (use weka.filters.AllFilter
* to disable preprocessing).
* (default: weka.filters.unsupervised.attribute.Center)
* </pre>
*
* <pre>
* Options specific to kernel weka.classifiers.functions.supportVector.PolyKernel:
* </pre>
*
* <pre>
* -D
* Enables debugging output (if available) to be printed.
* (default: off)
* </pre>
*
* <pre>
* -no-checks
* Turns off all checks - use with caution!
* (default: checks on)
* </pre>
*
* <pre>
* -C <num>
* The size of the cache (a prime number), 0 for full cache and
* -1 to turn it off.
* (default: 250007)
* </pre>
*
* <pre>
* -E <num>
* The Exponent to use.
* (default: 1.0)
* </pre>
*
* <pre>
* -L
* Use lower-order terms.
* (default: no)
* </pre>
*
* <pre>
* Options specific to preprocessing filter weka.filters.unsupervised.attribute.Center:
* </pre>
*
* <pre>
* -unset-class-temporarily
* Unsets the class index temporarily before the filter is
* applied to the data.
* (default: no)
* </pre>
*
* <!-- options-end -->
*
* @author Jonathan Miles (jdm18@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class KernelFilter extends SimpleBatchFilter implements
UnsupervisedFilter, TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = 213800899640387499L;
/** The number of instances in the training data. */
protected int m_NumTrainInstances;
/** Kernel to use **/
protected Kernel m_Kernel = new PolyKernel();
/** the Kernel which is actually used for computation */
protected Kernel m_ActualKernel = null;
/**
* Turn off all checks and conversions? Turning them off assumes that data is
* purely numeric, doesn't contain any missing values, and has a nominal
* class. Turning them off also means that no header information will be
* stored if the machine is linear. Finally, it also assumes that no instance
* has a weight equal to 0.
*/
protected boolean m_checksTurnedOff;
/** The filter used to make attributes numeric. */
protected NominalToBinary m_NominalToBinary;
/** The filter used to get rid of missing values. */
protected ReplaceMissingValues m_Missing;
/** The dataset to initialize the filter with */
protected File m_InitFile = new File(System.getProperty("user.dir"));
/**
* the class index for the file to initialized with
*
* @see #m_InitFile
*/
protected SingleIndex m_InitFileClassIndex = new SingleIndex("last");
/** whether the filter was initialized */
protected boolean m_Initialized = false;
/**
* optimizes the kernel with this formula (A = # of attributes, N = # of
* instances)
*/
protected String m_KernelFactorExpression = "1";
/**
* the calculated kernel factor
*
* @see #m_KernelFactorExpression
*/
protected double m_KernelFactor = 1.0;
/** for centering/standardizing the data */
protected Filter m_Filter = new Center();
/** for centering/standardizing the data (the actual filter to use) */
protected Filter m_ActualFilter = null;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Converts the given set of data into a kernel matrix. "
+ "The class value remains unchanged as long as the chosen preprocessing "
+ "filter does not change it.\n\n"
+ "By default, the data is preprocessed with the Center filter, but the "
+ "user can choose any filter. (NB: one must be careful that the filter "
+ "does not alter the class attribute unintentionally.) With "
+ "weka.filters.AllFilter the preprocessing gets disabled.\n\n"
+ "For more information regarding preprocessing the data, see:\n\n"
+ getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "K.P. Bennett and M.J. Embrechts");
result.setValue(Field.TITLE,
"An Optimization Perspective on Kernel Partial Least Squares Regression");
result.setValue(Field.YEAR, "2003");
result.setValue(Field.EDITOR, "J. Suykens et al.");
result.setValue(Field.BOOKTITLE,
"Advances in Learning Theory: Methods, Models and Applications");
result.setValue(Field.PAGES, "227-249");
result.setValue(Field.PUBLISHER, "IOS Press, Amsterdam, The Netherlands");
result.setValue(Field.SERIES,
"NATO Science Series, Series III: Computer and System Sciences");
result.setValue(Field.VOLUME, "190");
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tTurns off all checks - use with caution!\n"
+ "\tTurning them off assumes that data is purely numeric, doesn't\n"
+ "\tcontain any missing values, and has a nominal class. Turning them\n"
+ "\toff also means that no header information will be stored if the\n"
+ "\tmachine is linear. Finally, it also assumes that no instance has\n"
+ "\ta weight equal to 0.\n" + "\t(default: checks on)", "no-checks", 0,
"-no-checks"));
result.addElement(new Option(
"\tThe file to initialize the filter with (optional).", "F", 1,
"-F <filename>"));
result.addElement(new Option(
"\tThe class index for the file to initialize with,\n"
+ "\tFirst and last are valid (optional, default: last).", "C", 1,
"-C <num>"));
result.addElement(new Option("\tThe Kernel to use.\n"
+ "\t(default: weka.classifiers.functions.supportVector.PolyKernel)",
"K", 1, "-K <classname and parameters>"));
result.addElement(new Option("\tDefines a factor for the kernel.\n"
+ "\t\t- RBFKernel: a factor for gamma\n"
+ "\t\t\tStandardize: 1/(2*N)\n" + "\t\t\tNormalize..: 6/N\n"
+ "\tAvailable parameters are:\n"
+ "\t\tN for # of instances, A for # of attributes\n" + "\t(default: 1)",
"kernel-factor", 0, "-kernel-factor"));
result
.addElement(new Option(
"\tThe Filter used for preprocessing (use weka.filters.AllFilter\n"
+ "\tto disable preprocessing).\n" + "\t(default: "
+ Center.class.getName() + ")", "P", 1,
"-P <classname and parameters>"));
result.addAll(Collections.list(super.listOptions()));
// kernel options
result.addElement(new Option("", "", 0, "\nOptions specific to kernel "
+ getKernel().getClass().getName() + ":"));
result
.addAll(Collections.list(((OptionHandler) getKernel()).listOptions()));
// filter options
if (getPreprocessing() instanceof OptionHandler) {
result.addElement(new Option("", "", 0,
"\nOptions specific to preprocessing filter "
+ getPreprocessing().getClass().getName() + ":"));
result.addAll(Collections.list(((OptionHandler) getPreprocessing())
.listOptions()));
}
return result.elements();
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getChecksTurnedOff()) {
result.add("-no-checks");
}
if ((getInitFile() != null) && getInitFile().isFile()) {
result.add("-F");
result.add("" + getInitFile().getAbsolutePath());
result.add("-C");
result.add("" + getInitFileClassIndex());
}
result.add("-K");
result.add("" + getKernel().getClass().getName() + " "
+ Utils.joinOptions(getKernel().getOptions()));
result.add("-kernel-factor");
result.add("" + getKernelFactorExpression());
result.add("-P");
String tmpStr = getPreprocessing().getClass().getName();
if (getPreprocessing() instanceof OptionHandler) {
tmpStr += " "
+ Utils.joinOptions(((OptionHandler) getPreprocessing()).getOptions());
}
result.add("" + tmpStr);
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -no-checks
* Turns off all checks - use with caution!
* Turning them off assumes that data is purely numeric, doesn't
* contain any missing values, and has a nominal class. Turning them
* off also means that no header information will be stored if the
* machine is linear. Finally, it also assumes that no instance has
* a weight equal to 0.
* (default: checks on)
* </pre>
*
* <pre>
* -F <filename>
* The file to initialize the filter with (optional).
* </pre>
*
* <pre>
* -C <num>
* The class index for the file to initialize with,
* First and last are valid (optional, default: last).
* </pre>
*
* <pre>
* -K <classname and parameters>
* The Kernel to use.
* (default: weka.classifiers.functions.supportVector.PolyKernel)
* </pre>
*
* <pre>
* -kernel-factor
* Defines a factor for the kernel.
* - RBFKernel: a factor for gamma
* Standardize: 1/(2*N)
* Normalize..: 6/N
* Available parameters are:
* N for # of instances, A for # of attributes
* (default: 1)
* </pre>
*
* <pre>
* -P <classname and parameters>
* The Filter used for preprocessing (use weka.filters.AllFilter
* to disable preprocessing).
* (default: weka.filters.unsupervised.attribute.Center)
* </pre>
*
* <pre>
* Options specific to kernel weka.classifiers.functions.supportVector.PolyKernel:
* </pre>
*
* <pre>
* -D
* Enables debugging output (if available) to be printed.
* (default: off)
* </pre>
*
* <pre>
* -no-checks
* Turns off all checks - use with caution!
* (default: checks on)
* </pre>
*
* <pre>
* -C <num>
* The size of the cache (a prime number), 0 for full cache and
* -1 to turn it off.
* (default: 250007)
* </pre>
*
* <pre>
* -E <num>
* The Exponent to use.
* (default: 1.0)
* </pre>
*
* <pre>
* -L
* Use lower-order terms.
* (default: no)
* </pre>
*
* <pre>
* Options specific to preprocessing filter weka.filters.unsupervised.attribute.Center:
* </pre>
*
* <pre>
* -unset-class-temporarily
* Unsets the class index temporarily before the filter is
* applied to the data.
* (default: no)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
String[] tmpOptions;
setChecksTurnedOff(Utils.getFlag("no-checks", options));
tmpStr = Utils.getOption('F', options);
if (tmpStr.length() != 0) {
setInitFile(new File(tmpStr));
} else {
setInitFile(null);
}
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
setInitFileClassIndex(tmpStr);
} else {
setInitFileClassIndex("last");
}
tmpStr = Utils.getOption('K', options);
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length != 0) {
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setKernel(Kernel.forName(tmpStr, tmpOptions));
}
tmpStr = Utils.getOption("kernel-factor", options);
if (tmpStr.length() != 0) {
setKernelFactorExpression(tmpStr);
} else {
setKernelFactorExpression("1");
}
tmpStr = Utils.getOption("P", options);
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length != 0) {
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setPreprocessing((Filter) Utils.forName(Filter.class, tmpStr, tmpOptions));
} else {
setPreprocessing(new Center());
}
super.setOptions(options);
Utils.checkForRemainingOptions(tmpOptions);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String initFileTipText() {
return "The dataset to initialize the filter with.";
}
/**
* Gets the file to initialize the filter with, can be null.
*
* @return the file
*/
public File getInitFile() {
return m_InitFile;
}
/**
* Sets the file to initialize the filter with, can be null.
*
* @param value the file
*/
public void setInitFile(File value) {
m_InitFile = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String initFileClassIndexTipText() {
return "The class index of the dataset to initialize the filter with (first and last are valid).";
}
/**
* Gets the class index of the file to initialize the filter with.
*
* @return the class index
*/
public String getInitFileClassIndex() {
return m_InitFileClassIndex.getSingleIndex();
}
/**
* Sets class index of the file to initialize the filter with.
*
* @param value the class index
*/
public void setInitFileClassIndex(String value) {
m_InitFileClassIndex.setSingleIndex(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String kernelTipText() {
return "The kernel to use.";
}
/**
* Gets the kernel to use.
*
* @return the kernel
*/
public Kernel getKernel() {
return m_Kernel;
}
/**
* Sets the kernel to use.
*
* @param value the kernel
*/
public void setKernel(Kernel value) {
m_Kernel = value;
}
/**
* Disables or enables the checks (which could be time-consuming). Use with
* caution!
*
* @param value if true turns off all checks
*/
public void setChecksTurnedOff(boolean value) {
m_checksTurnedOff = value;
}
/**
* Returns whether the checks are turned off or not.
*
* @return true if the checks are turned off
*/
public boolean getChecksTurnedOff() {
return m_checksTurnedOff;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String checksTurnedOffTipText() {
return "Turns time-consuming checks off - use with caution.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String kernelFactorExpressionTipText() {
return "The factor for the kernel, with A = # of attributes and N = # of instances.";
}
/**
* Gets the expression for the kernel.
*
* @return the expression
*/
public String getKernelFactorExpression() {
return m_KernelFactorExpression;
}
/**
* Sets the expression for the kernel.
*
* @param value the file
*/
public void setKernelFactorExpression(String value) {
m_KernelFactorExpression = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String preprocessingTipText() {
return "Sets the filter to use for preprocessing (use the AllFilter for no preprocessing).";
}
/**
* Sets the filter to use for preprocessing (use the AllFilter for no
* preprocessing)
*
* @param value the preprocessing filter
*/
public void setPreprocessing(Filter value) {
m_Filter = value;
m_ActualFilter = null;
}
/**
* Gets the filter used for preprocessing
*
* @return the current preprocessing filter.
*/
public Filter getPreprocessing() {
return m_Filter;
}
/**
* resets the filter, i.e., m_NewBatch to true and m_FirstBatchDone to false.
*/
@Override
protected void reset() {
super.reset();
m_Initialized = false;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
return new Instances(inputFormat);
}
/**
* initializes the filter with the given dataset, i.e., the kernel gets built.
* Needs to be called before the first call of Filter.useFilter or
* batchFinished(), if not the -F option (or setInitFile(File) is used).
*
* @param instances the data to initialize with
* @throws Exception if building of kernel fails
*/
public void initFilter(Instances instances) throws Exception {
// determine kernel factor
SimpleVariableDeclarations variables = new SimpleVariableDeclarations();
variables.addDouble("A");
variables.addDouble("N");
Node root = Parser.parse(
// expression
getKernelFactorExpression(),
// variables
variables,
// macros
new MacroDeclarationsCompositor(
new MathFunctions(),
new IfElseMacro(),
new JavaMacro()
)
);
if (!(root instanceof DoubleExpression))
throw new Exception("Kernel factor expression must be of double type!");
if (variables.getInitializer().hasVariable("A"))
variables.getInitializer().setDouble("A", instances.numAttributes());
if (variables.getInitializer().hasVariable("N"))
variables.getInitializer().setDouble("N", instances.numInstances());
m_KernelFactor = ((DoubleExpression) root).evaluate();
// init filters
if (!m_checksTurnedOff) {
m_Missing = new ReplaceMissingValues();
m_Missing.setInputFormat(instances);
instances = Filter.useFilter(instances, m_Missing);
} else {
m_Missing = null;
}
if (getKernel().getCapabilities().handles(Capability.NUMERIC_ATTRIBUTES)) {
boolean onlyNumeric = true;
if (!m_checksTurnedOff) {
for (int i = 0; i < instances.numAttributes(); i++) {
if (i != instances.classIndex()) {
if (!instances.attribute(i).isNumeric()) {
onlyNumeric = false;
break;
}
}
}
}
if (!onlyNumeric) {
m_NominalToBinary = new NominalToBinary();
m_NominalToBinary.setInputFormat(instances);
instances = Filter.useFilter(instances, m_NominalToBinary);
} else {
m_NominalToBinary = null;
}
} else {
m_NominalToBinary = null;
}
if ((m_Filter != null) && (m_Filter.getClass() != AllFilter.class)) {
m_ActualFilter = Filter.makeCopy(m_Filter);
m_ActualFilter.setInputFormat(instances);
instances = Filter.useFilter(instances, m_ActualFilter);
} else {
m_ActualFilter = null;
}
m_NumTrainInstances = instances.numInstances();
// set factor for kernel
m_ActualKernel = Kernel.makeCopy(m_Kernel);
if (m_ActualKernel instanceof RBFKernel) {
((RBFKernel) m_ActualKernel).setGamma(m_KernelFactor
* ((RBFKernel) m_ActualKernel).getGamma());
}
// build kernel
m_ActualKernel.buildKernel(instances);
m_Initialized = true;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
if (getKernel() == null) {
result = super.getCapabilities();
result.disableAll();
} else {
result = getKernel().getCapabilities();
}
result.setMinimumNumberInstances(0);
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
// initializing necessary?
if (!m_Initialized) {
// do we have a file to initialize with?
if ((getInitFile() != null) && getInitFile().isFile()) {
DataSource source = new DataSource(getInitFile().getAbsolutePath());
Instances data = source.getDataSet();
m_InitFileClassIndex.setUpper(data.numAttributes() - 1);
data.setClassIndex(m_InitFileClassIndex.getIndex());
initFilter(data);
} else {
initFilter(instances);
}
}
// apply filters
if (m_Missing != null) {
instances = Filter.useFilter(instances, m_Missing);
}
if (m_NominalToBinary != null) {
instances = Filter.useFilter(instances, m_NominalToBinary);
}
if (m_ActualFilter != null) {
instances = Filter.useFilter(instances, m_ActualFilter);
}
// backup class attribute and remove it
int classIndex = instances.classIndex();
double[] classes = null;
Attribute classAttribute = null;
if (classIndex >= 0) {
classes = instances.attributeToDoubleArray(instances.classIndex());
classAttribute = (Attribute) instances.classAttribute().copy();
instances.setClassIndex(-1);
instances.deleteAttributeAt(classIndex);
}
// generate new header
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int j = 0; j < m_NumTrainInstances; j++) {
atts.add(new Attribute("Kernel " + j));
}
if (classIndex >= 0) {
atts.add(classAttribute);
}
Instances result = new Instances("Kernel", atts, 0);
if (classIndex >= 0) {
result.setClassIndex(result.numAttributes() - 1);
}
// compute matrix
for (int i = 0; i < instances.numInstances(); i++) {
double[] k = new double[m_NumTrainInstances + ((classIndex >= 0) ? 1 : 0)];
for (int j = 0; j < m_NumTrainInstances; j++) {
double v = m_ActualKernel.eval(-1, j, instances.instance(i));
k[j] = v;
}
if (classIndex >= 0) {
k[k.length - 1] = classes[i];
}
// create new instance
Instance in = new DenseInstance(1.0, k);
result.add(in);
}
if (!isFirstBatchDone()) {
setOutputFormat(result);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the filter with the given arguments
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new KernelFilter(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/MakeIndicator.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MakeIndicator.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that creates a new dataset with a Boolean
* attribute replacing a nominal attribute. In the new dataset, a value of 1 is
* assigned to an instance that exhibits a value in the given range of attribute values,
* and a value of 0 is assigned to an instance that does not. The Boolean attribute is coded as numeric by
* default.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index.
* </pre>
*
* <pre>
* -V <index1,index2-index4,...>
* Specify the list of values to indicate. First and last are
* valid indexes (default last)
* </pre>
*
* <pre>
* -N <index>
* Set if new Boolean attribute nominal.
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class MakeIndicator extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 766001176862773163L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** The value's index */
private final Range m_ValIndex;
/** Make Boolean attribute numeric. */
private boolean m_Numeric = true;
/**
* Constructor
*/
public MakeIndicator() {
m_ValIndex = new Range("last");
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException the selecte attribute is not
* nominal
* @throws UnsupportedAttributeTypeException the selecte attribute has fewer
* than two values.
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
m_ValIndex.setUpper(instanceInfo.attribute(m_AttIndex.getIndex())
.numValues() - 1);
if (!instanceInfo.attribute(m_AttIndex.getIndex()).isNominal()) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute not nominal.");
}
if (instanceInfo.attribute(m_AttIndex.getIndex()).numValues() < 2) {
throw new UnsupportedAttributeTypeException("Chosen attribute has less "
+ "than two values.");
}
setOutputFormat();
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instance newInstance = (Instance) instance.copy();
if (!newInstance.isMissing(m_AttIndex.getIndex())) {
if (m_ValIndex.isInRange((int) newInstance.value(m_AttIndex.getIndex()))) {
newInstance.setValue(m_AttIndex.getIndex(), 1);
} else {
newInstance.setValue(m_AttIndex.getIndex(), 0);
}
}
push(newInstance, false); // No need to copy instance
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(3);
newVector.addElement(new Option("\tSets the attribute index.", "C", 1,
"-C <col>"));
newVector.addElement(new Option(
"\tSpecify the list of values to indicate. First and last are\n"
+ "\tvalid indexes (default last)", "V", 1,
"-V <index1,index2-index4,...>"));
newVector.addElement(new Option("\tSet if new Boolean attribute nominal.",
"N", 0, "-N <index>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index.
* </pre>
*
* <pre>
* -V <index1,index2-index4,...>
* Specify the list of values to indicate. First and last are
* valid indexes (default last)
* </pre>
*
* <pre>
* -N <index>
* Set if new Boolean attribute nominal.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
setAttributeIndex(attIndex);
} else {
setAttributeIndex("last");
}
String valIndex = Utils.getOption('V', options);
if (valIndex.length() != 0) {
setValueIndices(valIndex);
} else {
setValueIndices("last");
}
setNumeric(!Utils.getFlag('N', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + (getAttributeIndex()));
options.add("-V");
options.add(getValueIndices());
if (!getNumeric()) {
options.add("-N");
}
return options.toArray(new String[0]);
}
/**
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that creates a new dataset with a Boolean attribute "
+ "replacing a nominal attribute. In the new dataset, a value of 1 is "
+ "assigned to an instance that exhibits a value in the given range of attribute "
+ "values, and a value of 0 is assigned to an instance that does not. The Boolean attribute is "
+ "coded as numeric by default.";
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute should be replaced by the indicator. This "
+ "attribute must be nominal.";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* Get the range containing the indicator values.
*
* @return the range containing the indicator values
*/
public Range getValueRange() {
return m_ValIndex;
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String valueIndicesTipText() {
return "Specify range of nominal values to act on."
+ " This is a comma separated list of attribute indices (numbered from"
+ " 1), with \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the indices of the indicator values.
*
* @return the indices of the indicator values
*/
public String getValueIndices() {
return m_ValIndex.getRanges();
}
/**
* Sets indices of the indicator values.
*
* @param range the string representation of the indicator value indices
* @see Range
*/
public void setValueIndices(String range) {
m_ValIndex.setRanges(range);
}
/**
* Sets index of the indicator value.
*
* @param index the index of the indicator value
*/
public void setValueIndex(int index) {
setValueIndices("" + (index + 1));
}
/**
* Set which attributes are to be deleted (or kept if invert is true)
*
* @param indices an array containing indexes of attributes to select. Since
* the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setValueIndicesArray(int[] indices) {
setValueIndices(Range.indicesToRangeList(indices));
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numericTipText() {
return "Determines whether the output indicator attribute is numeric. If "
+ "this is set to false, the output attribute will be nominal.";
}
/**
* Sets if the new Attribute is to be numeric.
*
* @param bool true if new Attribute is to be numeric
*/
public void setNumeric(boolean bool) {
m_Numeric = bool;
}
/**
* Check if new attribute is to be numeric.
*
* @return true if new attribute is to be numeric
*/
public boolean getNumeric() {
return m_Numeric;
}
/**
* Set the output format.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts;
ArrayList<String> newVals;
// Compute new attributes
newAtts = new ArrayList<Attribute>(getInputFormat().numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (j != m_AttIndex.getIndex()) {
// We don't have to copy the attribute because the
// attribute index remains unchanged.
newAtts.add(att);
} else {
if (m_Numeric) {
Attribute a = new Attribute(att.name());
a.setWeight(att.weight());
newAtts.add(a);
} else {
String vals;
int[] sel = m_ValIndex.getSelection();
if (sel.length == 1) {
vals = att.value(sel[0]);
} else {
vals = m_ValIndex.getRanges().replace(',', '_');
}
newVals = new ArrayList<String>(2);
newVals.add("neg_" + vals);
newVals.add("pos_" + vals);
Attribute a = new Attribute(att.name(), newVals);
a.setWeight(att.weight());
newAtts.add(a);
}
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new MakeIndicator(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/MathExpression.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MathExpression.java
* Copyright (C) 2004 Prados Julien
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.core.expressionlanguage.common.IfElseMacro;
import weka.core.expressionlanguage.common.JavaMacro;
import weka.core.expressionlanguage.common.MacroDeclarationsCompositor;
import weka.core.expressionlanguage.common.MathFunctions;
import weka.core.expressionlanguage.common.Primitives.DoubleExpression;
import weka.core.expressionlanguage.common.SimpleVariableDeclarations;
import weka.core.expressionlanguage.common.SimpleVariableDeclarations.VariableInitializer;
import weka.core.expressionlanguage.common.VariableDeclarationsCompositor;
import weka.core.expressionlanguage.core.Node;
import weka.core.expressionlanguage.parser.Parser;
import weka.core.expressionlanguage.weka.InstancesHelper;
import weka.core.expressionlanguage.weka.StatsHelper;
import weka.experiment.Stats;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Modify numeric attributes according to a given
* mathematical expression. Supported operators are +, -, *,
* /, pow, log, abs, cos, exp, sqrt, tan, sin, ceil, floor, rint, (, ), MEAN, MAX, MIN, SD, COUNT, SUM,
* SUMSQUARED, ifelse. The 'A' letter refers to the value of the attribute being processed. Other attribute
* values (numeric only) can be accessed through the variables A1, A2, A3, ...
*
* Example: pow(A,6)/(MEAN+MAX)*ifelse(A<0,0,sqrt(A))+ifelse(![A>9 && A<15])
* <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>
* -E <expression>
* Specify the expression to apply.
* </pre>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to ignore. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only modify specified columns)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Prados Julien (julien.prados@cui.unige.ch)
* @version $Revision$
*/
public class MathExpression extends PotentialClassIgnorer implements
UnsupervisedFilter, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -3713222714671997901L;
/** Stores which columns to select as a funky range */
protected Range m_SelectCols = new Range();
/** The default modification expression */
public static final String m_defaultExpression = "(A-MIN)/(MAX-MIN)";
/** The modification expression */
private String m_expression = m_defaultExpression;
/** The compiled modification expression */
private DoubleExpression m_CompiledExpression;
/** Attributes statistics */
private Stats[] m_attStats;
/** InstancesHelpers for different indices */
private InstancesHelper m_InstancesHelper;
/** StatsHelpers for different indices */
private StatsHelper m_StatsHelper;
/** VariableInitializer for the current value 'A' in an expression */
private VariableInitializer m_CurrentValue;
/**
* Constructor
*/
public MathExpression() {
super();
setInvertSelection(false);
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Modify numeric attributes according to a given mathematical expression. Supported operators are +, -, *, " +
"/, pow, log, abs, cos, exp, sqrt, tan, sin, ceil, floor, rint, (, ), MEAN, MAX, MIN, SD, COUNT, SUM, " +
"SUMSQUARED, ifelse. The 'A' letter refers to the value of the attribute being processed. Other attribute " +
"values (numeric only) can be accessed through the variables A1, A2, A3, ... \n\nExample:" +
"pow(A,6)/(MEAN+MAX)*ifelse(A<0,0,sqrt(A))+ifelse(![A>9 && A<15])";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
m_SelectCols.setUpper(instanceInfo.numAttributes() - 1);
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
m_attStats = new Stats[instanceInfo.numAttributes()];
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_SelectCols.isInRange(i)
&& instanceInfo.attribute(i).isNumeric()
&& (instanceInfo.classIndex() != i) || getIgnoreClass()) {
m_attStats[i] = new Stats();
}
}
if (instanceInfo != null)
compile();
return true;
}
/**
* Compiles the expression
* Requires that the input format is set and not null
*
* @throws Exception if a compilation error occurs
*/
private void compile() throws Exception {
m_InstancesHelper = new InstancesHelper(getInputFormat());
m_StatsHelper = new StatsHelper();
SimpleVariableDeclarations currentValueDeclaration = new SimpleVariableDeclarations();
currentValueDeclaration.addDouble("A");
Node node = Parser.parse(
// expression
m_expression,
// variables
new VariableDeclarationsCompositor(
m_InstancesHelper,
m_StatsHelper,
currentValueDeclaration
),
// macros
new MacroDeclarationsCompositor(
m_InstancesHelper,
new MathFunctions(),
new IfElseMacro(),
new JavaMacro()
)
);
if (!(node instanceof DoubleExpression))
throw new Exception("Expression must be of type double!");
m_CurrentValue = currentValueDeclaration.getInitializer();
m_CompiledExpression = (DoubleExpression) node;
}
/**
* Input an instance for filtering. Filter requires all training 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 set.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (!m_FirstBatchDone) {
for (int i = 0; i < instance.numAttributes(); i++) {
if (m_SelectCols.isInRange(i)
&& instance.attribute(i).isNumeric()
&& (getInputFormat().classIndex() != i)
&& (!instance.isMissing(i))) {
m_attStats[i].add(instance.value(i), instance.weight());
}
}
bufferInput(instance);
return false;
} else {
convertInstance(instance);
return true;
}
}
/**
* Signify 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
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!m_FirstBatchDone) {
Instances input = getInputFormat();
for (int i = 0; i < input.numAttributes(); i++) {
if (m_SelectCols.isInRange(i)
&& input.attribute(i).isNumeric()
&& input.classIndex() != i) {
m_attStats[i].calculateDerived();
}
}
// Convert pending input instances
for (int i = 0; i < input.numInstances(); i++) {
convertInstance(input.instance(i));
}
}
// Free memory
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
* @throws Exception if instance cannot be converted
*/
private void convertInstance(Instance instance) throws Exception {
double[] vals = instance.toDoubleArray();
for (int i = 0; i < instance.numAttributes(); i++) {
if (
m_SelectCols.isInRange(i)
&& instance.attribute(i).isNumeric()
&& !Utils.isMissingValue(vals[i])
&& getInputFormat().classIndex() != i
) {
// setup program
m_InstancesHelper.setInstance(instance);
m_StatsHelper.setStats(m_attStats[i]);
if (m_CurrentValue.hasVariable("A"))
m_CurrentValue.setDouble("A", vals[i]);
// compute
double value = m_CompiledExpression.evaluate();
// set new value
if (Double.isNaN(value) || Double.isInfinite(value) ||
m_InstancesHelper.missingAccessed()) {
System.err
.println("WARNING:Error in evaluating the expression: missing value set");
vals[i] = Utils.missingValue();
} else {
vals[i] = value;
}
}
}
Instance outInstance;
if (instance instanceof SparseInstance) {
outInstance = new SparseInstance(instance.weight(), vals);
} else {
outInstance = new DenseInstance(instance.weight(), vals);
}
outInstance.setDataset(instance.dataset());
push(outInstance, false); // No need to copy instance
}
/**
* 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>
* -E <expression>
* Specify the expression to apply.
* </pre>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to ignore. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only modify specified columns)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String expString = Utils.getOption('E', options);
if (expString.length() != 0) {
setExpression(expString);
} else {
setExpression(m_defaultExpression);
}
String ignoreList = Utils.getOption('R', options);
if (ignoreList.length() != 0) {
setIgnoreRange(ignoreList);
}
setInvertSelection(Utils.getFlag('V', options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-E");
result.add(getExpression());
if (getInvertSelection()) {
result.add("-V");
}
if (!getIgnoreRange().equals("")) {
result.add("-R");
result.add(getIgnoreRange());
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSpecify the expression to apply. Eg. pow(A,6)/(MEAN+MAX)"
+ "\n\tSupported operators are +, -, *, /, pow, log,"
+ "\n\tabs, cos, exp, sqrt, tan, sin, ceil, floor, rint, (, ), "
+ "\n\tMEAN, MAX, MIN, SD, COUNT, SUM, SUMSQUARED, ifelse. The 'A'"
+ "\n\tletter refers to the value of the attribute being processed."
+ "\n\tOther attribute values (numeric only) can be accessed through"
+ "\n\tthe variables A1, A2, A3, ...", "E", 1, "-E <expression>"));
result
.addElement(new Option(
"\tSpecify list of columns to ignore. First and last are valid\n"
+ "\tindexes. (default none)", "R", 1,
"-R <index1,index2-index4,...>"));
result.addElement(new Option(
"\tInvert matching sense (i.e. only modify specified columns)", "V", 0,
"-V"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String expressionTipText() {
return "Specify the expression to apply.";
}
/**
* Set the expression to apply
*
* @param expr a mathematical expression to apply
* @throws Exception if the input format is set and there is a problem with the expression
*/
public void setExpression(String expr) throws Exception {
m_expression = expr;
if (getInputFormat() != null)
compile();
}
/**
* Get the expression
*
* @return the expression
*/
public String getExpression() {
return m_expression;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether action is to select or unselect."
+ " If set to true, only the specified attributes will be modified;"
+ " If set to false, specified attributes will not be modified.";
}
/**
* Get whether the supplied columns are to be select or unselect
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return !m_SelectCols.getInvert();
}
/**
* Set whether selected columns should be select or unselect. If true the
* selected columns are modified. If false the selected columns are not
* modified.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_SelectCols.setInvert(!invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoreRangeTipText() {
return "Specify range of attributes to ignore."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getIgnoreRange() {
return m_SelectCols.getRanges();
}
/**
* Set which attributes are to be ignored
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br/>
* eg: first-3,5,6-last
*/
public void setIgnoreRange(String rangeList) {
m_SelectCols.setRanges(rangeList);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new MathExpression(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/MergeInfrequentNominalValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MergeInfrequentNominalValues.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start -->
* Merges all values of the specified nominal attributes that are insufficiently frequent.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <int>
* The minimum frequency for a value to remain (default: 2).
* </pre>
*
* <pre> -R <range>
* Sets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: 1,2)</pre>
*
* <pre> -V
* Invert matching sense (i.e. act on all attributes not specified in list)</pre>
*
* <pre> -S
* Use short IDs for merged attribute values.</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank
* @version $Revision: ???? $
*/
public class MergeInfrequentNominalValues extends SimpleBatchFilter implements
UnsupervisedFilter, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 4444337331921333847L;
/** Set the minimum frequency for a value not to be merged. */
protected int m_MinimumFrequency = 2;
/** Stores which atributes to operate on (or nto) */
protected Range m_SelectCols = new Range();
/** Stores the indexes of the selected attributes in order. */
protected int[] m_SelectedAttributes;
/** Indicators for which attributes need to be changed. */
protected boolean[] m_AttToBeModified;
/** The new values. */
protected int[][] m_NewValues;
/** Whether to use short identifiers for merge values. */
protected boolean m_UseShortIDs = false;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Merges all values of the specified nominal attributes that are insufficiently frequent.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(3);
result.addElement(new Option(
"\tThe minimum frequency for a value to remain (default: 2).\n", "-N", 1,
"-N <int>"));
result
.addElement(new Option(
"\tSets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'\n"
+ "\tE.g.: first-5,7,9,20-last\n" + "\t(default: 1,2)", "R", 1,
"-R <range>"));
result
.addElement(new Option(
"\tInvert matching sense (i.e. act on all attributes not specified in list)",
"V", 0, "-V"));
result.addElement(new Option("\tUse short IDs for merged attribute values.", "S", 0, "-S"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-N");
result.add("" + getMinimumFrequency());
result.add("-R");
result.add(getAttributeIndices());
if (getInvertSelection()) {
result.add("-V");
}
if (getUseShortIDs()) {
result.add("-S");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <int>
* The minimum frequency for a value to remain (default: 2).
* </pre>
*
* <pre> -R <range>
* Sets list of attributes to act on (or its inverse). 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: 1,2)</pre>
*
* <pre> -V
* Invert matching sense (i.e. act on all attributes not specified in list)</pre>
*
* <pre> -S
* Use short IDs for merged attribute values.</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String minFrequencyString = Utils.getOption('N', options);
if (minFrequencyString.length() != 0) {
setMinimumFrequency(Integer.parseInt(minFrequencyString));
} else {
setMinimumFrequency(2);
}
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("");
}
setInvertSelection(Utils.getFlag('V', options));
setUseShortIDs(Utils.getFlag('S', options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String minimumFrequencyTipText() {
return "The minimum frequency for a value to remain.";
}
/**
* Gets the minimum frequency.
*
* @return int the minimum frequency.
*/
public int getMinimumFrequency() {
return m_MinimumFrequency;
}
/**
* Sets the minimum frequency.
*
* @param minF the minimum frequency as an integer.
*/
public void setMinimumFrequency(int minF) {
m_MinimumFrequency = minF;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on (or its inverse)."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_SelectCols.getRanges();
}
/**
* Set which attributes are to be acted on (or not, if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String rangeList) {
m_SelectCols.setRanges(rangeList);
}
/**
* Set which attributes are to be acted on (or not, if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether selected attributes are to be acted "
+ "on or all other attributes are used instead.";
}
/**
* Get whether the supplied attributes are to be acted on or all other
* attributes.
*
* @return true if the supplied attributes will be kept
*/
public boolean getInvertSelection() {
return m_SelectCols.getInvert();
}
/**
* Set whether selected attributes should be acted on or all other attributes.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_SelectCols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useShortIDsTipText() {
return "If true, short IDs will be used for merged attribute values.";
}
/**
* Get whether short IDs are to be used.
*
* @return true if short IDs are to be used.
*/
public boolean getUseShortIDs() {
return m_UseShortIDs;
}
/**
* Sets whether short IDs are to be used.
*
* @param m_UseShortIDs if true, short IDs will be used
*/
public void setUseShortIDs(boolean m_UseShortIDs) {
this.m_UseShortIDs = m_UseShortIDs;
}
/**
* We need access to the full input data in determineOutputFormat.
*/
@Override
public boolean allowAccessToFullInputFormat() {
return true;
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) {
// Set the upper limit of the range
m_SelectCols.setUpper(inputFormat.numAttributes() - 1);
// Get the selected attributes
m_SelectedAttributes = m_SelectCols.getSelection();
// Allocate arrays to store frequencies
int[][] freqs = new int[inputFormat.numAttributes()][];
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
Attribute att = inputFormat.attribute(current);
if ((current != inputFormat.classIndex()) && (att.isNominal())) {
freqs[current] = new int[att.numValues()];
}
}
// Go through all the instances and compute frequencies
for (Instance inst : inputFormat) {
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
if ((current != inputFormat.classIndex())
&& (inputFormat.attribute(current).isNominal())) {
if (!inst.isMissing(current)) {
freqs[current][(int) inst.value(current)]++;
}
}
}
}
// Get the number of infrequent values for the corresponding attributes
int[] numInfrequentValues = new int[inputFormat.numAttributes()];
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
Attribute att = inputFormat.attribute(current);
if ((current != inputFormat.classIndex()) && (att.isNominal())) {
for (int k = 0; k < att.numValues(); k++) {
if (m_Debug) {
System.err.println("Attribute: " + att.name() + " Value: "
+ att.value(k) + " Freq.: " + freqs[current][k]);
}
if (freqs[current][k] < m_MinimumFrequency) {
numInfrequentValues[current]++;
}
}
}
}
// Establish which attributes need to be modified.
// Also, compute mapping of indices.
m_AttToBeModified = new boolean[inputFormat.numAttributes()];
m_NewValues = new int[inputFormat.numAttributes()][];
for (int m_SelectedAttribute : m_SelectedAttributes) {
int current = m_SelectedAttribute;
Attribute att = inputFormat.attribute(current);
if ((numInfrequentValues[current] > 1)) {
// Attribute needs to be modified
m_AttToBeModified[current] = true;
// Start with index one because 0 refers to merged values
int j = 1;
m_NewValues[current] = new int[att.numValues()];
for (int k = 0; k < att.numValues(); k++) {
if (freqs[current][k] < m_MinimumFrequency) {
m_NewValues[current][k] = 0;
} else {
m_NewValues[current][k] = j++;
}
}
}
}
// Create new header
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < inputFormat.numAttributes(); i++) {
int current = i;
Attribute att = inputFormat.attribute(current);
if (m_AttToBeModified[i]) {
ArrayList<String> vals = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
vals.add(""); // Placeholder
for (int j = 0; j < att.numValues(); j++) {
if (m_NewValues[current][j] == 0) {
if (sb.length() != 0) {
sb.append("_or_");
}
sb.append(att.value(j));
} else {
vals.add(att.value(j));
}
}
if (m_UseShortIDs) {
vals.set(0, new StringBuilder().append("").append(sb.toString().hashCode()).toString());
} else {
vals.set(0, sb.toString()); // Replace empty string
}
Attribute a = new Attribute(att.name() + "_merged_infrequent_values", vals);
a.setWeight(att.weight());
atts.add(a);
} else {
atts.add((Attribute) att.copy());
}
}
// Return modified header
Instances data = new Instances(inputFormat.relationName(), atts, 0);
data.setClassIndex(inputFormat.classIndex());
return data;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Processes the given data.
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instances process(Instances instances) throws Exception {
// Generate the output and return it
Instances result = new Instances(getOutputFormat(),
instances.numInstances());
for (int i = 0; i < instances.numInstances(); i++) {
Instance inst = instances.instance(i);
double[] newData = new double[instances.numAttributes()];
for (int j = 0; j < instances.numAttributes(); j++) {
if (m_AttToBeModified[j] && !inst.isMissing(j)) {
newData[j] = m_NewValues[j][(int) inst.value(j)];
} else {
newData[j] = inst.value(j);
}
}
DenseInstance instNew = new DenseInstance(inst.weight(), newData);
instNew.setDataset(result);
// copy possible strings, relational values...
copyValues(instNew, false, inst.dataset(), outputFormatPeek());
// Add instance to output
result.add(instNew);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 8034 $");
}
/**
* runs the filter with the given arguments
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new MergeInfrequentNominalValues(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/MergeManyValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MergeManyValues.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Merges many values of a nominal attribute into one
* value.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index
* (default: last)
* </pre>
*
* <pre>
* -L <label>
* Sets the label of the newly merged classes
* (default: 'merged')
* </pre>
*
* <pre>
* -R <range>
* Sets the merge range. 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: 1,2)
* </pre>
*
* <!-- options-end -->
*
* @author Kathryn Hempstalk (kah18 at cs.waikato.ac.nz)
* @version $Revision$
*/
public class MergeManyValues extends PotentialClassIgnorer implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
private static final long serialVersionUID = 4649332102154713625L;
/** The attribute's index setting. */
protected SingleIndex m_AttIndex = new SingleIndex("last");
/** The first value's index setting. */
protected String m_Label = "merged";
/** The merge value's index setting. */
protected Range m_MergeRange = new Range("1,2");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Merges many values of a nominal attribute into one value.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(3);
newVector.addElement(new Option("\tSets the attribute index\n"
+ "\t(default: last)", "C", 1, "-C <col>"));
newVector.addElement(new Option(
"\tSets the label of the newly merged classes\n"
+ "\t(default: 'merged')", "L", 1, "-L <label>"));
newVector.addElement(new Option(
"\tSets the merge range. 'first and 'last' are accepted as well.'\n"
+ "\tE.g.: first-5,7,9,20-last\n" + "\t(default: 1,2)", "R", 1,
"-R <range>"));
Enumeration<Option> superOpts = super.listOptions();
while (superOpts.hasMoreElements()) {
newVector.add(superOpts.nextElement());
}
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index
* (default: last)
* </pre>
*
* <pre>
* -L <label>
* Sets the label of the newly merged classes
* (default: 'merged')
* </pre>
*
* <pre>
* -R <range>
* Sets the merge range. 'first and 'last' are accepted as well.'
* E.g.: first-5,7,9,20-last
* (default: 1,2)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
setAttributeIndex(tmpStr);
} else {
setAttributeIndex("last");
}
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0) {
setLabel(tmpStr);
} else {
setLabel("merged");
}
tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setMergeValueRange(tmpStr);
} else {
setMergeValueRange("1,2");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-C");
result.add(getAttributeIndex());
result.add("-L");
result.add(getLabel());
result.add("-R");
result.add(getMergeValueRange());
String[] superOpts = super.getOptions();
result.addAll(Arrays.asList(superOpts));
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(inputFormatPeek().numAttributes() - 1);
m_MergeRange.setUpper(inputFormatPeek().attribute(m_AttIndex.getIndex())
.numValues() - 1);
if ((inputFormatPeek().classIndex() > -1)
&& (inputFormatPeek().classIndex() == m_AttIndex.getIndex())) {
throw new Exception("Cannot process class attribute.");
}
if (!inputFormatPeek().attribute(m_AttIndex.getIndex()).isNominal()) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute not nominal.");
}
if (inputFormatPeek().attribute(m_AttIndex.getIndex()).numValues() < 2) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute has less than " + "two values.");
}
setOutputFormat();
return true;
}
/**
* Set the output format. Takes the current average class values and
* m_InputFormat and calls setOutputFormat(Instances) appropriately.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts;
ArrayList<String> newVals;
// Compute new attributes
newAtts = new ArrayList<Attribute>(getInputFormat().numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (j != m_AttIndex.getIndex()) {
newAtts.add((Attribute) att.copy());
} else {
// Compute list of attribute values
newVals = new ArrayList<String>(att.numValues() - 1);
for (int i = 0; i < att.numValues(); i++) {
boolean inMergeList = false;
if (att.value(i).equalsIgnoreCase(m_Label)) {
// don't want to add this one.
inMergeList = true;
} else {
inMergeList = m_MergeRange.isInRange(i);
}
if (!inMergeList) {
// add it.
newVals.add(att.value(i));
}
}
newVals.add(m_Label);
Attribute newAtt = new Attribute(att.name(), newVals);
newAtt.setWeight(getInputFormat().attribute(j).weight());
newAtts.add(newAtt);
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Attribute att = outputFormatPeek().attribute(m_AttIndex.getIndex());
Instance newInstance = (Instance) instance.copy();
if (!instance.isMissing(m_AttIndex.getIndex())) {
int index = att.indexOfValue(instance.stringValue(m_AttIndex.getIndex()));
if (index == -1) {
newInstance.setValue(m_AttIndex.getIndex(), att.indexOfValue(m_Label));
} else {
newInstance.setValue(m_AttIndex.getIndex(), index);
}
}
push(newInstance, false); // No need to copy instance
return true;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute to process. This "
+ "attribute must be nominal (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String labelTipText() {
return "The new label for the merged values.";
}
/**
* Get the label for the new merged class.
*
* @return the label for the merged class.
*/
public String getLabel() {
return m_Label;
}
/**
* Sets label of the merged class.
*
* @param alabel the new label.
*/
public void setLabel(String alabel) {
m_Label = alabel;
}
/**
* Get the range of the merge values used.
*
* @return the range of the merge values
*/
public String getMergeValueRange() {
return m_MergeRange.getRanges();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String mergeValueRangeTipText() {
return "The range of values to merge.";
}
/**
* Sets range of the merge values used.
*
* @param range the range of the merged values
*/
public void setMergeValueRange(String range) {
m_MergeRange.setRanges(range);
}
/**
* Returns the revision string.
*
* @return The revision string.
*/
@Override
public String getRevision() {
return "$Revision$";
}
/**
* Main method for executing this filter.
*
* @param args use -h to display all options
*/
public static void main(String[] args) {
runFilter(new MergeManyValues(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/MergeTwoValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* MergeTwoValues.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Merges two values of a nominal attribute into one
* value.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the first value's index (default first).
* </pre>
*
* <pre>
* -S <value index>
* Sets the second value's index (default last).
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class MergeTwoValues extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 2925048980504034018L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** The first value's index setting. */
private final SingleIndex m_FirstIndex = new SingleIndex("first");
/** The second value's index setting. */
private final SingleIndex m_SecondIndex = new SingleIndex("last");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Merges two values of a nominal attribute into one value.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
m_FirstIndex.setUpper(instanceInfo.attribute(m_AttIndex.getIndex())
.numValues() - 1);
m_SecondIndex.setUpper(instanceInfo.attribute(m_AttIndex.getIndex())
.numValues() - 1);
if ((instanceInfo.classIndex() > -1)
&& (instanceInfo.classIndex() == m_AttIndex.getIndex())) {
throw new Exception("Cannot process class attribute.");
}
if (!instanceInfo.attribute(m_AttIndex.getIndex()).isNominal()) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute not nominal.");
}
if (instanceInfo.attribute(m_AttIndex.getIndex()).numValues() < 2) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute has less than " + "two values.");
}
if (m_SecondIndex.getIndex() <= m_FirstIndex.getIndex()) {
// XXX Maybe we should just swap the values??
throw new Exception("The second index has to be greater "
+ "than the first.");
}
setOutputFormat();
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instance newInstance = (Instance) instance.copy();
if ((int) newInstance.value(m_AttIndex.getIndex()) == m_SecondIndex
.getIndex()) {
newInstance.setValue(m_AttIndex.getIndex(), m_FirstIndex.getIndex());
} else if ((int) newInstance.value(m_AttIndex.getIndex()) > m_SecondIndex
.getIndex()) {
newInstance.setValue(m_AttIndex.getIndex(),
newInstance.value(m_AttIndex.getIndex()) - 1);
}
push(newInstance, false); // No need to copy instance
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(3);
newVector.addElement(new Option(
"\tSets the attribute index (default last).", "C", 1, "-C <col>"));
newVector.addElement(new Option(
"\tSets the first value's index (default first).", "F", 1,
"-F <value index>"));
newVector.addElement(new Option(
"\tSets the second value's index (default last).", "S", 1,
"-S <value index>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the first value's index (default first).
* </pre>
*
* <pre>
* -S <value index>
* Sets the second value's index (default last).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
setAttributeIndex(attIndex);
} else {
setAttributeIndex("last");
}
String firstValIndex = Utils.getOption('F', options);
if (firstValIndex.length() != 0) {
setFirstValueIndex(firstValIndex);
} else {
setFirstValueIndex("first");
}
String secondValIndex = Utils.getOption('S', options);
if (secondValIndex.length() != 0) {
setSecondValueIndex(secondValIndex);
} else {
setSecondValueIndex("last");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + getAttributeIndex());
options.add("-F");
options.add("" + getFirstValueIndex());
options.add("-S");
options.add("" + getSecondValueIndex());
return options.toArray(new String[0]);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute to process. This "
+ "attribute must be nominal (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String firstValueIndexTipText() {
return "Sets the first value to be merged. "
+ "(\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the first value used.
*
* @return the index of the first value
*/
public String getFirstValueIndex() {
return m_FirstIndex.getSingleIndex();
}
/**
* Sets index of the first value used.
*
* @param firstIndex the index of the first value
*/
public void setFirstValueIndex(String firstIndex) {
m_FirstIndex.setSingleIndex(firstIndex);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String secondValueIndexTipText() {
return "Sets the second value to be merged. "
+ "(\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the second value used.
*
* @return the index of the second value
*/
public String getSecondValueIndex() {
return m_SecondIndex.getSingleIndex();
}
/**
* Sets index of the second value used.
*
* @param secondIndex the index of the second value
*/
public void setSecondValueIndex(String secondIndex) {
m_SecondIndex.setSingleIndex(secondIndex);
}
/**
* Set the output format. Takes the current average class values and
* m_InputFormat and calls setOutputFormat(Instances) appropriately.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts;
ArrayList<String> newVals;
boolean firstEndsWithPrime = false, secondEndsWithPrime = false;
StringBuffer text = new StringBuffer();
// Compute new attributes
newAtts = new ArrayList<Attribute>(getInputFormat().numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (j != m_AttIndex.getIndex()) {
newAtts.add((Attribute) att.copy());
} else {
// Compute new value
if (att.value(m_FirstIndex.getIndex()).endsWith("'")) {
firstEndsWithPrime = true;
}
if (att.value(m_SecondIndex.getIndex()).endsWith("'")) {
secondEndsWithPrime = true;
}
if (firstEndsWithPrime || secondEndsWithPrime) {
text.append("'");
}
if (firstEndsWithPrime) {
text.append(att.value(m_FirstIndex.getIndex()).substring(1,
att.value(m_FirstIndex.getIndex()).length() - 1));
} else {
text.append(att.value(m_FirstIndex.getIndex()));
}
text.append('_');
if (secondEndsWithPrime) {
text.append(att.value(m_SecondIndex.getIndex()).substring(1,
att.value(m_SecondIndex.getIndex()).length() - 1));
} else {
text.append(att.value(m_SecondIndex.getIndex()));
}
if (firstEndsWithPrime || secondEndsWithPrime) {
text.append("'");
}
// Compute list of attribute values
newVals = new ArrayList<String>(att.numValues() - 1);
for (int i = 0; i < att.numValues(); i++) {
if (i == m_FirstIndex.getIndex()) {
newVals.add(text.toString());
} else if (i != m_SecondIndex.getIndex()) {
newVals.add(att.value(i));
}
}
Attribute newAtt = new Attribute(att.name(), newVals);
newAtt.setWeight(getInputFormat().attribute(j).weight());
newAtts.add(newAtt);
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new MergeTwoValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NominalToBinary.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NominalToBinary.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Converts all nominal attributes into binary numeric attributes. An attribute with k values is transformed into k binary attributes if the class is nominal (using the one-attribute-per-value approach). Binary
* attributes are left binary if option '-A' is not given. If the class is numeric, you might want to use the supervised version of this filter.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Sets if binary attributes are to be coded as nominal ones.
* </pre>
*
* <pre>
* -A
* For each nominal value a new attribute is created,
* not only if there are more than 2 values.
* </pre>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to act on. First and last are
* valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NominalToBinary extends Filter implements UnsupervisedFilter, OptionHandler, StreamableFilter, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -1130642825710549138L;
/** Stores which columns to act on */
protected Range m_Columns = new Range();
/** Are the new attributes going to be nominal or numeric ones? */
private boolean m_Numeric = true;
/** Are all values transformed into new attributes? */
private boolean m_TransformAll = false;
/** Whether we need to transform at all */
private boolean m_needToTransform = false;
/** Whether to spread attribute weight when creating binary attributes */
protected boolean m_SpreadAttributeWeight = false;
/** Constructor - initialises the filter */
public NominalToBinary() {
this.setAttributeIndices("first-last");
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Converts all nominal attributes into binary numeric attributes. An " + "attribute with k values is transformed into k binary attributes if " + "the class is nominal (using the one-attribute-per-value approach). "
+ "Binary attributes are left binary if option '-A' is not given. " + "If the class is numeric, you might want to use the supervised version of " + "this filter.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.m_Columns.setUpper(instanceInfo.numAttributes() - 1);
this.setOutputFormat();
return true;
}
/**
* Input an instance for filtering. Filter requires all training instances be read before producing output.
*
* @param instance
* the input instance
* @return true if the filtered instance may now be collected with output().
* @throws InterruptedException
* @throws IllegalStateException
* if no input format has been set
*/
@Override
public boolean input(final Instance instance) throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
this.convertInstance(instance);
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tSets if binary attributes are to be coded as nominal ones.", "N", 0, "-N"));
newVector.addElement(new Option("\tFor each nominal value a new attribute is created, \n" + "\tnot only if there are more than 2 values.", "A", 0, "-A"));
newVector.addElement(new Option("\tSpecifies list of columns to act on. First and last are \n" + "\tvalid indexes.\n" + "\t(default: first-last)", "R", 1, "-R <col1,col2-col4,...>"));
newVector.addElement(new Option("\tInvert matching sense of column indexes.", "V", 0, "-V"));
newVector.addElement(
new Option("\tWhen generating binary attributes, spread weight of old " + "attribute across new attributes. Do not give each new attribute the old weight.\n\t", "spread-attribute-weight", 0, "-spread-attribute-weight"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -N
* Sets if binary attributes are to be coded as nominal ones.
* </pre>
*
* <pre>
* -A
* For each nominal value a new attribute is created,
* not only if there are more than 2 values.
* </pre>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to act on. First and last are
* valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -spread-attribute-weight
* When generating binary attributes, spread weight of old
* attribute across new attributes. Do not give each new attribute the old weight.
* </pre>
*
* <!-- options-end -->
*
* @param options
* the list of options as an array of strings
* @throws Exception
* if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setBinaryAttributesNominal(Utils.getFlag('N', options));
this.setTransformAllValues(Utils.getFlag('A', options));
String convertList = Utils.getOption('R', options);
if (convertList.length() != 0) {
this.setAttributeIndices(convertList);
} else {
this.setAttributeIndices("first-last");
}
this.setInvertSelection(Utils.getFlag('V', options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
this.setSpreadAttributeWeight(Utils.getFlag("spread-attribute-weight", options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (this.getBinaryAttributesNominal()) {
options.add("-N");
}
if (this.getTransformAllValues()) {
options.add("-A");
}
if (!this.getAttributeIndices().equals("")) {
options.add("-R");
options.add(this.getAttributeIndices());
}
if (this.getInvertSelection()) {
options.add("-V");
}
if (this.getSpreadAttributeWeight()) {
options.add("-spread-attribute-weight");
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String spreadAttributeWeightTipText() {
return "When generating binary attributes, spread weight of old attribute across new attributes. " + "Do not give each new attribute the old weight.";
}
/**
* If true, when generating binary attributes, spread weight of old attribute across new attributes. Do not give each new attribute the old weight.
*
* @param p
* whether weight is spread
*/
public void setSpreadAttributeWeight(final boolean p) {
this.m_SpreadAttributeWeight = p;
}
/**
* If true, when generating binary attributes, spread weight of old attribute across new attributes. Do not give each new attribute the old weight.
*
* @return whether weight is spread
*/
public boolean getSpreadAttributeWeight() {
return this.m_SpreadAttributeWeight;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String binaryAttributesNominalTipText() {
return "Whether resulting binary attributes will be nominal.";
}
/**
* Gets if binary attributes are to be treated as nominal ones.
*
* @return true if binary attributes are to be treated as nominal ones
*/
public boolean getBinaryAttributesNominal() {
return !this.m_Numeric;
}
/**
* Sets if binary attributes are to be treates as nominal ones.
*
* @param bool
* true if binary attributes are to be treated as nominal ones
*/
public void setBinaryAttributesNominal(final boolean bool) {
this.m_Numeric = !bool;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String transformAllValuesTipText() {
return "Whether all nominal values are turned into new attributes, not only if there are more than 2 values.";
}
/**
* Gets if all nominal values are turned into new attributes, not only if there are more than 2.
*
* @return true all nominal values are transformed into new attributes
*/
public boolean getTransformAllValues() {
return this.m_TransformAll;
}
/**
* Sets whether all nominal values are transformed into new attributes, not just if there are more than 2.
*
* @param bool
* true if all nominal value are transformed into new attributes
*/
public void setTransformAllValues(final boolean bool) {
this.m_TransformAll = bool;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected" + " (nominal) attributes in the range will be processed; if" + " true, only non-selected attributes will be processed.";
}
/**
* Gets whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return this.m_Columns.getInvert();
}
/**
* Sets whether selected columns should be removed or kept. If true the selected columns are kept and unselected columns are deleted. If false selected columns are deleted and unselected columns are kept.
*
* @param invert
* the new invert setting
*/
public void setInvertSelection(final boolean invert) {
this.m_Columns.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on." + " This is a comma separated list of attribute indices, with" + " \"first\" and \"last\" valid values. Specify an inclusive" + " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return this.m_Columns.getRanges();
}
/**
* Sets which attributes are to be acted on.
*
* @param rangeList
* a string representing the list of attributes. Since the string will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException
* if an invalid range list is supplied
*/
public void setAttributeIndices(final String rangeList) {
this.m_Columns.setRanges(rangeList);
}
/**
* Set the output format if the class is nominal.
*
* @throws InterruptedException
*/
private void setOutputFormat() throws InterruptedException {
ArrayList<Attribute> newAtts;
int newClassIndex;
StringBuffer attributeName;
Instances outputFormat;
ArrayList<String> vals;
// Compute new attributes
this.m_needToTransform = false;
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
// XXX Killed WEKA
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Attribute att = this.getInputFormat().attribute(i);
if (att.isNominal() && i != this.getInputFormat().classIndex() && (att.numValues() > 2 || this.m_TransformAll || this.m_Numeric)) {
this.m_needToTransform = true;
break;
}
}
if (!this.m_needToTransform) {
this.setOutputFormat(this.getInputFormat());
return;
}
newClassIndex = this.getInputFormat().classIndex();
newAtts = new ArrayList<Attribute>();
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
// XXX Killed WEKA
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Attribute att = this.getInputFormat().attribute(j);
if (!att.isNominal() || (j == this.getInputFormat().classIndex()) || !this.m_Columns.isInRange(j)) {
newAtts.add((Attribute) att.copy());
} else {
if ((att.numValues() <= 2) && (!this.m_TransformAll)) {
if (this.m_Numeric) {
String value = "";
if (att.numValues() == 2) {
value = "=" + att.value(1);
}
Attribute a = new Attribute(att.name() + value);
a.setWeight(att.weight());
newAtts.add(a);
} else {
newAtts.add((Attribute) att.copy());
}
} else {
if (newClassIndex >= 0 && j < this.getInputFormat().classIndex()) {
newClassIndex += att.numValues() - 1;
}
// Compute values for new attributes
for (int k = 0; k < att.numValues(); k++) {
// XXX Killed WEKA
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
attributeName = new StringBuffer(att.name() + "=");
attributeName.append(att.value(k));
if (this.m_Numeric) {
Attribute a = new Attribute(attributeName.toString());
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / att.numValues());
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
} else {
vals = new ArrayList<String>(2);
vals.add("f");
vals.add("t");
Attribute a = new Attribute(attributeName.toString(), vals);
if (this.getSpreadAttributeWeight()) {
a.setWeight(att.weight() / att.numValues());
} else {
a.setWeight(att.weight());
}
newAtts.add(a);
}
}
}
}
}
outputFormat = new Instances(this.getInputFormat().relationName(), newAtts, 0);
outputFormat.setClassIndex(newClassIndex);
this.setOutputFormat(outputFormat);
}
/**
* Convert a single instance over if the class is nominal. The converted instance is added to the end of the output queue.
*
* @param instance
* the instance to convert
* @throws InterruptedException
*/
private void convertInstance(final Instance instance) throws InterruptedException {
if (!this.m_needToTransform) {
this.push(instance);
return;
}
double[] vals = new double[this.outputFormatPeek().numAttributes()];
int attSoFar = 0;
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
// XXX Killed WEKA
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Attribute att = this.getInputFormat().attribute(j);
if (!att.isNominal() || (j == this.getInputFormat().classIndex()) || !this.m_Columns.isInRange(j)) {
vals[attSoFar] = instance.value(j);
attSoFar++;
} else {
if ((att.numValues() <= 2) && (!this.m_TransformAll)) {
vals[attSoFar] = instance.value(j);
attSoFar++;
} else {
if (instance.isMissing(j)) {
for (int k = 0; k < att.numValues(); k++) {
vals[attSoFar + k] = instance.value(j);
}
} else {
for (int k = 0; k < att.numValues(); k++) {
if (k == (int) instance.value(j)) {
vals[attSoFar + k] = 1;
} else {
vals[attSoFar + k] = 0;
}
}
}
attSoFar += att.numValues();
}
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
this.copyValues(inst, false, instance.dataset(), this.getOutputFormat());
this.push(inst); // No need to copy instance
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv
* should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new NominalToBinary(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NominalToString.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NominalToString.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Converts a nominal attribute (i.e. set number of
* values) to string (i.e. unspecified number of values).
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the range of attributes to convert (default last).
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class NominalToString extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 8655492378380068939L;
/** The attribute's index setting. */
private final Range m_AttIndex = new Range("last");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Converts a nominal attribute (that is, a set number of values) to string "
+ "(that is, an unspecified number of values).";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if the selected attribute a
* string attribute.
* @throws Exception if the input format can't be set successfully.
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
/*
* if (!instanceInfo.attribute(m_AttIndex.getIndex()).isNominal()) throw new
* UnsupportedAttributeTypeException("Chosen attribute is not of " +
* "type nominal.");
*/
return false;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @param instance the input instance.
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input structure has been defined.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isOutputFormatDefined()) {
Instance newInstance = (Instance) instance.copy();
push(newInstance, false); // No need to copy
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.
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isOutputFormatDefined()) {
setOutputFormat();
// Convert pending input instances
for (int i = 0; i < getInputFormat().numInstances(); i++) {
push((Instance) getInputFormat().instance(i).copy(), false); // No need to copy
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSets the range of attributes to convert (default last).", "C", 1,
"-C <col>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the range of attributes to convert (default last).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0) {
setAttributeIndexes(tmpStr);
} else {
setAttributeIndexes("last");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-C");
result.add("" + (getAttributeIndexes()));
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexesTipText() {
return "Sets a range attributes to process. Any non-nominal "
+ "attributes in the range are left untouched (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndexes() {
// return m_AttIndex.getSingleIndex();
return m_AttIndex.getRanges();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndexes(String attIndex) {
// m_AttIndex.setSingleIndex(attIndex);
m_AttIndex.setRanges(attIndex);
}
/**
* Set the output format. Takes the current average class values and
* m_InputFormat and calls setOutputFormat(Instances) appropriately.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts = new ArrayList<Attribute>(getInputFormat()
.numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (!att.isNominal() || !m_AttIndex.isInRange(j)) {
newAtts.add(att);
} else {
Attribute newAtt = new Attribute(att.name(), (ArrayList<String>) null);
newAtt.setWeight(getInputFormat().attribute(j).weight());
newAtts.add(newAtt);
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new NominalToString(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Normalize.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Normalize.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Sourcable;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Normalizes all numeric values in the given dataset
* (apart from the class attribute, if set). By default, the resulting values are
* in [0,1] for the data used to compute the normalization intervals. But with
* the scale and translation parameters one can change that, e.g., with scale =
* 2.0 and translation = -1.0 you get values in the range [-1,+1].
* <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>
* -S <num>
* The scaling factor for the output range.
* (default: 1.0)
* </pre>
*
* <pre>
* -T <num>
* The translation of the output range.
* (default: 0.0)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Normalize extends PotentialClassIgnorer implements UnsupervisedFilter, Sourcable, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
static final long serialVersionUID = -8158531150984362898L;
/** The minimum values for numeric attributes. */
protected double[] m_MinArray;
/** The maximum values for numeric attributes. */
protected double[] m_MaxArray;
/** The translation of the output range. */
protected double m_Translation = 0;
/** The scaling factor of the output range. */
protected double m_Scale = 1.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 "Normalizes all numeric values in the given dataset (apart from the " + "class attribute, if set). By default, the resulting values are " + "in [0,1] for the data used to compute the normalization intervals. "
+ "But with the scale and translation parameters one can change that, " + "e.g., with scale = 2.0 and translation = -1.0 you get values in the " + "range [-1,+1].";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe scaling factor for the output range.\n" + "\t(default: 1.0)", "S", 1, "-S <num>"));
result.addElement(new Option("\tThe translation of the output range.\n" + "\t(default: 0.0)", "T", 1, "-T <num>"));
result.addAll(Collections.list(super.listOptions()));
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>
* -S <num>
* The scaling factor for the output range.
* (default: 1.0)
* </pre>
*
* <pre>
* -T <num>
* The translation of the output range.
* (default: 0.0)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0) {
this.setScale(Double.parseDouble(tmpStr));
} else {
this.setScale(1.0);
}
tmpStr = Utils.getOption('T', options);
if (tmpStr.length() != 0) {
this.setTranslation(Double.parseDouble(tmpStr));
} else {
this.setTranslation(0.0);
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-S");
result.add("" + this.getScale());
result.add("-T");
result.add("" + this.getTranslation());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
this.m_MinArray = this.m_MaxArray = null;
return true;
}
/**
* Input an instance for filtering. Filter requires all training instances be
* read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws Exception if an error occurs
* @throws IllegalStateException if no input format has been set.
*/
@Override
public boolean input(final Instance instance) throws Exception {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.m_MinArray == null) {
this.bufferInput(instance);
return false;
} else {
this.convertInstance(instance);
return true;
}
}
/**
* Signify 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 Exception if an error occurs
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_MinArray == null) {
Instances input = this.getInputFormat();
// Compute minimums and maximums
this.m_MinArray = new double[input.numAttributes()];
this.m_MaxArray = new double[input.numAttributes()];
for (int i = 0; i < input.numAttributes(); i++) {
this.m_MinArray[i] = Double.NaN;
}
for (int j = 0; j < input.numInstances(); j++) {
double[] value = input.instance(j).toDoubleArray();
for (int i = 0; i < input.numAttributes(); i++) {
if (input.attribute(i).isNumeric() && (input.classIndex() != i)) {
if (!Utils.isMissingValue(value[i])) {
if (Double.isNaN(this.m_MinArray[i])) {
this.m_MinArray[i] = this.m_MaxArray[i] = value[i];
} else {
if (value[i] < this.m_MinArray[i]) {
this.m_MinArray[i] = value[i];
}
if (value[i] > this.m_MaxArray[i]) {
this.m_MaxArray[i] = value[i];
}
}
}
}
}
}
// Convert pending input instances
for (int i = 0; i < input.numInstances(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
this.convertInstance(input.instance(i));
}
}
// Free memory
this.flushInput();
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
* @throws Exception if conversion fails
*/
protected void convertInstance(final Instance instance) throws Exception {
Instance inst = null;
if (instance instanceof SparseInstance) {
double[] newVals = new double[instance.numAttributes()];
int[] newIndices = new int[instance.numAttributes()];
double[] vals = instance.toDoubleArray();
int ind = 0;
for (int j = 0; j < instance.numAttributes(); j++) {
double value;
if (instance.attribute(j).isNumeric() && (!Utils.isMissingValue(vals[j])) && (this.getInputFormat().classIndex() != j)) {
if (Double.isNaN(this.m_MinArray[j]) || (this.m_MaxArray[j] == this.m_MinArray[j])) {
value = 0;
} else {
value = (vals[j] - this.m_MinArray[j]) / (this.m_MaxArray[j] - this.m_MinArray[j]) * this.m_Scale + this.m_Translation;
if (Double.isNaN(value)) {
throw new Exception("A NaN value was generated " + "while normalizing " + instance.attribute(j).name());
}
}
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
} else {
value = vals[j];
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
}
}
double[] tempVals = new double[ind];
int[] tempInd = new int[ind];
System.arraycopy(newVals, 0, tempVals, 0, ind);
System.arraycopy(newIndices, 0, tempInd, 0, ind);
inst = new SparseInstance(instance.weight(), tempVals, tempInd, instance.numAttributes());
} else {
double[] vals = instance.toDoubleArray();
for (int j = 0; j < this.getInputFormat().numAttributes(); j++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (instance.attribute(j).isNumeric() && (!Utils.isMissingValue(vals[j])) && (this.getInputFormat().classIndex() != j)) {
if (Double.isNaN(this.m_MinArray[j]) || (this.m_MaxArray[j] == this.m_MinArray[j])) {
vals[j] = 0;
} else {
vals[j] = (vals[j] - this.m_MinArray[j]) / (this.m_MaxArray[j] - this.m_MinArray[j]) * this.m_Scale + this.m_Translation;
if (Double.isNaN(vals[j])) {
throw new Exception("A NaN value was generated " + "while normalizing " + instance.attribute(j).name());
}
}
}
}
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
this.push(inst, false); // No need to copy
}
/**
* Returns a string that describes the filter as source. The filter will be
* contained in a class with the given name (there may be auxiliary classes),
* and will contain two methods with these signatures:
*
* <pre>
* <code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code>
* </pre>
*
* where the array <code>i</code> contains elements that are either Double,
* String, with missing values represented as null. The generated code is
* public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
@Override
public String toSource(final String className, final Instances data) throws Exception {
StringBuffer result;
boolean[] process;
int i;
result = new StringBuffer();
// determine what attributes were processed
process = new boolean[data.numAttributes()];
for (i = 0; i < data.numAttributes(); i++) {
process[i] = (data.attribute(i).isNumeric() && (i != data.classIndex()));
}
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /** lists which attributes will be processed */\n");
result.append(" protected final static boolean[] PROCESS = new boolean[]{" + Utils.arrayToString(process) + "};\n");
result.append("\n");
result.append(" /** the minimum values for numeric values */\n");
result.append(" protected final static double[] MIN = new double[]{" + Utils.arrayToString(this.m_MinArray).replaceAll("NaN", "Double.NaN") + "};\n");
result.append("\n");
result.append(" /** the maximum values for numeric values */\n");
result.append(" protected final static double[] MAX = new double[]{" + Utils.arrayToString(this.m_MaxArray) + "};\n");
result.append("\n");
result.append(" /** the scale factor */\n");
result.append(" protected final static double SCALE = " + this.m_Scale + ";\n");
result.append("\n");
result.append(" /** the translation */\n");
result.append(" protected final static double TRANSLATION = " + this.m_Translation + ";\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" Object[] result;\n");
result.append("\n");
result.append(" result = new Object[i.length];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" if (PROCESS[n] && (i[n] != null)) {\n");
result.append(" if (Double.isNaN(MIN[n]) || (MIN[n] == MAX[n]))\n");
result.append(" result[n] = 0;\n");
result.append(" else\n");
result.append(" result[n] = (((Double) i[n]) - MIN[n]) / (MAX[n] - MIN[n]) * SCALE + TRANSLATION;\n");
result.append(" }\n");
result.append(" else {\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" Object[][] result;\n");
result.append("\n");
result.append(" result = new Object[i.length][];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" result[n] = filter(i[n]);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
}
/**
* Returns the calculated minimum values for the attributes in the data.
*
* @return the array with the minimum values
*/
public double[] getMinArray() {
return this.m_MinArray;
}
/**
* Returns the calculated maximum values for the attributes in the data.
*
* @return the array with the maximum values
*/
public double[] getMaxArray() {
return this.m_MaxArray;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String scaleTipText() {
return "The factor for scaling the output range (default: 1).";
}
/**
* Get the scaling factor.
*
* @return the factor
*/
public double getScale() {
return this.m_Scale;
}
/**
* Sets the scaling factor.
*
* @param value the scaling factor
*/
public void setScale(final double value) {
this.m_Scale = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String translationTipText() {
return "The translation of the output range (default: 0).";
}
/**
* Get the translation.
*
* @return the translation
*/
public double getTranslation() {
return this.m_Translation;
}
/**
* Sets the translation.
*
* @param value the translation
*/
public void setTranslation(final double value) {
this.m_Translation = value;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for running this filter.
*
* @param args should contain arguments to the filter, use -h for help
*/
public static void main(final String[] args) {
runFilter(new Normalize(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NumericCleaner.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NumericCleaner.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleStreamFilter;
/**
* <!-- globalinfo-start --> A filter that 'cleanses' the numeric data from
* values that are too small, too big or very close to a certain value,
* and sets these values to a pre-defined default.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -output-debug-info
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -min <double>
* The minimum threshold. (default -Double.MAX_VALUE)
* </pre>
*
* <pre>
* -min-default <double>
* The minimum threshold below which values are replaced by the corresponding default.
* (default -Double.MAX_VALUE)
* </pre>
*
* <pre>
* -max <double>
* The maximum threshold above which values are replaced by the corresponding default.
* (default Double.MAX_VALUE)
* </pre>
*
* <pre>
* -max-default <double>
* The replacement for values larger than the maximum threshold.
* (default Double.MAX_VALUE)
* </pre>
*
* <pre>
* -closeto <double>
* The value with respect to which closeness is determined. (default 0)
* </pre>
*
* <pre>
* -closeto-default <double>
* The replacement for values that are too close to '-closeto'.
* (default 0)
* </pre>
*
* <pre>
* -closeto-tolerance <double>
* The tolerance for testing whether a value is too close. (default 1E-6)
* </pre>
*
* <pre>
* -decimals <int>
* The number of decimals to round to, -1 means no rounding at all.
* (default -1)
* </pre>
*
* <pre>
* -R <col1,col2,...>
* The list of columns to cleanse, e.g., first-last or first-3,5-last.
* (default first-last)
* </pre>
*
* <pre>
* -V
* Inverts the matching sense.
* </pre>
*
* <pre>
* -include-class
* Whether to include the class in the cleansing.
* The class column will always be skipped if this flag is not
* present. (default no)
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class NumericCleaner extends SimpleStreamFilter implements WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -352890679895066592L;
/** the minimum threshold */
protected double m_MinThreshold = -Double.MAX_VALUE;
/** the minimum default replacement value */
protected double m_MinDefault = -Double.MAX_VALUE;
/** the maximum threshold */
protected double m_MaxThreshold = Double.MAX_VALUE;
/** the maximum default replacement value */
protected double m_MaxDefault = Double.MAX_VALUE;
/** the number the values are checked for closeness to */
protected double m_CloseTo = 0;
/** the default replacement value for numbers "close-to" */
protected double m_CloseToDefault = 0;
/**
* the tolerance distance, below which numbers are considered being "close-to"
*/
protected double m_CloseToTolerance = 1E-6;
/** Stores which columns to cleanse */
protected Range m_Cols = new Range("first-last");
/** whether to include the class attribute */
protected boolean m_IncludeClass = false;
/** the number of decimals to round to (-1 means no rounding) */
protected int m_Decimals = -1;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter that 'cleanses' the numeric data from values that are too "
+ "small, too big or very close to a certain value, and sets "
+ "these values to a pre-defined default.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(11);
result.addElement(new Option(
"\tThe minimum threshold below which values are replaced by the corresponding default.\n" +
"\t(default -Double.MAX_VALUE)", "min", 1,
"-min <double>"));
result.addElement(new Option(
"\tThe replacement for values smaller than the minimum threshold.\n"
+ "\t(default -Double.MAX_VALUE)", "min-default", 1,
"-min-default <double>"));
result.addElement(new Option(
"\tThe maximum threshold above which values are replaced by the corresponding default.\n" +
"\t(default Double.MAX_VALUE)", "max", 1,
"-max <double>"));
result.addElement(new Option(
"\tThe replacement for values larger than the maximum threshold.\n"
+ "\t(default Double.MAX_VALUE)", "max-default", 1,
"-max-default <double>"));
result.addElement(new Option(
"\tThe value with respect to which closeness is determined. (default 0)", "closeto",
1, "-closeto <double>"));
result.addElement(new Option(
"\tThe replacement for values that are too close to '-closeto'.\n"
+ "\t(default 0)", "closeto-default", 1, "-closeto-default <double>"));
result.addElement(new Option(
"\tThe tolerance for testing whether a value is too close.\n" +
"\t(default 1E-6)", "closeto-tolerance", 1,
"-closeto-tolerance <double>"));
result.addElement(new Option(
"\tThe number of decimals to round to, -1 means no rounding at all.\n"
+ "\t(default -1)", "decimals", 1, "-decimals <int>"));
result.addElement(new Option(
"\tThe list of columns to cleanse, e.g., first-last or first-3,5-last.\n"
+ "\t(default first-last)", "R", 1, "-R <col1,col2,...>"));
result
.addElement(new Option("\tInverts the matching sense.", "V", 0, "-V"));
result.addElement(new Option(
"\tWhether to include the class in the cleansing.\n"
+ "\tThe class column will always be skipped if this flag is not\n"
+ "\tpresent. (default no)", "include-class", 0, "-include-class"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>(20);
result.add("-min");
result.add("" + m_MinThreshold);
result.add("-min-default");
result.add("" + m_MinDefault);
result.add("-max");
result.add("" + m_MaxThreshold);
result.add("-max-default");
result.add("" + m_MaxDefault);
result.add("-closeto");
result.add("" + m_CloseTo);
result.add("-closeto-default");
result.add("" + m_CloseToDefault);
result.add("-closeto-tolerance");
result.add("" + m_CloseToTolerance);
result.add("-R");
result.add("" + m_Cols.getRanges());
if (m_Cols.getInvert()) {
result.add("-V");
}
if (m_IncludeClass) {
result.add("-include-class");
}
result.add("-decimals");
result.add("" + getDecimals());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -output-debug-info
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -min <double>
* The minimum threshold. (default -Double.MAX_VALUE)
* </pre>
*
* <pre>
* -min-default <double>
* The minimum threshold below which values are replaced by the corresponding default.
* (default -Double.MAX_VALUE)
* </pre>
*
* <pre>
* -max <double>
* The maximum threshold above which values are replaced by the corresponding default.
* (default Double.MAX_VALUE)
* </pre>
*
* <pre>
* -max-default <double>
* The replacement for values larger than the maximum threshold.
* (default Double.MAX_VALUE)
* </pre>
*
* <pre>
* -closeto <double>
* The value with respect to which closeness is determined. (default 0)
* </pre>
*
* <pre>
* -closeto-default <double>
* The replacement for values that are too close to '-closeto'.
* (default 0)
* </pre>
*
* <pre>
* -closeto-tolerance <double>
* The tolerance for testing whether a value is too close. (default 1E-6)
* </pre>
*
* <pre>
* -decimals <int>
* The number of decimals to round to, -1 means no rounding at all.
* (default -1)
* </pre>
*
* <pre>
* -R <col1,col2,...>
* The list of columns to cleanse, e.g., first-last or first-3,5-last.
* (default first-last)
* </pre>
*
* <pre>
* -V
* Inverts the matching sense.
* </pre>
*
* <pre>
* -include-class
* Whether to include the class in the cleansing.
* The class column will always be skipped if this flag is not
* present. (default no)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption("min", options);
if (tmpStr.length() != 0) {
setMinThreshold(Double.parseDouble(tmpStr));
} else {
setMinThreshold(-Double.MAX_VALUE);
}
tmpStr = Utils.getOption("min-default", options);
if (tmpStr.length() != 0) {
setMinDefault(Double.parseDouble(tmpStr));
} else {
setMinDefault(-Double.MAX_VALUE);
}
tmpStr = Utils.getOption("max", options);
if (tmpStr.length() != 0) {
setMaxThreshold(Double.parseDouble(tmpStr));
} else {
setMaxThreshold(Double.MAX_VALUE);
}
tmpStr = Utils.getOption("max-default", options);
if (tmpStr.length() != 0) {
setMaxDefault(Double.parseDouble(tmpStr));
} else {
setMaxDefault(Double.MAX_VALUE);
}
tmpStr = Utils.getOption("closeto", options);
if (tmpStr.length() != 0) {
setCloseTo(Double.parseDouble(tmpStr));
} else {
setCloseTo(0);
}
tmpStr = Utils.getOption("closeto-default", options);
if (tmpStr.length() != 0) {
setCloseToDefault(Double.parseDouble(tmpStr));
} else {
setCloseToDefault(0);
}
tmpStr = Utils.getOption("closeto-tolerance", options);
if (tmpStr.length() != 0) {
setCloseToTolerance(Double.parseDouble(tmpStr));
} else {
setCloseToTolerance(1E-6);
}
tmpStr = Utils.getOption("R", options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("first-last");
}
setInvertSelection(Utils.getFlag("V", options));
setIncludeClass(Utils.getFlag("include-class", options));
tmpStr = Utils.getOption("decimals", options);
if (tmpStr.length() != 0) {
setDecimals(Integer.parseInt(tmpStr));
} else {
setDecimals(-1);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
m_Cols.setUpper(inputFormat.numAttributes() - 1);
return new Instances(inputFormat);
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
int i;
double val;
double factor;
double[] result = new double[instance.numAttributes()];
if (m_Decimals > -1) {
factor = StrictMath.pow(10, m_Decimals);
} else {
factor = 1;
}
for (i = 0; i < instance.numAttributes(); i++) {
// Save old value for the moment
result[i] = instance.value(i);
// only numeric attributes
if (!instance.attribute(i).isNumeric()) {
continue;
}
// out of range?
if (!m_Cols.isInRange(i)) {
continue;
}
// skip class?
if ((instance.classIndex() == i) && (!m_IncludeClass)) {
continue;
}
// too small?
if (result[i] < m_MinThreshold) {
if (getDebug()) {
System.out.println("Too small: " + result[i] + " -> "
+ m_MinDefault);
}
result[i] = m_MinDefault;
}
// too big?
else if (result[i] > m_MaxThreshold) {
if (getDebug()) {
System.out.println("Too big: " + result[i] + " -> "
+ m_MaxDefault);
}
result[i] = m_MaxDefault;
}
// too close?
else if ((result[i] - m_CloseTo < m_CloseToTolerance)
&& (m_CloseTo - result[i] < m_CloseToTolerance)
&& (result[i] != m_CloseTo)) {
if (getDebug()) {
System.out.println("Too close: " + result[i] + " -> "
+ m_CloseToDefault);
}
result[i] = m_CloseToDefault;
}
// decimals?
if (m_Decimals > -1 && !Utils.isMissingValue(result[i])) {
val = result[i];
val = StrictMath.round(val * factor) / factor;
result[i] = val;
}
}
return instance.copy(result);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String minThresholdTipText() {
return "The minimum threshold below which values are replaced by the corresponding default.";
}
/**
* Get the minimum threshold.
*
* @return the minimum threshold.
*/
public double getMinThreshold() {
return m_MinThreshold;
}
/**
* Set the minimum threshold.
*
* @param value the minimum threshold to use.
*/
public void setMinThreshold(double value) {
m_MinThreshold = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String minDefaultTipText() {
return "The replacement for values smaller than the minimum threshold.";
}
/**
* Get the minimum default.
*
* @return the minimum default.
*/
public double getMinDefault() {
return m_MinDefault;
}
/**
* Set the minimum default.
*
* @param value the minimum default to use.
*/
public void setMinDefault(double value) {
m_MinDefault = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxThresholdTipText() {
return "The maximum threshold above which values are replaced by the corresponding default.";
}
/**
* Get the maximum threshold.
*
* @return the maximum threshold.
*/
public double getMaxThreshold() {
return m_MaxThreshold;
}
/**
* Set the maximum threshold.
*
* @param value the maximum threshold to use.
*/
public void setMaxThreshold(double value) {
m_MaxThreshold = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxDefaultTipText() {
return "The replacement for values larger than the maximum threshold.";
}
/**
* Get the maximum default.
*
* @return the maximum default.
*/
public double getMaxDefault() {
return m_MaxDefault;
}
/**
* Set the naximum default.
*
* @param value the maximum default to use.
*/
public void setMaxDefault(double value) {
m_MaxDefault = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String closeToTipText() {
return "The value with respect to which closeness is determined.";
}
/**
* Get the "close to" number.
*
* @return the "close to" number.
*/
public double getCloseTo() {
return m_CloseTo;
}
/**
* Set the "close to" number.
*
* @param value the number to use for checking closeness.
*/
public void setCloseTo(double value) {
m_CloseTo = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String closeToDefaultTipText() {
return "The replacement for values that are too close.";
}
/**
* Get the "close to" default.
*
* @return the "close to" default.
*/
public double getCloseToDefault() {
return m_CloseToDefault;
}
/**
* Set the "close to" default.
*
* @param value the "close to" default to use.
*/
public void setCloseToDefault(double value) {
m_CloseToDefault = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String closeToToleranceTipText() {
return "The tolerance for testing whether a value is too close.";
}
/**
* Get the "close to" Tolerance.
*
* @return the "close to" Tolerance.
*/
public double getCloseToTolerance() {
return m_CloseToTolerance;
}
/**
* Set the "close to" Tolerance.
*
* @param value the "close to" Tolerance to use.
*/
public void setCloseToTolerance(double value) {
m_CloseToTolerance = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "The selection of columns to use in the cleansing process, first and last are valid indices.";
}
/**
* Gets the selection of the columns, e.g., first-last or first-3,5-last
*
* @return the selected indices
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets the columns to use, e.g., first-last or first-3,5-last
*
* @param value the columns to use
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "If enabled, the selection of the columns is inverted.";
}
/**
* Gets whether the selection of the columns is inverted
*
* @return true if the selection is inverted
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether the selection of the indices is inverted or not
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String includeClassTipText() {
return "If disabled, the class attribute will be left out of the cleaning process.";
}
/**
* Gets whether the class is included in the cleaning process or always
* skipped.
*
* @return true if the class can be considered for cleaning.
*/
public boolean getIncludeClass() {
return m_IncludeClass;
}
/**
* Sets whether the class can be cleaned, too.
*
* @param value true if the class can be cleansed, too
*/
public void setIncludeClass(boolean value) {
m_IncludeClass = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String decimalsTipText() {
return "The number of decimals to round to, -1 means no rounding at all.";
}
/**
* Get the number of decimals to round to.
*
* @return the number of decimals.
*/
public int getDecimals() {
return m_Decimals;
}
/**
* Set the number of decimals to round to.
*
* @param value the number of decimals.
*/
public void setDecimals(int value) {
m_Decimals = value;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Runs the filter from commandline, use "-h" to see all options.
*
* @param args the commandline options for the filter
*/
public static void main(String[] args) {
runFilter(new NumericCleaner(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NumericToBinary.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NumericToBinary.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Converts all numeric attributes into binary
* attributes (apart from the class attribute, if set): if the value of the
* numeric attribute is exactly zero, the value of the new attribute will be
* zero. If the value of the numeric attribute is missing, the value of the new
* attribute will be missing. Otherwise, the value of the new attribute will be
* one. The new attributes will be nominal.
* <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>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NumericToBinary extends PotentialClassIgnorer implements
UnsupervisedFilter, StreamableFilter, WeightedInstancesHandler, WeightedAttributesHandler {
/** Stores which columns to turn into binary */
protected Range m_Cols = new Range("first-last");
/** The default columns to turn into binary */
protected String m_DefaultCols = "first-last";
/** for serialization */
static final long serialVersionUID = 2616879323359470802L;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Converts all numeric attributes into binary attributes (apart from "
+ "the class attribute, if set): if the value of the numeric attribute is "
+ "exactly zero, the value of the new attribute will be zero. If the "
+ "value of the numeric attribute is missing, the value of the new "
+ "attribute will be missing. Otherwise, the value of the new "
+ "attribute will be one. The new attributes will be nominal.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(2);
result.addElement(new Option(
"\tSpecifies list of columns to binarize. 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"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to binarize. First and last are valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setInvertSelection(Utils.getFlag('V', options));
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices(m_DefaultCols);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if ( !getAttributeIndices().equals("") ) {
result.add("-R");
result.add(getAttributeIndices());
}
if( getInvertSelection() ) {
result.add("-V");
}
return result.toArray( new String[result.size()] );
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " (numeric) attributes in the range will be 'binarized'; if"
+ " true, only non-selected attributes will be 'binarized'.";
}
/**
* Gets whether the supplied columns are to be worked on or the others.
*
* @return true if the supplied columns will be worked on
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether selected columns should be worked on or all the others apart
* from these. If true all the other columns are considered for
* "binarization".
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets which attributes are to be "binarized" (only numeric attributes
* among the selection will be transformed).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Sets which attributes are to be transformed to binary. (only numeric
* attributes among the selection will be transformed).
*
* @param value an array containing indexes of attributes to binarize. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* 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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat();
return true;
}
/**
* Input an instance for filtering.
*
* @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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
convertInstance(instance);
return true;
}
/**
* Set the output format.
*/
private void setOutputFormat() {
ArrayList<Attribute> newAtts;
int newClassIndex;
StringBuffer attributeName;
Instances outputFormat;
ArrayList<String> vals;
m_Cols.setUpper(getInputFormat().numAttributes() - 1);
// Compute new attributes
newClassIndex = getInputFormat().classIndex();
newAtts = new ArrayList<Attribute>();
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if ((j == newClassIndex) || (!att.isNumeric()) || !m_Cols.isInRange(j) ) {
newAtts.add(att); // Not necessary to make a copy because index does not change
} else {
attributeName = new StringBuffer(att.name() + "_binarized");
vals = new ArrayList<String>(2);
vals.add("0");
vals.add("1");
Attribute a = new Attribute(attributeName.toString(), vals);
a.setWeight(att.weight());
newAtts.add(a);
}
}
outputFormat = new Instances(getInputFormat().relationName(), newAtts, 0);
outputFormat.setClassIndex(newClassIndex);
setOutputFormat(outputFormat);
}
/**
* Convert a single instance over. The converted instance is added to the end
* of the output queue.
*
* @param instance the instance to convert
*/
private void convertInstance(Instance instance) {
Instance inst = null;
if (instance instanceof SparseInstance) {
double[] vals = new double[instance.numValues()];
int[] newIndices = new int[instance.numValues()];
for (int j = 0; j < instance.numValues(); j++) {
Attribute att = getInputFormat().attribute(instance.index(j));
if ((!att.isNumeric())
|| (instance.index(j) == getInputFormat().classIndex())
|| !m_Cols.isInRange(instance.index(j))) {
vals[j] = instance.valueSparse(j);
} else {
if (instance.isMissingSparse(j)) {
vals[j] = instance.valueSparse(j);
} else {
vals[j] = 1;
}
}
newIndices[j] = instance.index(j);
}
inst = new SparseInstance(instance.weight(), vals, newIndices,
outputFormatPeek().numAttributes());
} else {
double[] vals = new double[outputFormatPeek().numAttributes()];
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if ((!att.isNumeric())
|| (j == getInputFormat().classIndex())
|| !m_Cols.isInRange(j)) {
vals[j] = instance.value(j);
} else {
if (instance.isMissing(j) || (instance.value(j) == 0)) {
vals[j] = instance.value(j);
} else {
vals[j] = 1;
}
}
}
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
push(inst, false); // No need to copy
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new NumericToBinary(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NumericToDate.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* DateToNumeric.java
* Copyright (C) 2006-2017 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
/**
* <!-- globalinfo-start -->
* A filter for turning numeric attributes into date attributes.
* The numeric value is assumed to be the number of milliseconds since January 1, 1970, 00:00:00 GMT,
* corresponding to the given date."
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of attributes to turn into date ones. Only numeric attributes will be converted.
* First and last are valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -F <value index>
* Sets the output date format string (default corresponds to ISO-8601).
* </pre>
*
* <!-- options-end -->
*
* @author eibe (eibe at waikato dot ac dot nz)
* @version $Revision: 14274 $
*/
public class NumericToDate extends SimpleBatchFilter implements WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -6514657821295776239L;
/** Stores which columns to turn into date attributes */
protected Range m_Cols = new Range("first-last");
/** The default columns to turn into date attributes */
protected String m_DefaultCols = "first-last";
/** The default output date format. Corresponds to ISO-8601 format. */
protected static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
/** The output date format. */
protected SimpleDateFormat m_DateFormat = DEFAULT_FORMAT;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for turning numeric attributes into date attributes." +
"The numeric value is assumed to be the number of milliseconds since January 1, 1970, 00:00:00 GMT, " +
"corresponding to the given date.";
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(2);
result.addElement(new Option(
"\tSpecifies list of columns to convert. 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(
"\tSets the output date format string (default corresponds to ISO-8601).",
"F", 1, "-F <value index>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of attributes to turn into date ones. Only numeric attributes will be converted.
* First and last are valid indexes.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -F <value index>
* Sets the output date format string (default corresponds to ISO-8601).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setInvertSelection(Utils.getFlag('V', options));
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices(m_DefaultCols);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
String formatString = Utils.getOption('F', options);
if (formatString.length() != 0) {
setDateFormat(formatString);
} else {
setDateFormat(DEFAULT_FORMAT);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (!getAttributeIndices().equals("")) {
result.add("-R");
result.add(getAttributeIndices());
}
if (getInvertSelection()) {
result.add("-V");
}
result.add("-F");
result.add("" + getDateFormat().toPattern());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dateFormatTipText() {
return "The date format to use. This should be a "
+ "format understood by Java's SimpleDateFormat class.";
}
/**
* Get the date format used in output.
*
* @return the output date format.
*/
public SimpleDateFormat getDateFormat() {
return m_DateFormat;
}
/**
* Sets the output date format.
*
* @param dateFormat the output date format.
*/
public void setDateFormat(String dateFormat) {
setDateFormat(new SimpleDateFormat(dateFormat));
}
/**
* Sets the output date format.
*
* @param dateFormat the output date format.
*/
public void setDateFormat(SimpleDateFormat dateFormat) {
if (dateFormat == null) {
throw new NullPointerException();
}
m_DateFormat = dateFormat;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " (numeric) attributes in the range will be turned into date attributes; if"
+ " true, only non-selected attributes will be turned into date attributes.";
}
/**
* Gets whether the supplied columns are to be worked on or the others.
*
* @return true if the supplied columns will be worked on
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether selected columns should be worked on or all the others apart
* from these. If true all the other columns are considered for conversion.
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets which attributes are to be turned into date attributes (only numeric attributes
* among the selection will be transformed).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Sets which attributes are to be transformed to date attributes (only numeric
* attributes among the selection will be transformed).
*
* @param value an array containing indexes of attributes to turn into date ones. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param data the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances data) throws Exception {
m_Cols.setUpper(data.numAttributes() - 1);
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < data.numAttributes(); i++) {
if (!m_Cols.isInRange(i) || !data.attribute(i).isNumeric()) {
atts.add(data.attribute(i));
} else {
Attribute newAtt = new Attribute(data.attribute(i).name(), getDateFormat().toPattern());
newAtt.setWeight(data.attribute(i).weight());
atts.add(newAtt);
}
}
Instances result = new Instances(data.relationName(), atts, 0);
result.setClassIndex(data.classIndex());
return result;
}
/**
* This filter's output format is immediately available
*/
@Override
protected boolean hasImmediateOutputFormat() {
return true;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result = getOutputFormat();
for (int i = 0; i < instances.numInstances(); i++) {
Instance newInst = (Instance)instances.instance(i).copy();
// copy possible string, relational values
copyValues(newInst, false, instances, outputFormatPeek());
result.add(newInst);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 14274 $");
}
/**
* Runs the filter with the given parameters. Use -h to list options.
*
* @param args the commandline options
*/
public static void main(String[] args) {
runFilter(new NumericToDate(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NumericToNominal.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NumericToNominal.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Vector;
/**
* <!-- globalinfo-start --> A filter for turning numeric attributes into
* nominal ones. Unlike discretization, it just takes all numeric values and
* adds them to the list of nominal values of that attribute. Useful after CSV
* imports, to force certain attributes to become nominal, e.g., the class
* attribute, containing values from 1 to 5.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <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>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class NumericToNominal extends SimpleBatchFilter implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
private static final long serialVersionUID = -6614630932899796239L;
/** the maximum number of decimals to use */
protected final static int MAX_DECIMALS = 6;
/** Stores which columns to turn into nominals */
protected Range m_Cols = new Range("first-last");
/** The default columns to turn into nominals */
protected String m_DefaultCols = "first-last";
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter for turning numeric attributes into nominal ones. Unlike "
+ "discretization, it just takes all numeric values and adds them to "
+ "the list of nominal values of that attribute. Useful after CSV "
+ "imports, to force certain attributes to become nominal, e.g., "
+ "the class attribute, containing values from 1 to 5.";
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(2);
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"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <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>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setInvertSelection(Utils.getFlag('V', options));
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices(m_DefaultCols);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (!getAttributeIndices().equals("")) {
result.add("-R");
result.add(getAttributeIndices());
}
if (getInvertSelection()) {
result.add("-V");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " (numeric) attributes in the range will be 'nominalized'; if"
+ " true, only non-selected attributes will be 'nominalized'.";
}
/**
* Gets whether the supplied columns are to be worked on or the others.
*
* @return true if the supplied columns will be worked on
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether selected columns should be worked on or all the others apart
* from these. If true all the other columns are considered for
* "nominalization".
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets which attributes are to be "nominalized" (only numeric attributes
* among the selection will be transformed).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Sets which attributes are to be transoformed to nominal. (only numeric
* attributes among the selection will be transformed).
*
* @param value an array containing indexes of attributes to nominalize. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances data;
Instances result;
ArrayList<Attribute> atts;
ArrayList<String> values;
HashSet<Double> hash;
int i;
int n;
boolean isDate;
Instance inst;
Vector<Double> sorted;
m_Cols.setUpper(inputFormat.numAttributes() - 1);
data = new Instances(inputFormat);
atts = new ArrayList<Attribute>();
for (i = 0; i < data.numAttributes(); i++) {
if (!m_Cols.isInRange(i) || !data.attribute(i).isNumeric()) {
atts.add(data.attribute(i));
continue;
}
// date attribute?
isDate = (data.attribute(i).type() == Attribute.DATE);
// determine all available attribute values in dataset
hash = new HashSet<Double>();
for (n = 0; n < data.numInstances(); n++) {
inst = data.instance(n);
if (inst.isMissing(i)) {
continue;
}
hash.add(new Double(inst.value(i)));
}
// sort values
sorted = new Vector<Double>();
for (Double o : hash) {
sorted.add(o);
}
Collections.sort(sorted);
// create attribute from sorted values
values = new ArrayList<String>();
for (Double o : sorted) {
if (isDate) {
values.add(data.attribute(i).formatDate(o.doubleValue()));
} else {
String label = Utils.doubleToString(o.doubleValue(), MAX_DECIMALS);
if (!values.contains(label))
values.add(label);
}
}
Attribute newAtt = new Attribute(data.attribute(i).name(), values);
newAtt.setWeight(data.attribute(i).weight());
atts.add(newAtt);
}
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result;
int i;
int n;
double[] values;
String value;
Instance inst;
Instance newInst;
// we need the complete input data!
if (!isFirstBatchDone()) {
setOutputFormat(determineOutputFormat(getInputFormat()));
}
result = new Instances(getOutputFormat());
for (i = 0; i < instances.numInstances(); i++) {
inst = instances.instance(i);
values = inst.toDoubleArray();
for (n = 0; n < values.length; n++) {
if (!m_Cols.isInRange(n) || !instances.attribute(n).isNumeric()
|| inst.isMissing(n)) {
continue;
}
// get index of value
if (instances.attribute(n).type() == Attribute.DATE) {
value = inst.stringValue(n);
} else {
value = Utils.doubleToString(inst.value(n), MAX_DECIMALS);
}
int index = result.attribute(n).indexOfValue(value);
if (index == -1) {
values[n] = Utils.missingValue();;
} else {
values[n] = index;
}
}
// generate new instance
if (inst instanceof SparseInstance) {
newInst = new SparseInstance(inst.weight(), values);
} else {
newInst = new DenseInstance(inst.weight(), values);
}
// copy possible string, relational values
copyValues(newInst, false, inst.dataset(), outputFormatPeek());
result.add(newInst);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Runs the filter with the given parameters. Use -h to list options.
*
* @param args the commandline options
*/
public static void main(String[] args) {
runFilter(new NumericToNominal(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/NumericTransform.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NumericTransform.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Transforms numeric attributes using a given
* transformation method.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to transform. First and last are
* valid indexes (default none). Non-numeric columns are
* skipped.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -C <string>
* Sets the class containing transformation method.
* (default java.lang.Math)
* </pre>
*
* <pre>
* -M <string>
* Sets the method. (default abs)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NumericTransform extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -8561413333351366934L;
/** Stores which columns to transform. */
private final Range m_Cols = new Range();
/** Class containing transformation method. */
private String m_Class;
/** Transformation method. */
private String m_Method;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Transforms numeric attributes using a given transformation method.";
}
/**
* Default constructor -- sets the default transform method to
* java.lang.Math.abs().
*/
public NumericTransform() {
m_Class = "java.lang.Math";
m_Method = "abs";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
if (m_Class == null) {
throw new IllegalStateException("No class has been set.");
}
if (m_Method == null) {
throw new IllegalStateException("No method has been set.");
}
super.setInputFormat(instanceInfo);
m_Cols.setUpper(instanceInfo.numAttributes() - 1);
setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @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 set.
* @throws InvocationTargetException if there is a problem applying the
* configured transform method.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Method m = (Class.forName(m_Class)).getMethod(m_Method,
new Class[] { Double.TYPE });
double[] vals = new double[instance.numAttributes()];
Double[] params = new Double[1];
Double newVal;
for (int i = 0; i < instance.numAttributes(); i++) {
if (instance.isMissing(i)) {
vals[i] = Utils.missingValue();
} else {
if (m_Cols.isInRange(i) && instance.attribute(i).isNumeric()) {
params[0] = new Double(instance.value(i));
newVal = (Double) m.invoke(null, (Object[]) params);
if (newVal.isNaN() || newVal.isInfinite()) {
vals[i] = Utils.missingValue();
} else {
vals[i] = newVal.doubleValue();
}
} else {
vals[i] = instance.value(i);
}
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
push(inst, false); // No need to copy
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option(
"\tSpecify list of columns to transform. First and last are\n"
+ "\tvalid indexes (default none). Non-numeric columns are \n"
+ "\tskipped.", "R", 1, "-R <index1,index2-index4,...>"));
newVector.addElement(new Option("\tInvert matching sense.", "V", 0, "-V"));
newVector.addElement(new Option(
"\tSets the class containing transformation method.\n"
+ "\t(default java.lang.Math)", "C", 1, "-C <string>"));
newVector.addElement(new Option("\tSets the method. (default abs)", "M", 1,
"-M <string>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to transform. First and last are
* valid indexes (default none). Non-numeric columns are
* skipped.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -C <string>
* Sets the class containing transformation method.
* (default java.lang.Math)
* </pre>
*
* <pre>
* -M <string>
* Sets the method. (default abs)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setAttributeIndices(Utils.getOption('R', options));
setInvertSelection(Utils.getFlag('V', options));
String classString = Utils.getOption('C', options);
if (classString.length() != 0) {
setClassName(classString);
}
String methodString = Utils.getOption('M', options);
if (methodString.length() != 0) {
setMethodName(methodString);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
if (m_Class != null) {
options.add("-C");
options.add(getClassName());
}
if (m_Method != null) {
options.add("-M");
options.add(getMethodName());
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classNameTipText() {
return "Name of the class containing the method used for the transformation.";
}
/**
* Get the class containing the transformation method.
*
* @return string describing the class
*/
public String getClassName() {
return m_Class;
}
/**
* Sets the class containing the transformation method.
*
* @param name the name of the class
* @throws ClassNotFoundException if class can't be found
*/
public void setClassName(String name) throws ClassNotFoundException {
m_Class = name;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String methodNameTipText() {
return "Name of the method used for the transformation.";
}
/**
* Get the transformation method.
*
* @return string describing the transformation method.
*/
public String getMethodName() {
return m_Method;
}
/**
* Set the transformation method.
*
* @param name the name of the method
* @throws NoSuchMethodException if method can't be found in class
*/
public void setMethodName(String name) throws NoSuchMethodException {
m_Method = name;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to process the inverse of the given attribute ranges.";
}
/**
* Get whether the supplied columns are to be transformed or not
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Set whether selected columns should be transformed or not.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_Cols.setInvert(invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Set which attributes are to be transformed (or kept if invert is true).
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String rangeList) {
m_Cols.setRanges(rangeList);
}
/**
* Set which attributes are to be transformed (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new NumericTransform(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Nystroem.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Nystroem.java
* Copyright (C) 2016 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.classifiers.functions.supportVector.Kernel;
import weka.classifiers.functions.supportVector.PolyKernel;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.SimpleBatchFilter;
import weka.filters.unsupervised.instance.Resample;
import no.uib.cipr.matrix.*;
import no.uib.cipr.matrix.Matrix;
import java.util.ArrayList;
/**
<!-- globalinfo-start -->
* Implements the Nystroem method for feature extraction using a kernel function.<br>
* <br>
* For more information on the algorithm, see<br>
* <br>
* Tianbao Yang, Yu-Feng Li, Mehrdad Mahdavi, Rong Jin, Zhi-Hua Zhou: Nystr"{o}m Method vs Random Fourier Features: A Theoretical and Empirical Comparison. In: Proc 26th Annual Conference on Neural Information Processing Systems, 485--493, 2012.
* <br><br>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @inproceedings{Yang2012,
* author = {Tianbao Yang and Yu-Feng Li and Mehrdad Mahdavi and Rong Jin and Zhi-Hua Zhou},
* booktitle = {Proc 26th Annual Conference on Neural Information Processing Systems},
* pages = {485--493},
* title = {Nystr"{o}m Method vs Random Fourier Features: A Theoretical and Empirical Comparison},
* year = {2012},
* URL = {http://papers.nips.cc/paper/4588-nystrom-method-vs-random-fourier-features-a-theoretical-and-empirical-comparison}
* }
* </pre>
* <br><br>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p>
*
* <pre> -K <kernel specification>
* The kernel function to use.</pre>
*
* <pre> -F <filter specification>
* The filter to use, which should be a filter that takes a sample of instances.</pre>
*
* <pre> -use-svd
* Whether to use singular value decomposition instead of eigendecomposition.</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 12341 $
*/
public class Nystroem extends SimpleBatchFilter implements TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = -251931442147263433L;
/** Constant to avoid division by zero. */
public static double SMALL = 1e-6;
/** The filter to use for sub sampling. */
protected Filter m_Filter;
/** The kernel function to use. */
protected Kernel m_Kernel;
/** Determines whether singular value decomposition is used instead of eigendecomposition. */
protected boolean m_useSVD;
/** Stores the sample used for the approximation. */
protected Instances m_Sample;
/** Stores the weighting matrix. */
protected Matrix m_WeightingMatrix;
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = getKernel().getCapabilities();
result.setOwner(this);
result.setMinimumNumberInstances(0);
result.enableAllClasses();
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
/**
* Gets whether to use singular value decomposition instead of eigendecomposition.
*
* @return true if SVD is to be used
*/
@OptionMetadata(
displayName = "Use SVD and not eigendecomposition",
description = "Whether to use singular value decomposition instead of eigendecomposition.",
displayOrder = 3,
commandLineParamName = "use-svd",
commandLineParamSynopsis = "-use-svd",
commandLineParamIsFlag = true)
public boolean getUseSVD() { return m_useSVD; }
/**
* Sets whether to use singular value decomposition instead of eigendecomposition.
* @param flag true if singular value decomposition is to be used.
*/
public void setUseSVD(boolean flag) {m_useSVD = flag; }
/**
* Gets the filter that is used for sub sampling.
*
* @return the filter
*/
@OptionMetadata(
displayName = "Filter for sampling instances",
description = "The filter to use, which should be a filter that takes a sample of instances.",
displayOrder = 2,
commandLineParamName = "F",
commandLineParamSynopsis = "-F <filter specification>")
public Filter getFilter() { return m_Filter; }
/**
* Sets the filter to use for sub sampling.
*
* @param filter the filter to use
*/
public void setFilter(Filter filter) { this.m_Filter = filter; }
/**
* sets the kernel to use
*
* @param value the kernel to use
*/
public void setKernel(Kernel value) {
m_Kernel = value;
}
/**
* Returns the kernel to use
*
* @return the current kernel
*/
@OptionMetadata(
displayName = "Kernel function",
description = "The kernel function to use.", displayOrder = 1,
commandLineParamName = "K",
commandLineParamSynopsis = "-K <kernel specification>")
public Kernel getKernel() {
return m_Kernel;
}
/**
* Default constructor. Sets filter to Resample filter without replacement and sample size percentage to 10%.
* The kernel is set to PolyKernel with default options.
*/
public Nystroem() {
m_Filter = new Resample();
((Resample)m_Filter).setNoReplacement(true);
((Resample)m_Filter).setSampleSizePercent(10);
m_Kernel = new PolyKernel();
}
/**
* Provides information regarding this class.
*
* @return string describing the method that this class implements
*/
@Override
public String globalInfo() {
return "Implements the Nystroem method for feature extraction using a kernel function.\n\n" +
"For more information on the algorithm, see\n\n" + getTechnicalInformation().toString();
}
/**
* Returns a reference to the algorithm implemented by this class.
*
* @return a reference to the algorithm implemented by this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result = new TechnicalInformation(TechnicalInformation.Type.INPROCEEDINGS);
result.setValue(TechnicalInformation.Field.AUTHOR, "Tianbao Yang and Yu-Feng Li and Mehrdad Mahdavi and Rong Jin and Zhi-Hua Zhou");
result.setValue(TechnicalInformation.Field.TITLE, "Nystr\"{o}m Method vs Random Fourier Features: A Theoretical and Empirical Comparison");
result.setValue(TechnicalInformation.Field.BOOKTITLE, "Proc 26th Annual Conference on Neural Information Processing Systems");
result.setValue(TechnicalInformation.Field.PAGES, "485--493");
result.setValue(TechnicalInformation.Field.YEAR, "2012");
result.setValue(TechnicalInformation.Field.URL, "http://papers.nips.cc/paper/4588-nystrom-method-vs-random-fourier-features-a-theoretical-and-empirical-comparison");
return result;
}
/**
* Returns whether to allow the determineOutputFormat(Instances) method access
* to the full dataset rather than just the header.
* <p/>
* Default implementation returns false.
*
* @return whether determineOutputFormat has access to the full input dataset
*/
public boolean allowAccessToFullInputFormat() {
return true;
}
/**
* Determines the output format for the data that is produced by this filter.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception if a problem occurs when the output format is generated
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) throws Exception {
// Sample subset of instances
Filter filter = Filter.makeCopy(getFilter());
filter.setInputFormat(inputFormat);
m_Sample = Filter.useFilter(inputFormat, filter);
// Compute kernel-based matrices for subset
m_Kernel = Kernel.makeCopy(m_Kernel);
m_Kernel.buildKernel(m_Sample);
int m = m_Sample.numInstances();
int n = inputFormat.numInstances();
Matrix khatM = new UpperSymmDenseMatrix(m);
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
khatM.set(i, j, m_Kernel.eval(i, j, m_Sample.instance(i)));
}
}
m_Kernel.clean();
if (m_Debug) {
Matrix kbM = new DenseMatrix(n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
kbM.set(i, j, m_Kernel.eval(-1, j, inputFormat.instance(i)));
}
}
// Calculate SVD of kernel matrix
SVD svd = SVD.factorize(khatM);
double[] singularValues = svd.getS();
Matrix sigmaI = new UpperSymmDenseMatrix(m);
for (int i = 0; i < singularValues.length; i++) {
if (singularValues[i] > SMALL) {
sigmaI.set(i, i, 1.0 / singularValues[i]);
}
}
System.err.println("U :\n" + svd.getU());
System.err.println("Vt :\n" + svd.getVt());
System.err.println("Reciprocal of singular values :\n" + sigmaI);
Matrix pseudoInverse = svd.getU().mult(sigmaI, new DenseMatrix(m,m)).mult(svd.getVt(), new DenseMatrix(m,m));
// Compute reduced-rank version
Matrix khatr = kbM.mult(pseudoInverse, new DenseMatrix(n, m)).mult(kbM.transpose(new DenseMatrix(m, n)), new DenseMatrix(n,n));
System.err.println("Reduced rank matrix: \n" + khatr);
}
// Compute weighting matrix
if (getUseSVD()) {
SVD svd = SVD.factorize(khatM);
double[] e = svd.getS();
Matrix dhatr = new UpperSymmDenseMatrix(e.length);
for (int i = 0; i < e.length; i++) {
if (Math.sqrt(e[i]) > SMALL) {
dhatr.set(i, i, 1.0 / Math.sqrt(e[i]));
}
}
if (m_Debug) {
System.err.println("U matrix :\n" + svd.getU());
System.err.println("Vt matrix :\n" + svd.getVt());
System.err.println("Singluar values \n" + Utils.arrayToString(svd.getS()));
System.err.println("Reciprocal of square root of singular values :\n" + dhatr);
}
m_WeightingMatrix = dhatr.mult(svd.getVt(), new DenseMatrix(m,m));
} else {
SymmDenseEVD evd = SymmDenseEVD.factorize(khatM);
double[] e = evd.getEigenvalues();
Matrix dhatr = new UpperSymmDenseMatrix(e.length);
for (int i = 0; i < e.length; i++) {
if (Math.sqrt(e[i]) > SMALL) {
dhatr.set(i, i, 1.0 / Math.sqrt(e[i]));
}
}
if (m_Debug) {
System.err.println("Eigenvector matrix :\n" + evd.getEigenvectors());
System.err.println("Eigenvalues \n" + Utils.arrayToString(evd.getEigenvalues()));
System.err.println("Reciprocal of square root of eigenvalues :\n" + dhatr);
}
m_WeightingMatrix = dhatr.mult(evd.getEigenvectors().transpose(), new DenseMatrix(m,m));
}
if (m_Debug) {
System.err.println("Weighting matrix: \n" + m_WeightingMatrix);
}
// Construct header for output format
boolean hasClass = (inputFormat.classIndex() >= 0);
ArrayList<Attribute> atts = new ArrayList<Attribute>(m + ((hasClass) ? 1 : 0));
for (int i = 0; i < m; i++) {
atts.add(new Attribute("z" + (i + 1)));
}
if (hasClass) {
atts.add((Attribute) inputFormat.classAttribute().copy());
}
Instances d = new Instances(inputFormat.relationName(), atts, 0);
if (hasClass) {
d.setClassIndex(d.numAttributes() - 1);
}
return d;
}
/**
* Takes a batch of data and transforms it.
*
* @param instances the data to process
* @return the processed instances
* @throws Exception is thrown if a problem occurs
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances transformed = getOutputFormat();
boolean hasClass = (instances.classIndex() >= 0);
int m = m_Sample.numInstances();
for (Instance inst : instances) {
Vector n = new DenseVector(m);
for (int i = 0; i < m; i++) {
n.set(i, m_Kernel.eval(-1, i, inst));
}
Vector newInst = m_WeightingMatrix.mult(n, new DenseVector(m));
double[] newVals = new double[m + ((hasClass) ? 1 : 0)];
for (int i = 0; i < m; i++) {
newVals[i] = newInst.get(i);
}
if (hasClass) {
newVals[transformed.classIndex()] = inst.classValue();
}
transformed.add(new DenseInstance(inst.weight(), newVals));
}
return transformed;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 12037 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Nystroem(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Obfuscate.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Obfuscate.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A simple instance filter that renames the relation,
* all attribute names and all nominal attribute values. For
* exchanging sensitive datasets. Leaves string and relational
* attributes untouched.
* <p/>
* <!-- globalinfo-end -->
*
* @author Len Trigg (len@reeltwo.com)
* @version $Revision$
*/
public class Obfuscate extends Filter implements UnsupervisedFilter,
StreamableFilter, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -343922772462971561L;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A simple instance filter that renames the relation, all attribute names "
+ "and all nominal attribute values. For exchanging sensitive "
+ "datasets. Leaves string and relational attributes untouched.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
// Make the obfuscated header
ArrayList<Attribute> v = new ArrayList<Attribute>();
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
Attribute oldAtt = instanceInfo.attribute(i);
Attribute newAtt = null;
switch (oldAtt.type()) {
case Attribute.NUMERIC:
newAtt = new Attribute("A" + (i + 1));
break;
case Attribute.DATE:
String format = oldAtt.getDateFormat();
newAtt = new Attribute("A" + (i + 1), format);
break;
case Attribute.NOMINAL:
ArrayList<String> vals = new ArrayList<String>();
for (int j = 0; j < oldAtt.numValues(); j++) {
vals.add("V" + (j + 1));
}
newAtt = new Attribute("A" + (i + 1), vals);
break;
case Attribute.STRING:
case Attribute.RELATIONAL:
default:
newAtt = (Attribute) oldAtt.copy();
System.err.println("Not converting attribute: " + oldAtt.name());
break;
}
newAtt.setWeight(oldAtt.weight());
v.add(newAtt);
}
Instances newHeader = new Instances("R", v, 10);
newHeader.setClassIndex(instanceInfo.classIndex());
setOutputFormat(newHeader);
return true;
}
/**
* 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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
push((Instance) instance.copy(), false); // No need to copy
return true;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Obfuscate(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/OrdinalToNumeric.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* OrdinalToNumeric.java
* Copyright (C) 1999-2017 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
/**
<!-- globalinfo-start -->
* An attribute filter that converts ordinal nominal attributes into numeric ones
* <br><br>
<!-- 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> -R <range or list of names>
* Attributes to operate on. Can be a 1-based index range of indices, or a comma-separated list of names.
* (default: first-last)</pre>
*
<!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class OrdinalToNumeric extends PotentialClassIgnorer implements
StreamableFilter, UnsupervisedFilter, EnvironmentHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** For serialization */
private static final long serialVersionUID = -5199516576940135696L;
/** For resolving environment variables */
protected transient Environment m_env = Environment.getSystemWide();
/** Range of columns to consider */
protected Range m_selectedRange;
/** Textual range string */
protected String m_range = "first-last";
/** Holds the resolved range */
protected String m_resolvedRange = "";
/**
* 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 attribute filter that converts ordinal nominal attributes into "
+ "numeric ones";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capabilities.Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<>();
Enumeration<Option> e = super.listOptions();
while (e.hasMoreElements()) {
result.addElement(e.nextElement());
}
result.addElement(new Option("\tAttributes to operate on. Can "
+ "be a 1-based index range of indices, or a comma-separated list of "
+ "names.\n\t(default: first-last)", "R", 1, "-R <range or list of "
+ "names>"));
return result.elements();
}
/**
* Parses a list of options for this object.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String atts = Utils.getOption('R', options);
if (atts.length() > 0) {
setAttributesToOperateOn(atts);
}
super.setOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<>();
result.addAll(Arrays.asList(super.getOptions()));
result.add("-R");
result.add(getAttributesToOperateOn());
return result.toArray(new String[result.size()]);
}
/**
* Set the attributes to operate on
*
* @param atts a range of 1-based indexes or a comma-separated list of
* attribute names
*/
@OptionMetadata(displayName = "Attributes to operate on",
description = "Attributes to operate on. Can be a 1-based index range of "
+ "indices or a comma-separated list of names",
commandLineParamName = "R",
commandLineParamSynopsis = "-R <range or list of names>", displayOrder = 1)
public void setAttributesToOperateOn(String atts) {
m_range = atts;
}
/**
* Get the attributes to operate on
*
* @return a range of 1-based indexes or a comma-separated list of attribute
* names
*/
public String getAttributesToOperateOn() {
return m_range;
}
/**
* Sets the format of the input instances.
*
* @param instancesInfo 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
*/
@Override
public boolean setInputFormat(Instances instancesInfo) throws Exception {
super.setInputFormat(instancesInfo);
m_resolvedRange = m_range;
if (m_env == null) {
m_env = Environment.getSystemWide();
}
if (m_resolvedRange != null && m_resolvedRange.length() > 0) {
m_resolvedRange = m_env.substitute(m_resolvedRange);
} else {
throw new Exception("No attributes to operate on defined");
}
m_selectedRange =
Utils.configureRangeFromRangeStringOrAttributeNameList(instancesInfo,
m_resolvedRange);
int[] selectedIndexes = m_selectedRange.getSelection();
Instances outputFormat = new Instances(instancesInfo, 0);
if (selectedIndexes.length > 0) {
ArrayList<Attribute> atts = new ArrayList<>();
for (int i = 0; i < instancesInfo.numAttributes(); i++) {
if (m_selectedRange.isInRange(i)
&& instancesInfo.attribute(i).isNominal()
&& i != instancesInfo.classIndex()) {
Attribute att = new Attribute(instancesInfo.attribute(i).name());
att.setWeight(instancesInfo.attribute(i).weight());
atts.add(att);
} else {
atts.add(instancesInfo.attribute(i)); // Copy not necessary
}
}
outputFormat = new Instances(instancesInfo.relationName(), atts, 0);
outputFormat.setClassIndex(instancesInfo.classIndex());
}
setOutputFormat(outputFormat);
return true;
}
/**
* 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 inst the input instance
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input format has been defined.
*/
@Override
public boolean input(Instance inst) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
push(inst);
return true;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: $");
}
/**
* Set environment to use
*
* @param env the environment variables to
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new OrdinalToNumeric(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/PKIDiscretize.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* PKIDiscretize.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
/**
* <!-- globalinfo-start --> Discretizes numeric attributes using equal
* frequency binning and forces the number of bins to be equal to the square root of
* the number of values of the numeric attribute.<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Ying Yang, Geoffrey I. Webb: Proportional k-Interval Discretization for
* Naive-Bayes Classifiers. In: 12th European Conference on Machine Learning,
* 564-575, 2001.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @inproceedings{Yang2001,
* author = {Ying Yang and Geoffrey I. Webb},
* booktitle = {12th European Conference on Machine Learning},
* pages = {564-575},
* publisher = {Springer},
* series = {LNCS},
* title = {Proportional k-Interval Discretization for Naive-Bayes Classifiers},
* volume = {2167},
* year = {2001}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-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>
* -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 Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class PKIDiscretize extends Discretize implements TechnicalInformationHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 6153101248977702675L;
/**
* 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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
// alter child behaviour to do what we want
this.m_FindNumBins = true;
return super.setInputFormat(instanceInfo);
}
/**
* Finds the number of bins to use and creates the cut points.
*
* @param index the attribute index
* @throws InterruptedException
*/
@Override
protected void findNumBins(final int index) throws InterruptedException {
Instances toFilter = this.getInputFormat();
// Find number of instances for attribute where not missing
double sum = 0;
for (Instance inst : toFilter) {
if (!inst.isMissing(index)) {
sum += inst.weight();
}
}
this.m_NumBins = (int) Math.sqrt(sum);
if (this.m_NumBins > 0) {
this.calculateCutPointsByEqualFrequencyBinning(index);
}
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tUnsets the class index temporarily before the filter is\n" + "\tapplied to the data.\n" + "\t(default: no)", "unset-class-temporarily", 1, "-unset-class-temporarily"));
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>
* -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
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setIgnoreClass(Utils.getFlag("unset-class-temporarily", options));
this.setMakeBinary(Utils.getFlag('D', options));
this.setInvertSelection(Utils.getFlag('V', options));
String convertList = Utils.getOption('R', options);
if (convertList.length() != 0) {
this.setAttributeIndices(convertList);
} else {
this.setAttributeIndices("first-last");
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (this.getMakeBinary()) {
result.add("-D");
}
if (this.getInvertSelection()) {
result.add("-V");
}
if (!this.getAttributeIndices().equals("")) {
result.add("-R");
result.add(this.getAttributeIndices());
}
return result.toArray(new String[result.size()]);
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Discretizes numeric attributes using equal" + " frequency binning and forces the number of bins to be equal to the square root of" + " the number of values of the numeric attribute.\n\n" + "For more information, see:\n\n"
+ this.getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Ying Yang and Geoffrey I. Webb");
result.setValue(Field.TITLE, "Proportional k-Interval Discretization for Naive-Bayes Classifiers");
result.setValue(Field.BOOKTITLE, "12th European Conference on Machine Learning");
result.setValue(Field.YEAR, "2001");
result.setValue(Field.PAGES, "564-575");
result.setValue(Field.PUBLISHER, "Springer");
result.setValue(Field.SERIES, "LNCS");
result.setValue(Field.VOLUME, "2167");
return result;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String findNumBinsTipText() {
return "Ignored.";
}
/**
* Get the value of FindNumBins.
*
* @return Value of FindNumBins.
*/
@Override
public boolean getFindNumBins() {
return false;
}
/**
* Set the value of FindNumBins.
*
* @param newFindNumBins Value to assign to FindNumBins.
*/
@Override
public void setFindNumBins(final boolean newFindNumBins) {
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String useEqualFrequencyTipText() {
return "Always true.";
}
/**
* Get the value of UseEqualFrequency.
*
* @return Value of UseEqualFrequency.
*/
@Override
public boolean getUseEqualFrequency() {
return true;
}
/**
* Set the value of UseEqualFrequency.
*
* @param newUseEqualFrequency Value to assign to UseEqualFrequency.
*/
@Override
public void setUseEqualFrequency(final boolean newUseEqualFrequency) {
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String binsTipText() {
return "Ignored.";
}
/**
* Ignored
*
* @return the number of bins.
*/
@Override
public int getBins() {
return 0;
}
/**
* Ignored
*
* @param numBins the number of bins
*/
@Override
public void setBins(final int numBins) {
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new PKIDiscretize(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/PartitionedMultiFilter.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* PartitionedMultiFilter.java
* Copyright (C) 2006-2016 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.filters.AllFilter;
import weka.filters.Filter;
import weka.filters.SimpleBatchFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
/**
* <!-- globalinfo-start --> A filter that applies filters on subsets of
* attributes and assembles the output into a new dataset. Attributes that are
* not covered by any of the ranges can be either retained or removed from the
* output.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -F <classname [options]>
* A filter to apply (can be specified multiple times).
* </pre>
*
* <pre>
* -R <range>
* An attribute range (can be specified multiple times).
* For each filter a range must be supplied. 'first' and 'last'
* are valid indices. 'inv(...)' around the range denotes an
* inverted range.
* </pre>
*
* <pre>
* -U
* Flag for leaving unused attributes out of the output, by default
* these are included in the filter output.
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see weka.filters.StreamableFilter
*/
public class PartitionedMultiFilter extends SimpleBatchFilter
implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
private static final long serialVersionUID = -6293720886005713120L;
/** The filters. */
protected Filter m_Filters[] = { new AllFilter() };
/** The attribute ranges. */
protected Range m_Ranges[] = { new Range("first-last") };
/** Whether unused attributes are left out of the output. */
protected boolean m_RemoveUnused = false;
/** the indices of the unused attributes. */
protected int[] m_IndicesUnused = new int[0];
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter that applies filters on subsets of attributes and "
+ "assembles the output into a new dataset. Attributes that are "
+ "not covered by any of the ranges can be either retained or removed "
+ "from the output.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tA filter to apply (can be specified multiple times).", "F", 1,
"-F <classname [options]>"));
result.addElement(new Option(
"\tAn attribute range (can be specified multiple times).\n"
+ "\tFor each filter a range must be supplied. 'first' and 'last'\n"
+ "\tare valid indices. 'inv(...)' around the range denotes an\n"
+ "\tinverted range.", "R", 1, "-R <range>"));
result.addElement(new Option(
"\tFlag for leaving unused attributes out of the output, by default\n"
+ "\tthese are included in the filter output.", "U", 0, "-U"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -F <classname [options]>
* A filter to apply (can be specified multiple times).
* </pre>
*
* <pre>
* -R <range>
* An attribute range (can be specified multiple times).
* For each filter a range must be supplied. 'first' and 'last'
* are valid indices. 'inv(...)' around the range denotes an
* inverted range.
* </pre>
*
* <pre>
* -U
* Flag for leaving unused attributes out of the output, by default
* these are included in the filter output.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
String classname;
String[] options2;
Vector<Object> objects;
Range range;
setRemoveUnused(Utils.getFlag("U", options));
objects = new Vector<Object>();
while ((tmpStr = Utils.getOption("F", options)).length() != 0) {
options2 = Utils.splitOptions(tmpStr);
classname = options2[0];
options2[0] = "";
objects.add(Utils.forName(Filter.class, classname, options2));
}
// at least one filter
if (objects.size() == 0) {
objects.add(new AllFilter());
}
setFilters(objects.toArray(new Filter[objects.size()]));
objects = new Vector<Object>();
while ((tmpStr = Utils.getOption("R", options)).length() != 0) {
if (tmpStr.startsWith("inv(") && tmpStr.endsWith(")")) {
range = new Range(tmpStr.substring(4, tmpStr.length() - 1));
range.setInvert(true);
} else {
range = new Range(tmpStr);
}
objects.add(range);
}
// at least one Range
if (objects.size() == 0) {
objects.add(new Range("first-last"));
}
setRanges(objects.toArray(new Range[objects.size()]));
// is number of filters the same as ranges?
checkDimensions();
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getRemoveUnused()) {
result.add("-U");
}
for (int i = 0; i < getFilters().length; i++) {
result.add("-F");
result.add(getFilterSpec(getFilter(i)));
}
for (int i = 0; i < getRanges().length; i++) {
String tmpStr = getRange(i).getRanges();
if (getRange(i).getInvert()) {
tmpStr = "inv(" + tmpStr + ")";
}
result.add("-R");
result.add(tmpStr);
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* checks whether the dimensions of filters and ranges fit together.
*
* @throws Exception if dimensions differ
*/
protected void checkDimensions() throws Exception {
if (getFilters().length != getRanges().length) {
throw new IllegalArgumentException("Number of filters (= "
+ getFilters().length + ") " + "and ranges (= " + getRanges().length
+ ") don't match!");
}
}
/**
* tests the data whether the filter can actually handle it.
*
* @param instanceInfo the data to test
* @throws Exception if the test fails
*/
@Override
protected void testInputFormat(Instances instanceInfo) throws Exception {
for (int i = 0; i < getRanges().length; i++) {
Instances newi = new Instances(instanceInfo, 0);
if (instanceInfo.size() > 0) {
newi.add((Instance) instanceInfo.get(0).copy());
}
Range range = getRanges()[i];
range.setUpper(instanceInfo.numAttributes() - 1);
Instances subset = generateSubset(newi, range);
getFilters()[i].setInputFormat(subset);
}
}
/**
* Sets whether unused attributes (ones that are not covered by any of the
* ranges) are removed from the output.
*
* @param value if true then the unused attributes get removed
*/
public void setRemoveUnused(boolean value) {
m_RemoveUnused = value;
}
/**
* Gets whether unused attributes (ones that are not covered by any of the
* ranges) are removed from the output.
*
* @return true if unused attributes are removed
*/
public boolean getRemoveUnused() {
return m_RemoveUnused;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String removeUnusedTipText() {
return "If true then unused attributes (ones that are not covered by any "
+ "of the ranges) will be removed from the output.";
}
/**
* Sets the list of possible filters to choose from. Also resets the state of
* the filter (this reset doesn't affect the options).
*
* @param filters an array of filters with all options set.
* @see #reset()
*/
public void setFilters(Filter[] filters) {
m_Filters = filters;
reset();
}
/**
* Gets the list of possible filters to choose from.
*
* @return the array of Filters
*/
public Filter[] getFilters() {
return m_Filters;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String filtersTipText() {
return "The base filters to be used.";
}
/**
* Gets a single filter from the set of available filters.
*
* @param index the index of the filter wanted
* @return the Filter
*/
public Filter getFilter(int index) {
return m_Filters[index];
}
/**
* returns the filter classname and the options as one string.
*
* @param filter the filter to get the specs for
* @return the classname plus options
*/
protected String getFilterSpec(Filter filter) {
String result;
if (filter == null) {
result = "";
} else {
result = filter.getClass().getName();
if (filter instanceof OptionHandler) {
result += " "
+ Utils.joinOptions(((OptionHandler) filter).getOptions());
}
}
return result;
}
/**
* Sets the list of possible Ranges to choose from. Also resets the state of
* the Range (this reset doesn't affect the options).
*
* @param Ranges an array of Ranges with all options set.
* @see #reset()
*/
public void setRanges(Range[] Ranges) {
m_Ranges = Ranges;
reset();
}
/**
* Gets the list of possible Ranges to choose from.
*
* @return the array of Ranges
*/
public Range[] getRanges() {
return m_Ranges;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String rangesTipText() {
return "The attribute ranges to be used; 'inv(...)' denotes an inverted range.";
}
/**
* Gets a single Range from the set of available Ranges.
*
* @param index the index of the Range wanted
* @return the Range
*/
public Range getRange(int index) {
return m_Ranges[index];
}
/**
* determines the indices of unused attributes (ones that are not covered by
* any of the range).
*
* @param data the data to base the determination on
* @see #m_IndicesUnused
*/
protected void determineUnusedIndices(Instances data) {
Vector<Integer> indices;
int i;
int n;
boolean covered;
// traverse all ranges
indices = new Vector<Integer>();
for (i = 0; i < data.numAttributes(); i++) {
if (i == data.classIndex()) {
continue;
}
covered = false;
for (n = 0; n < getRanges().length; n++) {
if (getRanges()[n].isInRange(i)) {
covered = true;
break;
}
}
if (!covered) {
indices.add(new Integer(i));
}
}
// create array
m_IndicesUnused = new int[indices.size()];
for (i = 0; i < indices.size(); i++) {
m_IndicesUnused[i] = indices.get(i).intValue();
}
if (getDebug()) {
System.out.println("Unused indices: "
+ Utils.arrayToString(m_IndicesUnused));
}
}
/**
* generates a subset of the dataset with only the attributes from the range
* (class is always added if present).
*
* @param data the data to work on
* @param range the range of attribute to use
* @return the generated subset
* @throws Exception if creation fails
*/
protected Instances generateSubset(Instances data, Range range)
throws Exception {
Remove filter;
StringBuilder atts;
Instances result;
int[] indices;
int i;
// determine attributes
indices = range.getSelection();
atts = new StringBuilder();
for (i = 0; i < indices.length; i++) {
if (i > 0) {
atts.append(",");
}
atts.append("" + (indices[i] + 1));
}
if ((data.classIndex() > -1) && (!range.isInRange(data.classIndex()))) {
atts.append("," + (data.classIndex() + 1));
}
// setup filter
filter = new Remove();
filter.setAttributeIndices(atts.toString());
filter.setInvertSelection(true);
filter.setInputFormat(data);
// generate output
result = Filter.useFilter(data, filter);
return result;
}
/**
* renames all the attributes in the dataset (excluding the class if present)
* by adding the prefix to the name.
*
* @param data the data to work on
* @param prefix the prefix for the attributes
* @return a copy of the data with the attributes renamed
* @throws Exception if renaming fails
*/
protected Instances renameAttributes(Instances data, String prefix)
throws Exception {
Instances result;
int i;
ArrayList<Attribute> atts;
// rename attributes
atts = new ArrayList<Attribute>();
for (i = 0; i < data.numAttributes(); i++) {
if (i == data.classIndex()) {
atts.add((Attribute) data.attribute(i).copy());
} else {
atts.add(data.attribute(i).copy(prefix + data.attribute(i).name()));
}
}
// create new dataset
result = new Instances(data.relationName(), atts, data.numInstances());
for (i = 0; i < data.numInstances(); i++) {
result.add((Instance) data.instance(i).copy());
}
// set class if present
if (data.classIndex() > -1) {
result.setClassIndex(data.classIndex());
}
return result;
}
/**
* Determines the output format based only on the full input dataset and
* returns this otherwise null is returned. In case the output format cannot
* be returned immediately, i.e., immediateOutputFormat() returns false, then
* this method will be called from batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
Instances processed;
int i;
int n;
ArrayList<Attribute> atts;
Attribute att;
if (!isFirstBatchDone()) {
// we need the full dataset here, see process(Instances)
if (inputFormat.numInstances() == 0) {
return null;
}
checkDimensions();
// determine unused indices
determineUnusedIndices(inputFormat);
atts = new ArrayList<Attribute>();
for (i = 0; i < getFilters().length; i++) {
if (!isFirstBatchDone()) {
// generate subset
processed = generateSubset(inputFormat, getRange(i));
// set input format
if (!getFilter(i).setInputFormat(processed)) {
Filter.useFilter(processed, getFilter(i));
}
}
// get output format
processed = getFilter(i).getOutputFormat();
// rename attributes
processed = renameAttributes(processed, "filtered-" + i + "-");
// add attributes
for (n = 0; n < processed.numAttributes(); n++) {
if (n == processed.classIndex()) {
continue;
}
atts.add((Attribute) processed.attribute(n).copy());
}
}
// add unused attributes
if (!getRemoveUnused()) {
for (i = 0; i < m_IndicesUnused.length; i++) {
att = inputFormat.attribute(m_IndicesUnused[i]);
atts.add(att.copy("unfiltered-" + att.name()));
}
}
// add class if present
if (inputFormat.classIndex() > -1) {
atts.add((Attribute) inputFormat.classAttribute().copy());
}
// generate new dataset
result = new Instances(inputFormat.relationName(), atts, 0);
if (inputFormat.classIndex() > -1) {
result.setClassIndex(result.numAttributes() - 1);
}
} else {
result = getOutputFormat();
}
return result;
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
Instances result;
int i;
int n;
int m;
int index;
Instances[] processed;
Instance inst;
Instance newInst;
double[] values;
Vector<Integer> errors;
if (!isFirstBatchDone()) {
checkDimensions();
// set upper limits
for (i = 0; i < m_Ranges.length; i++) {
m_Ranges[i].setUpper(instances.numAttributes() - 1);
}
// determine unused indices
determineUnusedIndices(instances);
}
// pass data through all filters
processed = new Instances[getFilters().length];
for (i = 0; i < getFilters().length; i++) {
processed[i] = generateSubset(instances, getRange(i));
if (!isFirstBatchDone()) {
getFilter(i).setInputFormat(processed[i]);
}
processed[i] = Filter.useFilter(processed[i], getFilter(i));
}
// set output format (can only be determined with full dataset, hence here)
if (!isFirstBatchDone()) {
result = determineOutputFormat(instances);
setOutputFormat(result);
} else {
result = getOutputFormat();
}
// check whether all filters didn't change the number of instances
errors = new Vector<Integer>();
for (i = 0; i < processed.length; i++) {
if (processed[i].numInstances() != instances.numInstances()) {
errors.add(new Integer(i));
}
}
if (errors.size() > 0) {
throw new IllegalStateException(
"The following filter(s) changed the number of instances: " + errors);
}
// assemble data
for (i = 0; i < instances.numInstances(); i++) {
inst = instances.instance(i);
values = new double[result.numAttributes()];
// filtered data
index = 0;
for (n = 0; n < processed.length; n++) {
for (m = 0; m < processed[n].numAttributes(); m++) {
if (m == processed[n].classIndex()) {
continue;
}
if (processed[n].instance(i).isMissing(m)) {
values[index] = Utils.missingValue();
} else if (result.attribute(index).isString()) {
values[index] = result.attribute(index).addStringValue(
processed[n].instance(i).stringValue(m));
} else if (result.attribute(index).isRelationValued()) {
values[index] = result.attribute(index).addRelation(
processed[n].instance(i).relationalValue(m));
} else {
values[index] = processed[n].instance(i).value(m);
}
index++;
}
}
// unused attributes
if (!getRemoveUnused()) {
for (n = 0; n < m_IndicesUnused.length; n++) {
if (inst.isMissing(m_IndicesUnused[n])) {
values[index] = Utils.missingValue();
} else if (result.attribute(index).isString()) {
values[index] = result.attribute(index).addStringValue(
inst.stringValue(m_IndicesUnused[n]));
} else if (result.attribute(index).isRelationValued()) {
values[index] = result.attribute(index).addRelation(
inst.relationalValue(m_IndicesUnused[n]));
} else {
values[index] = inst.value(m_IndicesUnused[n]);
}
index++;
}
}
// class
if (instances.classIndex() > -1) {
index = values.length - 1;
if (inst.classIsMissing())
values[index] = Utils.missingValue();
else if (result.attribute(index).isString())
values[index] = result.attribute(index).addStringValue(inst.stringValue(instances.classIndex()));
else if (result.attribute(index).isRelationValued())
values[index] = result.attribute(index).addRelation(inst.relationalValue(instances.classIndex()));
else
values[index] = inst.value(instances.classIndex());
}
// generate and add instance
if (inst instanceof SparseInstance) {
newInst = new SparseInstance(instances.instance(i).weight(), values);
} else {
newInst = new DenseInstance(instances.instance(i).weight(), values);
}
result.add(newInst);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for executing this class.
*
* @param args should contain arguments for the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new PartitionedMultiFilter(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/PotentialClassIgnorer.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* PotentialClassIgnorer.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Utils;
import weka.filters.Filter;
/**
* This filter should be extended by other unsupervised attribute filters to
* allow processing of the class attribute if that's required. It the class is
* to be ignored it is essential that the extending filter does not change the
* position (i.e. index) of the attribute that is originally the class attribute
* !
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz), Mark Hall
* (mhall@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class PotentialClassIgnorer extends Filter implements
OptionHandler {
/** for serialization */
private static final long serialVersionUID = 8625371119276845454L;
/** True if the class is to be unset */
protected boolean m_IgnoreClass = false;
/** Storing the class index */
protected int m_ClassIndex = -1;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tUnsets the class index temporarily before the filter is\n"
+ "\tapplied to the data.\n" + "\t(default: no)",
"unset-class-temporarily", 1, "-unset-class-temporarily"));
return result.elements();
}
/**
* Parses a list of options for this object.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setIgnoreClass(Utils.getFlag("unset-class-temporarily", options));
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getIgnoreClass()) {
result.add("-unset-class-temporarily");
}
return result.toArray(new String[result.size()]);
}
/**
* Sets the format of the input instances. If the filter is able to determine
* the output format before seeing any input instances, it does so here. This
* default implementation clears the output format and output queue, and the
* new batch flag is set. Overriders should call
* <code>super.setInputFormat(Instances)</code>
*
* @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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
boolean result = super.setInputFormat(instanceInfo);
if (m_IgnoreClass) {
m_ClassIndex = inputFormatPeek().classIndex();
inputFormatPeek().setClassIndex(-1);
}
return result;
}
/**
* Gets the format of the output instances. This should only be called after
* input() or batchFinished() has returned true. The relation name of the
* output instances should be changed to reflect the action of the filter (eg:
* add the filter name and options).
*
* @return an Instances object containing the output instance structure only.
* @throws NullPointerException if no input structure has been defined (or the
* output format hasn't been determined yet)
*/
@Override
public Instances getOutputFormat() {
if (m_IgnoreClass) {
outputFormatPeek().setClassIndex(m_ClassIndex);
}
return super.getOutputFormat();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoreClassTipText() {
return "The class index will be unset temporarily before the filter is applied.";
}
/**
* Set the IgnoreClass value. Set this to true if the class index is to be
* unset before the filter is applied.
*
* @param newIgnoreClass The new IgnoreClass value.
*/
public void setIgnoreClass(boolean newIgnoreClass) {
m_IgnoreClass = newIgnoreClass;
}
/**
* Gets the IgnoreClass value. If this to true then the class index is to
* unset before the filter is applied.
*
* @return the current IgnoreClass value.
*/
public boolean getIgnoreClass() {
return m_IgnoreClass;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/PrincipalComponents.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* PrincipalComponents.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import no.uib.cipr.matrix.*;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Performs a principal components analysis and
* transformation of the data.<br/>
* Dimensionality reduction is accomplished by choosing enough eigenvectors to
* account for some percentage of the variance in the original data -- default
* 0.95 (95%).<br/>
* Based on code of the attribute selection scheme 'PrincipalComponents' by Mark
* Hall and Gabi Schmidberger.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C
* Center (rather than standardize) the
* data and compute PCA using the covariance (rather
* than the correlation) matrix.
* </pre>
*
* <pre>
* -R <num>
* Retain enough PC attributes to account
* for this proportion of variance in the original data.
* (default: 0.95)
* </pre>
*
* <pre>
* -A <num>
* Maximum number of attributes to include in
* transformed attribute names.
* (-1 = include all, default: 5)
* </pre>
*
* <pre>
* -M <num>
* Maximum number of PC attributes to retain.
* (-1 = include all, default: -1)
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz) -- attribute selection code
* @author Gabi Schmidberger (gabi@cs.waikato.ac.nz) -- attribute selection code
* @author fracpete (fracpete at waikato dot ac dot nz) -- filter code
* @version $Revision$
*/
public class PrincipalComponents extends Filter implements OptionHandler,
UnsupervisedFilter {
/** for serialization. */
private static final long serialVersionUID = -5649876869480249303L;
/** The data to transform analyse/transform. */
protected Instances m_TrainInstances;
/** Keep a copy for the class attribute (if set). */
protected Instances m_TrainCopy;
/** The header for the transformed data format. */
protected Instances m_TransformedFormat;
/** Data has a class set. */
protected boolean m_HasClass;
/** Class index. */
protected int m_ClassIndex;
/** Number of attributes. */
protected int m_NumAttribs;
/** Number of instances. */
protected int m_NumInstances;
/** Correlation matrix for the original data. */
protected UpperSymmDenseMatrix m_Correlation;
/**
* If true, center (rather than standardize) the data and compute PCA from
* covariance (rather than correlation) matrix.
*/
private boolean m_center = false;
/**
* Will hold the unordered linear transformations of the (normalized) original
* data.
*/
protected double[][] m_Eigenvectors;
/** Eigenvalues for the corresponding eigenvectors. */
protected double[] m_Eigenvalues = null;
/** Sorted eigenvalues. */
protected int[] m_SortedEigens;
/** sum of the eigenvalues. */
protected double m_SumOfEigenValues = 0.0;
/** Filters for replacing missing values. */
protected ReplaceMissingValues m_ReplaceMissingFilter;
/** Filter for turning nominal values into numeric ones. */
protected NominalToBinary m_NominalToBinaryFilter;
/** Filter for removing class attribute, nominal attributes with 0 or 1 value. */
protected Remove m_AttributeFilter;
/** Filter for standardizing the data */
protected Standardize m_standardizeFilter;
/** Filter for centering the data */
protected Center m_centerFilter;
/** The number of attributes in the pc transformed data. */
protected int m_OutputNumAtts = -1;
/**
* the amount of varaince to cover in the original data when retaining the
* best n PC's.
*/
protected double m_CoverVariance = 0.95;
/** maximum number of attributes in the transformed attribute name. */
protected int m_MaxAttrsInName = 5;
/** maximum number of attributes in the transformed data (-1 for all). */
protected int m_MaxAttributes = -1;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Performs a principal components analysis and transformation of "
+ "the data.\n"
+ "Dimensionality reduction is accomplished by choosing enough eigenvectors "
+ "to account for some percentage of the variance in the original data -- "
+ "default 0.95 (95%).\n"
+ "Based on code of the attribute selection scheme 'PrincipalComponents' "
+ "by Mark Hall and Gabi Schmidberger.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tCenter (rather than standardize) the"
+ "\n\tdata and compute PCA using the covariance (rather"
+ "\n\t than the correlation) matrix.", "C", 0, "-C"));
result.addElement(new Option("\tRetain enough PC attributes to account\n"
+ "\tfor this proportion of variance in the original data.\n"
+ "\t(default: 0.95)", "R", 1, "-R <num>"));
result.addElement(new Option(
"\tMaximum number of attributes to include in \n"
+ "\ttransformed attribute names.\n"
+ "\t(-1 = include all, default: 5)", "A", 1, "-A <num>"));
result.addElement(new Option(
"\tMaximum number of PC attributes to retain.\n"
+ "\t(-1 = include all, default: -1)", "M", 1, "-M <num>"));
return result.elements();
}
/**
* Parses a list of options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C
* Center (rather than standardize) the
* data and compute PCA using the covariance (rather
* than the correlation) matrix.
* </pre>
*
* <pre>
* -R <num>
* Retain enough PC attributes to account
* for this proportion of variance in the original data.
* (default: 0.95)
* </pre>
*
* <pre>
* -A <num>
* Maximum number of attributes to include in
* transformed attribute names.
* (-1 = include all, default: 5)
* </pre>
*
* <pre>
* -M <num>
* Maximum number of PC attributes to retain.
* (-1 = include all, default: -1)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setVarianceCovered(Double.parseDouble(tmpStr));
} else {
setVarianceCovered(0.95);
}
tmpStr = Utils.getOption('A', options);
if (tmpStr.length() != 0) {
setMaximumAttributeNames(Integer.parseInt(tmpStr));
} else {
setMaximumAttributeNames(5);
}
tmpStr = Utils.getOption('M', options);
if (tmpStr.length() != 0) {
setMaximumAttributes(Integer.parseInt(tmpStr));
} else {
setMaximumAttributes(-1);
}
setCenterData(Utils.getFlag('C', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
result.add("" + getVarianceCovered());
result.add("-A");
result.add("" + getMaximumAttributeNames());
result.add("-M");
result.add("" + getMaximumAttributes());
if (getCenterData()) {
result.add("-C");
}
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String centerDataTipText() {
return "Center (rather than standardize) the data. PCA will "
+ "be computed from the covariance (rather than correlation) " + "matrix";
}
/**
* Set whether to center (rather than standardize) the data. If set to true
* then PCA is computed from the covariance rather than correlation matrix.
*
* @param center true if the data is to be centered rather than standardized
*/
public void setCenterData(boolean center) {
m_center = center;
}
/**
* Get whether to center (rather than standardize) the data. If true then PCA
* is computed from the covariance rather than correlation matrix.
*
* @return true if the data is to be centered rather than standardized.
*/
public boolean getCenterData() {
return m_center;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String varianceCoveredTipText() {
return "Retain enough PC attributes to account for this proportion of variance.";
}
/**
* Sets the amount of variance to account for when retaining principal
* components.
*
* @param value the proportion of total variance to account for
*/
public void setVarianceCovered(double value) {
m_CoverVariance = value;
}
/**
* Gets the proportion of total variance to account for when retaining
* principal components.
*
* @return the proportion of variance to account for
*/
public double getVarianceCovered() {
return m_CoverVariance;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maximumAttributeNamesTipText() {
return "The maximum number of attributes to include in transformed attribute names.";
}
/**
* Sets maximum number of attributes to include in transformed attribute
* names.
*
* @param value the maximum number of attributes
*/
public void setMaximumAttributeNames(int value) {
m_MaxAttrsInName = value;
}
/**
* Gets maximum number of attributes to include in transformed attribute
* names.
*
* @return the maximum number of attributes
*/
public int getMaximumAttributeNames() {
return m_MaxAttrsInName;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maximumAttributesTipText() {
return "The maximum number of PC attributes to retain.";
}
/**
* Sets maximum number of PC attributes to retain.
*
* @param value the maximum number of attributes
*/
public void setMaximumAttributes(int value) {
m_MaxAttributes = value;
}
/**
* Gets maximum number of PC attributes to retain.
*
* @return the maximum number of attributes
*/
public int getMaximumAttributes() {
return m_MaxAttributes;
}
/**
* Returns the capabilities of this evaluator.
*
* @return the capabilities of this evaluator
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.UNARY_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #batchFinished()
*/
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
double cumulative;
ArrayList<Attribute> attributes;
int i;
int j;
StringBuffer attName;
double[] coeff_mags;
int num_attrs;
int[] coeff_inds;
double coeff_value;
int numAttsLowerBound;
if (m_Eigenvalues == null) {
return inputFormat;
}
if (m_MaxAttributes > 0) {
numAttsLowerBound = m_NumAttribs - m_MaxAttributes;
} else {
numAttsLowerBound = 0;
}
if (numAttsLowerBound < 0) {
numAttsLowerBound = 0;
}
cumulative = 0.0;
attributes = new ArrayList<Attribute>();
for (i = m_NumAttribs - 1; i >= numAttsLowerBound; i--) {
attName = new StringBuffer();
// build array of coefficients
coeff_mags = new double[m_NumAttribs];
for (j = 0; j < m_NumAttribs; j++) {
coeff_mags[j] = -Math.abs(m_Eigenvectors[j][m_SortedEigens[i]]);
}
num_attrs = (m_MaxAttrsInName > 0) ? Math.min(m_NumAttribs,
m_MaxAttrsInName) : m_NumAttribs;
// this array contains the sorted indices of the coefficients
if (m_NumAttribs > 0) {
// if m_maxAttrsInName > 0, sort coefficients by decreasing magnitude
coeff_inds = Utils.sort(coeff_mags);
} else {
// if m_maxAttrsInName <= 0, use all coeffs in original order
coeff_inds = new int[m_NumAttribs];
for (j = 0; j < m_NumAttribs; j++) {
coeff_inds[j] = j;
}
}
// build final attName string
for (j = 0; j < num_attrs; j++) {
coeff_value = m_Eigenvectors[coeff_inds[j]][m_SortedEigens[i]];
if (j > 0 && coeff_value >= 0) {
attName.append("+");
}
attName.append(Utils.doubleToString(coeff_value, 5, 3)
+ inputFormat.attribute(coeff_inds[j]).name());
}
if (num_attrs < m_NumAttribs) {
attName.append("...");
}
attributes.add(new Attribute(attName.toString()));
cumulative += m_Eigenvalues[m_SortedEigens[i]];
if ((cumulative / m_SumOfEigenValues) >= m_CoverVariance) {
break;
}
}
if (m_HasClass) {
attributes.add((Attribute) m_TrainCopy.classAttribute().copy());
}
Instances outputFormat = new Instances(m_TrainCopy.relationName()
+ "_principal components", attributes, 0);
// set the class to be the last attribute if necessary
if (m_HasClass) {
outputFormat.setClassIndex(outputFormat.numAttributes() - 1);
}
m_OutputNumAtts = outputFormat.numAttributes();
return outputFormat;
}
protected void fillCovariance() throws Exception {
// just center the data or standardize it?
if (m_center) {
m_centerFilter = new Center();
m_centerFilter.setInputFormat(m_TrainInstances);
m_TrainInstances = Filter.useFilter(m_TrainInstances, m_centerFilter);
} else {
m_standardizeFilter = new Standardize();
m_standardizeFilter.setInputFormat(m_TrainInstances);
m_TrainInstances = Filter.useFilter(m_TrainInstances, m_standardizeFilter);
}
// now compute the covariance matrix
m_Correlation = new UpperSymmDenseMatrix(m_NumAttribs);
for (int i = 0; i < m_NumAttribs; i++) {
for (int j = i; j < m_NumAttribs; j++) {
double cov = 0;
for (Instance inst: m_TrainInstances) {
cov += inst.value(i) * inst.value(j);
}
cov /= m_TrainInstances.numInstances() - 1;
m_Correlation.set(i, j, cov);
}
}
}
/**
* Transform an instance in original (unormalized) format.
*
* @param instance an instance in the original (unormalized) format
* @return a transformed instance
* @throws Exception if instance can't be transformed
*/
protected Instance convertInstance(Instance instance) throws Exception {
Instance result;
double[] newVals;
Instance tempInst;
double cumulative;
int i;
int j;
double tempval;
int numAttsLowerBound;
newVals = new double[m_OutputNumAtts];
tempInst = (Instance) instance.copy();
m_ReplaceMissingFilter.input(tempInst);
m_ReplaceMissingFilter.batchFinished();
tempInst = m_ReplaceMissingFilter.output();
m_NominalToBinaryFilter.input(tempInst);
m_NominalToBinaryFilter.batchFinished();
tempInst = m_NominalToBinaryFilter.output();
if (m_AttributeFilter != null) {
m_AttributeFilter.input(tempInst);
m_AttributeFilter.batchFinished();
tempInst = m_AttributeFilter.output();
}
if (!m_center) {
m_standardizeFilter.input(tempInst);
m_standardizeFilter.batchFinished();
tempInst = m_standardizeFilter.output();
} else {
m_centerFilter.input(tempInst);
m_centerFilter.batchFinished();
tempInst = m_centerFilter.output();
}
if (m_HasClass) {
newVals[m_OutputNumAtts - 1] = instance.value(instance.classIndex());
}
if (m_MaxAttributes > 0) {
numAttsLowerBound = m_NumAttribs - m_MaxAttributes;
} else {
numAttsLowerBound = 0;
}
if (numAttsLowerBound < 0) {
numAttsLowerBound = 0;
}
cumulative = 0;
for (i = m_NumAttribs - 1; i >= numAttsLowerBound; i--) {
tempval = 0.0;
for (j = 0; j < m_NumAttribs; j++) {
tempval += m_Eigenvectors[j][m_SortedEigens[i]] * tempInst.value(j);
}
newVals[m_NumAttribs - i - 1] = tempval;
cumulative += m_Eigenvalues[m_SortedEigens[i]];
if ((cumulative / m_SumOfEigenValues) >= m_CoverVariance) {
break;
}
}
// create instance
if (instance instanceof SparseInstance) {
result = new SparseInstance(instance.weight(), newVals);
} else {
result = new DenseInstance(instance.weight(), newVals);
}
return result;
}
/**
* Initializes the filter with the given input data.
*
* @param instances the data to process
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
protected void setup(Instances instances) throws Exception {
int i;
int j;
Vector<Integer> deleteCols;
int[] todelete;
double[][] v;
m_TrainInstances = new Instances(instances);
// make a copy of the training data so that we can get the class
// column to append to the transformed data (if necessary)
m_TrainCopy = new Instances(m_TrainInstances, 0);
m_ReplaceMissingFilter = new ReplaceMissingValues();
m_ReplaceMissingFilter.setInputFormat(m_TrainInstances);
m_TrainInstances = Filter.useFilter(m_TrainInstances,
m_ReplaceMissingFilter);
m_NominalToBinaryFilter = new NominalToBinary();
m_NominalToBinaryFilter.setInputFormat(m_TrainInstances);
m_TrainInstances = Filter.useFilter(m_TrainInstances,
m_NominalToBinaryFilter);
// delete any attributes with only one distinct value or are all missing
deleteCols = new Vector<Integer>();
for (i = 0; i < m_TrainInstances.numAttributes(); i++) {
if (m_TrainInstances.numDistinctValues(i) <= 1) {
deleteCols.addElement(i);
}
}
if (m_TrainInstances.classIndex() >= 0) {
// get rid of the class column
m_HasClass = true;
m_ClassIndex = m_TrainInstances.classIndex();
deleteCols.addElement(new Integer(m_ClassIndex));
}
// remove columns from the data if necessary
if (deleteCols.size() > 0) {
m_AttributeFilter = new Remove();
todelete = new int[deleteCols.size()];
for (i = 0; i < deleteCols.size(); i++) {
todelete[i] = (deleteCols.elementAt(i)).intValue();
}
m_AttributeFilter.setAttributeIndicesArray(todelete);
m_AttributeFilter.setInvertSelection(false);
m_AttributeFilter.setInputFormat(m_TrainInstances);
m_TrainInstances = Filter.useFilter(m_TrainInstances, m_AttributeFilter);
}
// can evaluator handle the processed data ? e.g., enough attributes?
getCapabilities().testWithFail(m_TrainInstances);
m_NumInstances = m_TrainInstances.numInstances();
m_NumAttribs = m_TrainInstances.numAttributes();
// fillCorrelation();
fillCovariance();
// get eigen vectors/values
SymmDenseEVD evd = SymmDenseEVD.factorize(m_Correlation);
m_Eigenvectors = Matrices.getArray(evd.getEigenvectors());
m_Eigenvalues = evd.getEigenvalues();
// any eigenvalues less than 0 are not worth anything --- change to 0
for (i = 0; i < m_Eigenvalues.length; i++) {
if (m_Eigenvalues[i] < 0) {
m_Eigenvalues[i] = 0.0;
}
}
m_SortedEigens = Utils.sort(m_Eigenvalues);
m_SumOfEigenValues = Utils.sum(m_Eigenvalues);
m_TransformedFormat = determineOutputFormat(m_TrainInstances);
setOutputFormat(m_TransformedFormat);
m_TrainInstances = null;
}
/**
* 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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_Eigenvalues = null;
m_OutputNumAtts = -1;
m_AttributeFilter = null;
m_NominalToBinaryFilter = null;
m_SumOfEigenValues = 0.0;
return false;
}
/**
* Input an instance for filtering. Filter requires all training 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 set
* @throws Exception if conversion fails
*/
@Override
public boolean input(Instance instance) throws Exception {
Instance inst;
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (isNewBatch()) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
inst = convertInstance(instance);
inst.setDataset(getOutputFormat());
push(inst, false); // No need to copy
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws NullPointerException if no input structure has been defined,
* @throws Exception if there was a problem finishing the batch.
*/
@Override
public boolean batchFinished() throws Exception {
int i;
Instances insts;
Instance inst;
if (getInputFormat() == null) {
throw new NullPointerException("No input instance format defined");
}
insts = getInputFormat();
if (!isFirstBatchDone()) {
setup(insts);
}
for (i = 0; i < insts.numInstances(); i++) {
inst = convertInstance(insts.instance(i));
inst.setDataset(getOutputFormat());
push(inst, false); // No need to copy
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for running this filter.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new PrincipalComponents(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RandomProjection.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RandomProjection.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start -->
* Reduces the dimensionality of the data by projecting it onto a lower dimensional subspace using a random matrix with columns of unit length. It will reduce the number of attributes in the data while preserving much of its variation like PCA, but at a much less computational cost.<br/>
* It first applies the NominalToBinary filter to convert all attributes to numeric before reducing the dimension. It preserves the class attribute.<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Dmitriy Fradkin, David Madigan: Experiments with random projections for machine learning. In: KDD '03: Proceedings of the ninth ACM SIGKDD international conference on Knowledge discovery and data mining, New York, NY, USA, 517-522, 003.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @inproceedings{Fradkin003,
* address = {New York, NY, USA},
* author = {Dmitriy Fradkin and David Madigan},
* booktitle = {KDD '03: Proceedings of the ninth ACM SIGKDD international conference on Knowledge discovery and data mining},
* pages = {517-522},
* publisher = {ACM Press},
* title = {Experiments with random projections for machine learning},
* year = {003}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <number>
* The number of dimensions (attributes) the data should be reduced to
* (default 10; exclusive of the class attribute, if it is set).</pre>
*
* <pre> -D [SPARSE1|SPARSE2|GAUSSIAN]
* The distribution to use for calculating the random matrix.
* Sparse1 is:
* sqrt(3)*{-1 with prob(1/6), 0 with prob(2/3), +1 with prob(1/6)}
* Sparse2 is:
* {-1 with prob(1/2), +1 with prob(1/2)}
* </pre>
*
* <pre> -P <percent>
* The percentage of dimensions (attributes) the data should
* be reduced to (exclusive of the class attribute, if it is set). The -N
* option is ignored if this option is present and is greater
* than zero.</pre>
*
* <pre> -M
* Replace missing values using the ReplaceMissingValues filter instead of just skipping them.</pre>
*
* <pre> -R <num>
* The random seed for the random number generator used for
* calculating the random matrix (default 42).</pre>
*
* <!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz)
* @version $Revision$ [1.0 - 22 July 2003 - Initial version (Ashraf M.
* Kibriya)]
*/
public class RandomProjection extends Filter implements UnsupervisedFilter,
OptionHandler, TechnicalInformationHandler, Randomizable, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 4428905532728645880L;
/** Stores the number of dimensions to reduce the data to */
protected int m_k = 10;
/**
* Stores the dimensionality the data should be reduced to as percentage of
* the original dimension
*/
protected double m_percent = 0.0;
/** distribution type: sparse 1 */
public static final int SPARSE1 = 1;
/** distribution type: sparse 2 */
public static final int SPARSE2 = 2;
/** distribution type: gaussian */
public static final int GAUSSIAN = 3;
/**
* The types of distributions that can be used for calculating the random
* matrix
*/
public static final Tag[] TAGS_DSTRS_TYPE = { new Tag(SPARSE1, "Sparse1"),
new Tag(SPARSE2, "Sparse2"), new Tag(GAUSSIAN, "Gaussian"), };
/**
* Stores the distribution to use for calculating the random matrix
*/
protected int m_distribution = SPARSE1;
/**
* Should the missing values be replaced using
* unsupervised.ReplaceMissingValues filter
*/
protected boolean m_useReplaceMissing = false;
/** Keeps track of output format if it is defined or not */
protected boolean m_OutputFormatDefined = false;
/** The NominalToBinary filter applied to the data before this filter */
protected Filter m_ntob;
/** The ReplaceMissingValues filter */
protected Filter m_replaceMissing;
/** Stores the random seed used to generate the random matrix */
protected int m_rndmSeed = 42;
/** The random matrix */
protected double m_rmatrix[][];
/** The random number generator used for generating the random matrix */
protected Random m_random;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(5);
newVector.addElement(new Option(
"\tThe number of dimensions (attributes) the data should be reduced to\n"
+ "\t(default 10; exclusive of the class attribute, if it is set).",
"N", 1, "-N <number>"));
newVector
.addElement(new Option(
"\tThe distribution to use for calculating the random matrix.\n"
+ "\tSparse1 is:\n"
+ "\t sqrt(3)*{-1 with prob(1/6), 0 with prob(2/3), +1 with prob(1/6)}\n"
+ "\tSparse2 is:\n" + "\t {-1 with prob(1/2), +1 with prob(1/2)}",
"D", 1, "-D [SPARSE1|SPARSE2|GAUSSIAN]"));
// newVector.addElement(new Option(
// "\tUse Gaussian distribution for calculating the random matrix.",
// "G", 0, "-G"));
newVector
.addElement(new Option(
"\tThe percentage of dimensions (attributes) the data should\n"
+ "\tbe reduced to (exclusive of the class attribute, if it is set). The -N\n"
+ "\toption is ignored if this option is present and is greater\n"
+ "\tthan zero.", "P", 1, "-P <percent>"));
newVector.addElement(new Option(
"\tReplace missing values using the ReplaceMissingValues filter instead of just skipping them.",
"M", 0,
"-M"));
newVector.addElement(new Option(
"\tThe random seed for the random number generator used for\n"
+ "\tcalculating the random matrix (default 42).", "R", 0, "-R <num>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <number>
* The number of dimensions (attributes) the data should be reduced to
* (default 10; exclusive of the class attribute, if it is set).</pre>
*
* <pre> -D [SPARSE1|SPARSE2|GAUSSIAN]
* The distribution to use for calculating the random matrix.
* Sparse1 is:
* sqrt(3)*{-1 with prob(1/6), 0 with prob(2/3), +1 with prob(1/6)}
* Sparse2 is:
* {-1 with prob(1/2), +1 with prob(1/2)}
* </pre>
*
* <pre> -P <percent>
* The percentage of dimensions (attributes) the data should
* be reduced to (exclusive of the class attribute, if it is set). The -N
* option is ignored if this option is present and is greater
* than zero.</pre>
*
* <pre> -M
* Replace missing values using the ReplaceMissingValues filter instead of just skipping them.</pre>
*
* <pre> -R <num>
* The random seed for the random number generator used for
* calculating the random matrix (default 42).</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String mString = Utils.getOption('P', options);
if (mString.length() != 0) {
setPercent(Double.parseDouble(mString));
} else {
setPercent(0);
mString = Utils.getOption('N', options);
if (mString.length() != 0) {
setNumberOfAttributes(Integer.parseInt(mString));
} else {
setNumberOfAttributes(10);
}
}
mString = Utils.getOption('R', options);
if (mString.length() != 0) {
setSeed(Integer.parseInt(mString));
}
mString = Utils.getOption('D', options);
if (mString.length() != 0) {
if (mString.equalsIgnoreCase("sparse1")) {
setDistribution(new SelectedTag(SPARSE1, TAGS_DSTRS_TYPE));
} else if (mString.equalsIgnoreCase("sparse2")) {
setDistribution(new SelectedTag(SPARSE2, TAGS_DSTRS_TYPE));
} else if (mString.equalsIgnoreCase("gaussian")) {
setDistribution(new SelectedTag(GAUSSIAN, TAGS_DSTRS_TYPE));
}
}
if (Utils.getFlag('M', options)) {
setReplaceMissingValues(true);
} else {
setReplaceMissingValues(false);
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getReplaceMissingValues()) {
options.add("-M");
}
if (getPercent() <= 0) {
options.add("-N");
options.add("" + getNumberOfAttributes());
} else {
options.add("-P");
options.add("" + getPercent());
}
options.add("-R");
options.add("" + getSeed());
SelectedTag t = getDistribution();
options.add("-D");
options.add("" + t.getSelectedTag().getReadable());
return options.toArray(new String[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 "Reduces the dimensionality of the data by projecting"
+ " it onto a lower dimensional subspace using a random"
+ " matrix with columns of unit length. It will reduce"
+ " the number of attributes in the data while preserving"
+ " much of its variation like PCA, but at a much less"
+ " computational cost.\n"
+ "It first applies the NominalToBinary filter to"
+ " convert all attributes to numeric before reducing the"
+ " dimension. It preserves the class attribute.\n\n"
+ "For more information, see:\n\n" + getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing detailed
* information about the technical background of this class, e.g., paper
* reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.INPROCEEDINGS);
result.setValue(Field.AUTHOR, "Dmitriy Fradkin and David Madigan");
result.setValue(Field.TITLE,
"Experiments with random projections for machine learning");
result
.setValue(
Field.BOOKTITLE,
"KDD '03: Proceedings of the ninth ACM SIGKDD International Conference on Knowledge Discovery and Data mining");
result.setValue(Field.YEAR, "003");
result.setValue(Field.PAGES, "517-522");
result.setValue(Field.PUBLISHER, "ACM Press");
result.setValue(Field.ADDRESS, "New York, NY, USA");
return result;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numberOfAttributesTipText() {
return "The number of dimensions (attributes) the data should"
+ " be reduced to.";
}
/**
* Sets the number of attributes (dimensions) the data should be reduced to
*
* @param newAttNum the goal for the dimensions
*/
public void setNumberOfAttributes(int newAttNum) {
m_k = newAttNum;
}
/**
* Gets the current number of attributes (dimensionality) to which the data
* will be reduced to.
*
* @return the number of dimensions
*/
public int getNumberOfAttributes() {
return m_k;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String percentTipText() {
return " The percentage of dimensions (attributes) the data should"
+ " be reduced to (inclusive of the class attribute). The "
+ " NumberOfAttributes option is ignored if this option is"
+ " present or is greater than zero.";
}
/**
* Sets the percent the attributes (dimensions) of the data should be reduced
* to
*
* @param newPercent the percentage of attributes
*/
public void setPercent(double newPercent) {
if (newPercent > 0) {
newPercent /= 100;
}
m_percent = newPercent;
}
/**
* Gets the percent the attributes (dimensions) of the data will be reduced to
*
* @return the percentage of attributes
*/
public double getPercent() {
return m_percent * 100;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "The random seed used by the random"
+ " number generator used for generating the random matrix ";
}
/**
* Sets the random seed of the random number generator
*
* @param seed the random seed value
*/
@Override
public void setSeed(int seed) {
m_rndmSeed = seed;
}
/**
* Gets the random seed of the random number generator
*
* @return the random seed value
*/
@Override
public int getSeed() {
return m_rndmSeed;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String distributionTipText() {
return "The distribution to use for calculating the random matrix.\n"
+ "Sparse1 is:\n" + " sqrt(3) * { -1 with prob(1/6), \n"
+ " 0 with prob(2/3), \n"
+ " +1 with prob(1/6) } \n" + "Sparse2 is:\n"
+ " { -1 with prob(1/2), \n" + " +1 with prob(1/2) } ";
}
/**
* Sets the distribution to use for calculating the random matrix
*
* @param newDstr the distribution to use
*/
public void setDistribution(SelectedTag newDstr) {
if (newDstr.getTags() == TAGS_DSTRS_TYPE) {
m_distribution = newDstr.getSelectedTag().getID();
}
}
/**
* Returns the current distribution that'll be used for calculating the random
* matrix
*
* @return the current distribution
*/
public SelectedTag getDistribution() {
return new SelectedTag(m_distribution, TAGS_DSTRS_TYPE);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String replaceMissingValuesTipText() {
return "If set the filter uses weka.filters.unsupervised.attribute.ReplaceMissingValues"
+ " to replace the missing values instead of just skipping them.";
}
/**
* Sets either to use replace missing values filter or not
*
* @param t if true then the replace missing values is used
*/
public void setReplaceMissingValues(boolean t) {
m_useReplaceMissing = t;
}
/**
* Gets the current setting for using ReplaceMissingValues filter
*
* @return true if the replace missing values filter is used
*/
public boolean getReplaceMissingValues() {
return m_useReplaceMissing;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
result.disable(Capability.STRING_ATTRIBUTES);
result.disable(Capability.RELATIONAL_ATTRIBUTES);
// class
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
if (instanceInfo.classIndex() >= 0) {
m_ntob = new weka.filters.supervised.attribute.NominalToBinary();
} else {
m_ntob = new weka.filters.unsupervised.attribute.NominalToBinary();
}
m_replaceMissing = null;
m_OutputFormatDefined = false;
if (getReplaceMissingValues()) {
m_replaceMissing = new ReplaceMissingValues();
m_replaceMissing.setInputFormat(instanceInfo);
if (m_ntob.setInputFormat(m_replaceMissing.getOutputFormat())) {
setOutputFormat();
return true;
} else {
return false;
}
}
if (m_ntob.setInputFormat(instanceInfo)) {
setOutputFormat();
return true;
} else {
return false;
}
}
/**
* Input an instance for filtering.
*
* @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 set
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if ((m_OutputFormatDefined) && ((!m_useReplaceMissing) || isFirstBatchDone())) {
if (m_replaceMissing != null) {
m_replaceMissing.input(instance);
instance = m_replaceMissing.output();
}
m_ntob.input(instance);
instance = m_ntob.output();
push(convertInstance(instance), false);
return true;
}
bufferInput(instance);
return false;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws NullPointerException if no input structure has been defined,
* @throws Exception if there was a problem finishing the batch.
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new NullPointerException("No input instance format defined");
}
Instances insts = getInputFormat();
if (m_useReplaceMissing) {
insts = Filter.useFilter(insts, m_replaceMissing);
}
insts = Filter.useFilter(insts, m_ntob);
if (!m_OutputFormatDefined) {
setOutputFormat();
}
for (Instance instance : insts) {
push(convertInstance(instance), false); // No need to copy
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/** Sets the output format */
protected void setOutputFormat() throws Exception {
Instances currentFormat = m_ntob.getOutputFormat();
if (m_percent > 0) {
m_k = (int) ((getInputFormat().numAttributes() - 1) * m_percent);
}
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < m_k; i++) {
attributes.add(new Attribute("K" + (i + 1)));
}
if (getInputFormat().classIndex() > -1) {
attributes.add((Attribute) getInputFormat().classAttribute().copy());
}
Instances newFormat = new Instances(currentFormat.relationName(), attributes, 0);
if (getInputFormat().classIndex() > -1) {
newFormat.setClassIndex(attributes.size() - 1);
}
m_random = new Random(m_rndmSeed);
m_rmatrix = new double[m_k][currentFormat.numAttributes()];
if (m_distribution == GAUSSIAN) {
for (int i = 0; i < m_rmatrix.length; i++) {
for (int j = 0; j < m_rmatrix[i].length; j++) {
m_rmatrix[i][j] = m_random.nextGaussian();
}
}
} else {
boolean useDstrWithZero = (m_distribution == SPARSE1);
for (int i = 0; i < m_rmatrix.length; i++) {
for (int j = 0; j < m_rmatrix[i].length; j++) {
m_rmatrix[i][j] = rndmNum(useDstrWithZero);
}
}
}
m_OutputFormatDefined = true;
setOutputFormat(newFormat);
}
/**
* converts a single instance to the required format
*
* @param instance the instance to convert
* @return the converted instance
*/
protected Instance convertInstance(Instance instance) throws Exception {
double vals[] = new double[outputFormatPeek().numAttributes()];
for (int j = 0; j < m_k; j++) {
for (int i = 0; i < instance.numValues(); i++) {
int index = instance.index(i);
if (index != instance.classIndex()) {
double value = instance.valueSparse(i);
if (!Utils.isMissingValue(value)) {
vals[j] += m_rmatrix[j][index] * value;
}
} else {
vals[m_k] = instance.valueSparse(i);
}
}
}
return new DenseInstance(instance.weight(), vals);
}
private static final int weights[] = { 1, 1, 4 };
private static final int vals[] = { -1, 1, 0 };
private static final int weights2[] = { 1, 1 };
private static final int vals2[] = { -1, 1 };
private static final double sqrt3 = Math.sqrt(3);
/**
* returns a double x such that <br/>
* x = sqrt(3) * { -1 with prob. 1/6, 0 with prob. 2/3, 1 with prob. 1/6 }
*
* @param useDstrWithZero
* @return the generated number
*/
protected double rndmNum(boolean useDstrWithZero) {
if (useDstrWithZero) {
return sqrt3 * vals[weightedDistribution(weights)];
} else {
return vals2[weightedDistribution(weights2)];
}
}
/**
* Calculates a weighted distribution
*
* @param weights the weights to use
* @return
*/
protected int weightedDistribution(int[] weights) {
int sum = 0;
for (int weight : weights) {
sum += weight;
}
int val = (int) Math.floor(m_random.nextDouble() * sum);
for (int i = 0; i < weights.length; i++) {
val -= weights[i];
if (val < 0) {
return i;
}
}
return -1;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RandomProjection(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RandomSubset.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RandomSubset.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleStreamFilter;
/**
<!-- globalinfo-start -->
* Chooses a random subset of attributes, either an absolute number or a percentage. The class is always included in the output (as the last attribute).
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <double>
* The number of attributes to randomly select.
* If < 1 then percentage, >= 1 absolute number.
* (default: 0.5)</pre>
*
* <pre> -V
* Invert selection - i.e. randomly remove rather than select.</pre>
*
* <pre> -S <int>
* The seed value.
* (default: 1)</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
<!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @author eibe@cs.waikato.ac.nz
* @version $Revision$
*/
public class RandomSubset extends SimpleStreamFilter
implements Randomizable, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
private static final long serialVersionUID = 2911221724251628050L;
/**
* The number of attributes to randomly choose (>= 1 absolute number of
* attributes, < 1 percentage).
*/
protected double m_NumAttributes = 0.5;
/** The seed value. */
protected int m_Seed = 1;
/** The indices of the attributes that got selected. */
protected int[] m_Indices = null;
/** Whether to randomly remove rather than select */
protected boolean m_invertSelection;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Chooses a random subset of attributes, either an absolute number "
+ "or a percentage. The class is always included in the output ("
+ "as the last attribute).";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tThe number of attributes to randomly select.\n"
+ "\tIf < 1 then percentage, >= 1 absolute number.\n"
+ "\t(default: 0.5)", "N", 1, "-N <double>"));
result.addElement(new Option(
"\tInvert selection - i.e. randomly remove rather than select.", "V", 0,
"-V"));
result.addElement(new Option("\tThe seed value.\n" + "\t(default: 1)", "S",
1, "-S <int>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-N");
result.add("" + m_NumAttributes);
if (getInvertSelection()) {
result.add("-V");
}
result.add("-S");
result.add("" + m_Seed);
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -N <double>
* The number of attributes to randomly select.
* If < 1 then percentage, >= 1 absolute number.
* (default: 0.5)</pre>
*
* <pre> -V
* Invert selection - i.e. randomly remove rather than select.</pre>
*
* <pre> -S <int>
* The seed value.
* (default: 1)</pre>
*
* <pre> -output-debug-info
* If set, filter is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -do-not-check-capabilities
* If set, filter capabilities are not checked before filter is built
* (use with caution).</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption("N", options);
if (tmpStr.length() != 0) {
setNumAttributes(Double.parseDouble(tmpStr));
} else {
setNumAttributes(0.5);
}
setInvertSelection(Utils.getFlag('V', options));
tmpStr = Utils.getOption("S", options);
if (tmpStr.length() != 0) {
setSeed(Integer.parseInt(tmpStr));
} else {
setSeed(1);
}
super.setOptions(options);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numAttributesTipText() {
return "The number of attributes to choose: < 1 percentage, >= 1 absolute number.";
}
/**
* Get the number of attributes (< 1 percentage, >= 1 absolute number).
*
* @return the number of attributes.
*/
public double getNumAttributes() {
return m_NumAttributes;
}
/**
* Set the number of attributes.
*
* @param value the number of attributes to use.
*/
public void setNumAttributes(double value) {
m_NumAttributes = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Randomly remove rather than select attributes.";
}
/**
* Set whether to invert the selection - i.e. randomly remove rather than
* select attributes.
*
* @param inv true if the selection should be inverted
*/
public void setInvertSelection(boolean inv) {
m_invertSelection = inv;
}
/**
* Get whether to invert the selection - i.e. randomly remove rather than
* select attributes.
*
* @return true if the selection should be inverted
*/
public boolean getInvertSelection() {
return m_invertSelection;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "The seed value for the random number generator.";
}
/**
* Get the seed value for the random number generator.
*
* @return the seed value.
*/
public int getSeed() {
return m_Seed;
}
/**
* Set the seed value for the random number generator.
*
* @param value the seed value.
*/
public void setSeed(int value) {
m_Seed = value;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
ArrayList<Attribute> atts;
int i;
int numAtts;
Vector<Integer> indices;
Vector<Integer> subset;
Random rand;
int index;
// determine the number of attributes
numAtts = inputFormat.numAttributes();
if (inputFormat.classIndex() > -1) {
numAtts--;
}
if (m_NumAttributes < 1) {
numAtts = (int) Math.round(numAtts * m_NumAttributes);
} else {
if (m_NumAttributes < numAtts) {
numAtts = (int) m_NumAttributes;
}
}
if (getDebug()) {
System.out.println("# of atts: " + numAtts);
}
// determine random indices
indices = new Vector<Integer>();
for (i = 0; i < inputFormat.numAttributes(); i++) {
if (i == inputFormat.classIndex()) {
continue;
}
indices.add(i);
}
subset = new Vector<Integer>();
rand = new Random(m_Seed);
for (i = 0; i < numAtts; i++) {
index = rand.nextInt(indices.size());
subset.add(indices.get(index));
indices.remove(index);
}
if (m_invertSelection) {
subset = indices;
}
Collections.sort(subset);
if (inputFormat.classIndex() > -1) {
subset.add(inputFormat.classIndex());
}
if (getDebug()) {
System.out.println("indices: " + subset);
}
// generate output format
atts = new ArrayList<Attribute>();
m_Indices = new int[subset.size()];
for (i = 0; i < subset.size(); i++) {
atts.add((Attribute)inputFormat.attribute(subset.get(i)).copy());
m_Indices[i] = subset.get(i);
}
result = new Instances(inputFormat.relationName(), atts, 0);
if (inputFormat.classIndex() > -1) {
result.setClassIndex(result.numAttributes() - 1);
}
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
Instance result;
if (instance instanceof SparseInstance) {
int n1 = instance.numValues();
int classIndex = getInputFormat().classIndex();
int n2 = classIndex >= 0 ? m_Indices.length : m_Indices.length - 1;
int[] indices = new int[instance.numValues()];
double[] values = new double[instance.numValues()];
int vals = 0;
double classValue = 0;
boolean classFound = false;
for (int p1 = 0, p2 = 0; p1 < n1 && p2 < n2;) {
int ind1 = instance.index(p1);
int ind2 = m_Indices[p2];
if (ind1 == classIndex) {
classFound = true;
classValue = instance.valueSparse(p1);
p1++;
} else if (ind1 == ind2) {
indices[vals] = p2;
values[vals] = instance.valueSparse(p1);
vals++;
p1++;
p2++;
} else if (ind1 > ind2) {
p2++;
} else {
p1++;
}
}
if (classFound) {
indices[vals] = outputFormatPeek().numAttributes() - 1;
values[vals] = classValue;
}
result = new SparseInstance(instance.weight(), values, indices, m_Indices.length);
} else {
double[] values = new double[m_Indices.length];
for (int i = 0; i < m_Indices.length; i++) {
values[i] = instance.value(m_Indices[i]);
}
result = new DenseInstance(instance.weight(), values);
}
copyValues(result, false, instance.dataset(), outputFormatPeek());
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Runs the filter with the given parameters. Use -h to list options.
*
* @param args the commandline options
*/
public static void main(String[] args) {
runFilter(new RandomSubset(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Remove.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Remove.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An filter that removes a range of attributes from
* the dataset. Will re-order the remaining attributes if invert matching sense
* is turned on and the attribute column indices are not specified in ascending
* order.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to delete. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only keep specified columns)
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Remove extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 5011337331921522847L;
/** Stores which columns to select as a funky range */
protected Range m_SelectCols = new Range();
/**
* Stores the indexes of the selected attributes in order, once the dataset is
* seen
*/
protected int[] m_SelectedAttributes;
/**
* Constructor so that we can initialize the Range variable properly.
*/
public Remove() {
m_SelectCols.setInvert(true);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector
.addElement(new Option(
"\tSpecify list of columns to delete. First and last are valid\n"
+ "\tindexes. (default none)", "R", 1,
"-R <index1,index2-index4,...>"));
newVector.addElement(new Option(
"\tInvert matching sense (i.e. only keep specified columns)", "V", 0,
"-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of columns to delete. First and last are valid
* indexes. (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only keep specified columns)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String deleteList = Utils.getOption('R', options);
if (deleteList.length() != 0) {
setAttributeIndices(deleteList);
}
setInvertSelection(Utils.getFlag('V', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
return options.toArray(new String[0]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_SelectCols.setUpper(instanceInfo.numAttributes() - 1);
// Create the output buffer
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
int outputClass = -1;
m_SelectedAttributes = m_SelectCols.getSelection();
for (int current : m_SelectedAttributes) {
if (instanceInfo.classIndex() == current) {
outputClass = attributes.size();
}
Attribute keep = (Attribute) instanceInfo.attribute(current).copy();
attributes.add(keep);
}
// initInputLocators(instanceInfo, m_SelectedAttributes);
initInputLocators(getInputFormat(), m_SelectedAttributes);
Instances outputFormat = new Instances(instanceInfo.relationName(),
attributes, 0);
outputFormat.setClassIndex(outputClass);
setOutputFormat(outputFormat);
return true;
}
/**
* 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 structure has been defined.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (getOutputFormat().numAttributes() == 0) {
return false;
}
double[] vals = new double[getOutputFormat().numAttributes()];
for (int i = 0; i < m_SelectedAttributes.length; i++) {
int current = m_SelectedAttributes[i];
vals[i] = instance.value(current);
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy
return true;
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that removes a range of"
+ " attributes from the dataset. Will "
+ "re-order the remaining attributes "
+ "if invert matching sense is turned "
+ "on and the attribute column indices "
+ "are not specified in ascending order.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether action is to select or delete."
+ " If set to true, only the specified attributes will be kept;"
+ " If set to false, specified attributes will be deleted.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return !m_SelectCols.getInvert();
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are deleted. If false
* selected columns are deleted and unselected columns are kept.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_SelectCols.setInvert(!invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Get the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_SelectCols.getRanges();
}
/**
* Set which attributes are to be deleted (or kept if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String rangeList) {
m_SelectCols.setRanges(rangeList);
}
/**
* Set which attributes are to be deleted (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Remove(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RemoveByName.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveByName.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.filters.SimpleStreamFilter;
/**
* <!-- globalinfo-start --> Removes attributes based on a regular expression
* matched against their names.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -E <regular expression>
* The regular expression to match the attribute names against.
* (default: ^.*id$)
* </pre>
*
* <pre>
* -V
* Flag for inverting the matching sense. If set, attributes are kept
* instead of deleted.
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class RemoveByName extends SimpleStreamFilter implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
private static final long serialVersionUID = -3335106965521265631L;
/** the default expression. */
public final static String DEFAULT_EXPRESSION = "^.*id$";
/** the regular expression for selecting the attributes by name. */
protected String m_Expression = DEFAULT_EXPRESSION;
/** whether to invert the matching sense. */
protected boolean m_InvertSelection;
/** the Remove filter used internally for removing the attributes. */
protected Remove m_Remove;
/**
* Returns a string describing this classifier.
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Removes attributes based on a regular expression matched against "
+ "their names but will not remove the class attribute.";
}
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(2);
result.addElement(new Option(
"\tThe regular expression to match the attribute names against.\n"
+ "\t(default: " + DEFAULT_EXPRESSION + ")", "E", 1,
"-E <regular expression>"));
result.addElement(new Option(
"\tFlag for inverting the matching sense. If set, attributes are kept\n"
+ "\tinstead of deleted.\n" + "\t(default: off)", "V", 0, "-V"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* returns the options of the current setup.
*
* @return the current options
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-E");
result.add("" + getExpression());
if (getInvertSelection()) {
result.add("-V");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses the options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -E <regular expression>
* The regular expression to match the attribute names against.
* (default: ^.*id$)
* </pre>
*
* <pre>
* -V
* Flag for inverting the matching sense. If set, attributes are kept
* instead of deleted.
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if the option setting fails
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption("E", options);
if (tmpStr.length() != 0) {
setExpression(tmpStr);
} else {
setExpression(DEFAULT_EXPRESSION);
}
setInvertSelection(Utils.getFlag("V", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Sets the regular expression to match the attribute names against.
*
* @param value the regular expression
*/
public void setExpression(String value) {
m_Expression = value;
}
/**
* Returns the regular expression in use.
*
* @return the regular expression
*/
public String getExpression() {
return m_Expression;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String expressionTipText() {
return "The regular expression to match the attribute names against.";
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are deleted. If false
* selected columns are deleted and unselected columns are kept.
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_InvertSelection = value;
}
/**
* Get whether the supplied columns are to be removed or kept.
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_InvertSelection;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether action is to select or delete."
+ " If set to true, only the specified attributes will be kept;"
+ " If set to false, specified attributes will be deleted.";
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
// determine indices
Vector<Integer> indices = new Vector<Integer>();
for (int i = 0; i < inputFormat.numAttributes(); i++) {
// always leave class if set
if ((i == inputFormat.classIndex())) {
if (getInvertSelection()) {
indices.add(i);
}
continue;
}
if (inputFormat.attribute(i).name().matches(m_Expression)) {
indices.add(i);
}
}
int[] attributes = new int[indices.size()];
for (int i = 0; i < indices.size(); i++) {
attributes[i] = indices.get(i);
}
m_Remove = new Remove();
m_Remove.setAttributeIndicesArray(attributes);
m_Remove.setInvertSelection(getInvertSelection());
m_Remove.setInputFormat(inputFormat);
return m_Remove.getOutputFormat();
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
result = new Remove().getCapabilities();
result.setOwner(this);
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
m_Remove.input(instance);
return m_Remove.output();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the filter with the given arguments.
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new RemoveByName(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RemoveType.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveType.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Removes attributes of a given type.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -T <nominal|numeric|string|date|relational>
* Attribute type to delete. Valid options are "nominal",
* "numeric", "string", "date" and "relational".
* (default "string")
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only keep specified columns)
* </pre>
*
* <!-- options-end -->
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveType extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -3563999462782486279L;
/** The attribute filter used to do the filtering */
protected Remove m_attributeFilter = new Remove();
/** The type of attribute to delete */
protected int m_attTypeToDelete = Attribute.STRING;
/** Whether to invert selection */
protected boolean m_invert = false;
/** Tag allowing selection of attribute type to delete */
public static final Tag[] TAGS_ATTRIBUTETYPE = {
new Tag(Attribute.NOMINAL, "Delete nominal attributes"),
new Tag(Attribute.NUMERIC, "Delete numeric attributes"),
new Tag(Attribute.STRING, "Delete string attributes"),
new Tag(Attribute.DATE, "Delete date attributes"),
new Tag(Attribute.RELATIONAL, "Delete relational attributes") };
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.STRING_ATTRIBUTES);
result.enable(Capability.RELATIONAL_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
int[] attsToDelete = new int[instanceInfo.numAttributes()];
int numToDelete = 0;
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i == instanceInfo.classIndex()) {
if (!m_invert) {
continue; // skip class
} else {
attsToDelete[numToDelete++] = i; // Need to keep the class even if
// selection is inverted
}
}
if (instanceInfo.attribute(i).type() == m_attTypeToDelete) {
attsToDelete[numToDelete++] = i;
}
}
int[] finalAttsToDelete = new int[numToDelete];
System.arraycopy(attsToDelete, 0, finalAttsToDelete, 0, numToDelete);
m_attributeFilter.setAttributeIndicesArray(finalAttsToDelete);
m_attributeFilter.setInvertSelection(m_invert);
boolean result = m_attributeFilter.setInputFormat(instanceInfo);
Instances afOutputFormat = m_attributeFilter.getOutputFormat();
// restore old relation name to hide attribute filter stamp
afOutputFormat.setRelationName(instanceInfo.relationName());
setOutputFormat(afOutputFormat);
return result;
}
/**
* Input an instance for filtering.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
*/
@Override
public boolean input(Instance instance) {
return m_attributeFilter.input(instance);
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws Exception if something goes wrong
*/
@Override
public boolean batchFinished() throws Exception {
return m_attributeFilter.batchFinished();
}
/**
* Output an instance after filtering and remove from the output queue.
*
* @return the instance that has most recently been filtered (or null if the
* queue is empty).
*/
@Override
public Instance output() {
return m_attributeFilter.output();
}
/**
* Output an instance after filtering but do not remove from the output queue.
*
* @return the instance that has most recently been filtered (or null if the
* queue is empty).
*/
@Override
public Instance outputPeek() {
return m_attributeFilter.outputPeek();
}
/**
* Returns the number of instances pending output
*
* @return the number of instances pending output
*/
@Override
public int numPendingOutput() {
return m_attributeFilter.numPendingOutput();
}
/**
* Returns whether the output format is ready to be collected
*
* @return true if the output format is set
*/
@Override
public boolean isOutputFormatDefined() {
return m_attributeFilter.isOutputFormatDefined();
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option(
"\tAttribute type to delete. Valid options are \"nominal\", \n"
+ "\t\"numeric\", \"string\", \"date\" and \"relational\".\n"
+ "\t(default \"string\")", "T", 1,
"-T <nominal|numeric|string|date|relational>"));
newVector.addElement(new Option(
"\tInvert matching sense (i.e. only keep specified columns)", "V", 0,
"-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -T <nominal|numeric|string|date|relational>
* Attribute type to delete. Valid options are "nominal",
* "numeric", "string", "date" and "relational".
* (default "string")
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. only keep specified columns)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tString = Utils.getOption('T', options);
if (tString.length() != 0) {
setAttributeTypeString(tString);
}
setInvertSelection(Utils.getFlag('V', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
options.add("-T");
options.add(getAttributeTypeString());
return options.toArray(new String[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 "Removes attributes of a given type.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeTypeTipText() {
return "The type of attribute to remove.";
}
/**
* Sets the attribute type to be deleted by the filter.
*
* @param type a TAGS_ATTRIBUTETYPE of the new type the filter should delete
*/
public void setAttributeType(SelectedTag type) {
if (type.getTags() == TAGS_ATTRIBUTETYPE) {
m_attTypeToDelete = type.getSelectedTag().getID();
}
}
/**
* Gets the attribute type to be deleted by the filter.
*
* @return the attribute type as a selected tag TAGS_ATTRIBUTETYPE
*/
public SelectedTag getAttributeType() {
return new SelectedTag(m_attTypeToDelete, TAGS_ATTRIBUTETYPE);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether action is to select or delete."
+ " If set to true, only the specified attributes will be kept;"
+ " If set to false, specified attributes will be deleted.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_invert;
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are deleted. If false
* selected columns are deleted and unselected columns are kept.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_invert = invert;
}
/**
* Gets the attribute type to be deleted by the filter as a string.
*
* @return the attribute type as a String
*/
protected String getAttributeTypeString() {
if (m_attTypeToDelete == Attribute.NOMINAL) {
return "nominal";
} else if (m_attTypeToDelete == Attribute.NUMERIC) {
return "numeric";
} else if (m_attTypeToDelete == Attribute.STRING) {
return "string";
} else if (m_attTypeToDelete == Attribute.DATE) {
return "date";
} else if (m_attTypeToDelete == Attribute.RELATIONAL) {
return "relational";
} else {
return "unknown";
}
}
/**
* Sets the attribute type to be deleted by the filter.
*
* @param typeString a String representing the new type the filter should
* delete
*/
protected void setAttributeTypeString(String typeString) {
typeString = typeString.toLowerCase();
if (typeString.equals("nominal")) {
m_attTypeToDelete = Attribute.NOMINAL;
} else if (typeString.equals("numeric")) {
m_attTypeToDelete = Attribute.NUMERIC;
} else if (typeString.equals("string")) {
m_attTypeToDelete = Attribute.STRING;
} else if (typeString.equals("date")) {
m_attTypeToDelete = Attribute.DATE;
} else if (typeString.equals("relational")) {
m_attTypeToDelete = Attribute.RELATIONAL;
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RemoveType(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RemoveUseless.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveUseless.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.AttributeStats;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> This filter removes attributes that do not vary at all or that vary too
* much. All constant attributes are deleted automatically, along with any that exceed the maximum
* percentage of variance parameter. The maximum variance test is only applied to nominal
* attributes.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -M <max variance %>
* Maximum variance percentage allowed (default 99). Specifically, if
* (number_of_distinct_values / total_number_of_values * 100)
* is greater than this value, then the attribute will be removed.
* </pre>
*
* <!-- options-end -->
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveUseless extends Filter implements UnsupervisedFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -8659417851407640038L;
/** The filter used to remove attributes */
protected Remove m_removeFilter = null;
/** The type of attribute to delete */
protected double m_maxVariancePercentage = 99.0;
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.STRING_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.m_removeFilter = null;
return false;
}
/**
* Input an instance for filtering.
*
* @param instance
* the input instance
* @return true if the filtered instance may now be collected with output().
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.m_removeFilter != null) {
this.m_removeFilter.input(instance);
Instance processed = this.m_removeFilter.output();
this.copyValues(processed, false, instance.dataset(), this.outputFormatPeek());
this.push(processed, false); // No need to copy
return true;
}
this.bufferInput(instance);
return false;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws Exception
* if no input format defined
*/
@Override
public boolean batchFinished() throws Exception {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_removeFilter == null) {
// establish attributes to remove from first batch
Instances toFilter = this.getInputFormat();
int[] attsToDelete = new int[toFilter.numAttributes()];
int numToDelete = 0;
for (int i = 0; i < toFilter.numAttributes(); i++) {
if (i == toFilter.classIndex()) {
continue; // skip class
}
AttributeStats stats = toFilter.attributeStats(i);
if (stats.missingCount == toFilter.numInstances()) {
attsToDelete[numToDelete++] = i;
} else if (stats.distinctCount < 2) {
// remove constant attributes
attsToDelete[numToDelete++] = i;
} else if (toFilter.attribute(i).isNominal()) {
// remove nominal attributes that vary too much
double variancePercent = (double) stats.distinctCount / (double) (stats.totalCount - stats.missingCount) * 100.0;
if (variancePercent > this.m_maxVariancePercentage) {
attsToDelete[numToDelete++] = i;
}
}
}
int[] finalAttsToDelete = new int[numToDelete];
System.arraycopy(attsToDelete, 0, finalAttsToDelete, 0, numToDelete);
this.m_removeFilter = new Remove();
this.m_removeFilter.setAttributeIndicesArray(finalAttsToDelete);
this.m_removeFilter.setInvertSelection(false);
this.m_removeFilter.setInputFormat(toFilter);
for (int i = 0; i < toFilter.numInstances(); i++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
this.m_removeFilter.input(toFilter.instance(i));
}
this.m_removeFilter.batchFinished();
Instance processed;
Instances outputDataset = this.m_removeFilter.getOutputFormat();
// restore old relation name to hide attribute filter stamp
outputDataset.setRelationName(toFilter.relationName());
this.setOutputFormat(outputDataset);
while ((processed = this.m_removeFilter.output()) != null) {
processed.setDataset(outputDataset);
this.push(processed, false); // No need to copy
}
}
this.flushInput();
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<>(1);
newVector.addElement(
new Option("\tMaximum variance percentage allowed (default 99). Specifically, if" + "\t(number_of_distinct_values / total_number_of_values * 100)" + "\tis greater than this value, then the attribute will be removed.", "M",
1, "-M <max variance %>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -M <max variance %>
* Maximum variance percentage allowed (default 99). Specifically, if
* (number_of_distinct_values / total_number_of_values * 100)
* is greater than this value, then the attribute will be removed.
* </pre>
*
* <!-- options-end -->
*
* @param options
* the list of options as an array of strings
* @throws Exception
* if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String mString = Utils.getOption('M', options);
if (mString.length() != 0) {
this.setMaximumVariancePercentageAllowed((int) Double.valueOf(mString).doubleValue());
} else {
this.setMaximumVariancePercentageAllowed(99.0);
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<>();
options.add("-M");
options.add("" + this.getMaximumVariancePercentageAllowed());
return options.toArray(new String[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 "This filter removes attributes that do not vary at all or that vary " + "too much. All constant attributes are deleted automatically, along " + "with any that exceed the maximum percentage of variance parameter. "
+ "The maximum variance test is only applied to nominal attributes.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the explorer/experimenter gui
*/
public String maximumVariancePercentageAllowedTipText() {
return "Set the threshold for the highest variance allowed before a nominal attribute will be deleted. " + "Specifically, if (number_of_distinct_values / total_number_of_values * 100)"
+ " is greater than this value, then the attribute will be removed.";
}
/**
* Sets the maximum variance attributes are allowed to have before they are deleted by the filter.
*
* @param maxVariance
* the maximum variance allowed, specified as a percentage
*/
public void setMaximumVariancePercentageAllowed(final double maxVariance) {
this.m_maxVariancePercentage = maxVariance;
}
/**
* Gets the maximum variance attributes are allowed to have before they are deleted by the filter.
*
* @return the maximum variance allowed, specified as a percentage
*/
public double getMaximumVariancePercentageAllowed() {
return this.m_maxVariancePercentage;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv
* should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new RemoveUseless(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RenameAttribute.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RenameAttribute.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleStreamFilter;
/**
* <!-- globalinfo-start --> This filter is used for renaming attributes.<br/>
* Regular expressions can be used in the matching and replacing.<br/>
* See Javadoc of java.util.regex.Pattern class for more information:<br/>
* http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -find <regexp>
* The regular expression that the attribute names must match.
* (default: ([\s\S]+))
* </pre>
*
* <pre>
* -replace <string>
* The string to replace the regular expression of matching attributes with.
* Cannot be used in conjunction with '-remove'.
* (default: $0)
* </pre>
*
* <pre>
* -remove
* In case the matching string needs to be removed instead of replaced.
* Cannot be used in conjunction with '-replace <string>'.
* (default: off)
* </pre>
*
* <pre>
* -all
* Replaces all occurrences instead of just the first.
* (default: only first occurrence)
* </pre>
*
* <pre>
* -R <range>
* The attribute range to work on.
* This is a comma separated list of attribute indices, with "first" and "last" valid values.
* Specify an inclusive range with "-".
* E.g: "first-3,5,6-10,last".
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Inverts the attribute selection range.
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class RenameAttribute extends SimpleStreamFilter implements WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization. */
private static final long serialVersionUID = 4216491776378279596L;
/** the regular expression that the attribute names have to match. */
protected String m_Find = "([\\s\\S]+)";
/** the regular expression to replace the attribute name with. */
protected String m_Replace = "$0";
/** the attribute range to work on. */
protected Range m_AttributeIndices = new Range("first-last");
/** whether to replace all occurrences or just the first. */
protected boolean m_ReplaceAll = false;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "This filter is used for renaming attributes.\n\n"
+ "Regular expressions can be used in the matching and replacing.\n\n"
+ "See Javadoc of java.util.regex.Pattern class for more information:\n"
+ "http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(6);
result.addElement(new Option(
"\tThe regular expression that the attribute names must match.\n"
+ "\t(default: ([\\s\\S]+))", "find", 1, "-find <regexp>"));
result.addElement(new Option(
"\tThe string to replace the regular expression of matching attributes with.\n"
+ "\tCannot be used in conjunction with '-remove'.\n"
+ "\t(default: $0)", "replace", 1, "-replace <string>"));
result.addElement(new Option(
"\tIn case the matching string needs to be removed instead of replaced.\n"
+ "\tCannot be used in conjunction with '-replace <string>'.\n"
+ "\t(default: off)", "remove", 0, "-remove"));
result.addElement(new Option(
"\tReplaces all occurrences instead of just the first.\n"
+ "\t(default: only first occurrence)", "all", 0, "-all"));
result.addElement(new Option("\tThe attribute range to work on.\n"
+ "This is a comma separated list of attribute indices, with "
+ "\"first\" and \"last\" valid values.\n"
+ "\tSpecify an inclusive range with \"-\".\n"
+ "\tE.g: \"first-3,5,6-10,last\".\n" + "\t(default: first-last)", "R",
1, "-R <range>"));
result.addElement(new Option("\tInverts the attribute selection range.\n"
+ "\t(default: off)", "V", 0, "-V"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -find <regexp>
* The regular expression that the attribute names must match.
* (default: ([\s\S]+))
* </pre>
*
* <pre>
* -replace <string>
* The string to replace the regular expression of matching attributes with.
* Cannot be used in conjunction with '-remove'.
* (default: $0)
* </pre>
*
* <pre>
* -remove
* In case the matching string needs to be removed instead of replaced.
* Cannot be used in conjunction with '-replace <string>'.
* (default: off)
* </pre>
*
* <pre>
* -all
* Replaces all occurrences instead of just the first.
* (default: only first occurrence)
* </pre>
*
* <pre>
* -R <range>
* The attribute range to work on.
* This is a comma separated list of attribute indices, with "first" and "last" valid values.
* Specify an inclusive range with "-".
* E.g: "first-3,5,6-10,last".
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Inverts the attribute selection range.
* (default: off)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption("find", options);
if (tmpStr.length() != 0) {
setFind(tmpStr);
} else {
setFind("([\\s\\S]+)");
}
if (Utils.getFlag("remove", options)) {
setReplace("");
} else {
tmpStr = Utils.getOption("replace", options);
if (tmpStr.length() > 0) {
setReplace(tmpStr);
} else {
setReplace("$0");
}
}
setReplaceAll(Utils.getFlag("all", options));
tmpStr = Utils.getOption("R", options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("first-last");
}
setInvertSelection(Utils.getFlag("V", options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-find");
result.add(getFind());
if (getReplace().length() > 0) {
result.add("-replace");
result.add(getReplace());
} else {
result.add("-remove");
}
if (getReplaceAll()) {
result.add("-all");
}
result.add("-R");
result.add(getAttributeIndices());
if (getInvertSelection()) {
result.add("-V");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Sets the regular expression that the attribute names must match.
*
* @param value the regular expression
*/
public void setFind(String value) {
m_Find = value;
}
/**
* Returns the current regular expression for .
*
* @return a string containing a comma separated list of ranges
*/
public String getFind() {
return m_Find;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String findTipText() {
return "The regular expression that the attribute names must match.";
}
/**
* Sets the regular expression to replace matching attribute names with.
*
* @param value the regular expression
*/
public void setReplace(String value) {
m_Replace = value;
}
/**
* Returns the regular expression to replace matching attribute names with.
*
* @return the regular expression
*/
public String getReplace() {
return m_Replace;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String replaceTipText() {
return "The regular expression to use for replacing the matching attribute "
+ "names with.";
}
/**
* Sets whether to replace all occurrences or just the first one.
*
* @param value if true then all occurrences are replace
*/
public void setReplaceAll(boolean value) {
m_ReplaceAll = value;
}
/**
* Returns whether all occurrences are replaced or just the first one.
*
* @return true if all occurrences are replaced
*/
public boolean getReplaceAll() {
return m_ReplaceAll;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String replaceAllTipText() {
return "If set to true, then all occurrences of the match will be replaced; "
+ "otherwise only the first.";
}
/**
* Sets which attributes are to be acted on.
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from1. <br/>
* eg: first-3,5,6-last
*/
public void setAttributeIndices(String value) {
m_AttributeIndices.setRanges(value);
}
/**
* Gets the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_AttributeIndices.getRanges();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on; "
+ "this is a comma separated list of attribute indices, with "
+ "\"first\" and \"last\" valid values; specify an inclusive "
+ "range with \"-\"; eg: \"first-3,5,6-10,last\".";
}
/**
* Sets whether to invert the selection of the attributes.
*
* @param value if true then the selection is inverted
*/
public void setInvertSelection(boolean value) {
m_AttributeIndices.setInvert(value);
}
/**
* Gets whether to invert the selection of the attributes.
*
* @return true if the selection is inverted
*/
public boolean getInvertSelection() {
return m_AttributeIndices.getInvert();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "If set to true, the selection will be inverted; eg: the attribute "
+ "indices '2-4' then mean everything apart from '2-4'.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* hasImmediateOutputFormat() returns false, then this method will called from
* batchFinished() after the call of preprocess(Instances), in which, e.g.,
* statistics for the actual processing step can be gathered.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
Attribute att;
ArrayList<Attribute> atts;
int i;
m_AttributeIndices.setUpper(inputFormat.numAttributes() - 1);
// generate new header
atts = new ArrayList<Attribute>();
for (i = 0; i < inputFormat.numAttributes(); i++) {
att = inputFormat.attribute(i);
if (m_AttributeIndices.isInRange(i)) {
if (m_ReplaceAll) {
atts.add(att.copy(att.name().replaceAll(m_Find, m_Replace)));
} else {
atts.add(att.copy(att.name().replaceFirst(m_Find, m_Replace)));
}
} else {
atts.add((Attribute) att.copy());
}
}
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
return (Instance) instance.copy();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for executing this filter.
*
* @param args the arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new RenameAttribute(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/RenameNominalValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RenameNominalValues.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Renames the values of nominal attributes.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are:
* <p/>
*
* <pre>
* -R
* Attributes to act on. Can be either a range
* string (e.g. 1,2,6-10) OR a comma-separated list of named attributes
* (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. act on all attributes other than those specified)
* </pre>
*
* <pre>
* -N
* Nominal labels and their replacement values.
* E.g. red:blue, black:white, fred:bob
* </pre>
*
* <pre>
* -I
* Ignore case when matching nominal values
* </pre>
*
<!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class RenameNominalValues extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** For serialization */
private static final long serialVersionUID = -2121767582746512209L;
/** Range specification or comma-separated list of attribute names */
protected String m_selectedColsString = "";
/** The range object to use if a range has been supplied */
protected Range m_selectedCols = new Range();
/** The comma-separated list of nominal values and their replacements */
protected String m_renameVals = "";
/** True if case is to be ignored when matching nominal values */
protected boolean m_ignoreCase = false;
/** True if the matching sense (for attributes) is to be inverted */
protected boolean m_invert = false;
/**
* Stores the indexes of the selected attributes in order, once the dataset is
* seen
*/
protected int[] m_selectedAttributes;
/** The map of nominal values and their replacements */
protected Map<String, String> m_renameMap = new HashMap<String, String>();
/**
* Global help info
*
* @return the help info for this filter
*/
public String globalInfo() {
return "Renames the values of nominal attributes.";
}
/**
* 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 format couldn't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
int classIndex = instanceInfo.classIndex();
// setup the map
if (m_renameVals != null && m_renameVals.length() > 0) {
String[] vals = m_renameVals.split(",");
for (String val : vals) {
String[] parts = val.split(":");
if (parts.length != 2) {
throw new WekaException("Invalid replacement string: " + val);
}
if (parts[0].length() == 0 || parts[1].length() == 0) {
throw new WekaException("Invalid replacement string: " + val);
}
m_renameMap.put(
m_ignoreCase ? parts[0].toLowerCase().trim() : parts[0].trim(),
parts[1].trim());
}
}
// try selected atts as a numeric range first
Range tempRange = new Range();
tempRange.setInvert(m_invert);
if (m_selectedColsString == null) {
m_selectedColsString = "";
}
try {
tempRange.setRanges(m_selectedColsString);
tempRange.setUpper(instanceInfo.numAttributes() - 1);
m_selectedAttributes = tempRange.getSelection();
m_selectedCols = tempRange;
} catch (Exception r) {
// OK, now try as named attributes
StringBuffer indexes = new StringBuffer();
String[] attNames = m_selectedColsString.split(",");
boolean first = true;
for (String n : attNames) {
n = n.trim();
Attribute found = instanceInfo.attribute(n);
if (found == null) {
throw new WekaException("Unable to find attribute '" + n
+ "' in the incoming instances'");
}
if (first) {
indexes.append("" + (found.index() + 1));
first = false;
} else {
indexes.append("," + (found.index() + 1));
}
}
tempRange = new Range();
tempRange.setRanges(indexes.toString());
tempRange.setUpper(instanceInfo.numAttributes() - 1);
m_selectedAttributes = tempRange.getSelection();
m_selectedCols = tempRange;
}
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_selectedCols.isInRange(i)) {
if (instanceInfo.attribute(i).isNominal()) {
List<String> valsForAtt = new ArrayList<String>();
for (int j = 0; j < instanceInfo.attribute(i).numValues(); j++) {
String origV = instanceInfo.attribute(i).value(j);
String replace = m_ignoreCase ? m_renameMap
.get(origV.toLowerCase()) : m_renameMap.get(origV);
if (replace != null && !valsForAtt.contains(replace)) {
valsForAtt.add(replace);
} else {
valsForAtt.add(origV);
}
}
Attribute newAtt = new Attribute(instanceInfo.attribute(i).name(), valsForAtt);
newAtt.setWeight(instanceInfo.attribute(i).weight());
attributes.add(newAtt);
} else {
// ignore any selected attributes that are not nominal
Attribute att = (Attribute) instanceInfo.attribute(i).copy();
attributes.add(att);
}
} else {
Attribute att = (Attribute) instanceInfo.attribute(i).copy();
attributes.add(att);
}
}
Instances outputFormat = new Instances(instanceInfo.relationName(),
attributes, 0);
outputFormat.setClassIndex(classIndex);
setOutputFormat(outputFormat);
return true;
}
/**
* 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 structure has been defined.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (getOutputFormat().numAttributes() == 0) {
return false;
}
if (m_selectedAttributes.length == 0) {
push(instance);
} else {
double vals[] = new double[getOutputFormat().numAttributes()];
for (int i = 0; i < instance.numAttributes(); i++) {
double currentV = instance.value(i);
if (!m_selectedCols.isInRange(i)) {
vals[i] = currentV;
} else {
if (currentV == Utils.missingValue()) {
vals[i] = currentV;
} else {
String currentS = instance.attribute(i).value((int) currentV);
String replace = m_ignoreCase ? m_renameMap.get(currentS
.toLowerCase()) : m_renameMap.get(currentS);
if (replace == null) {
vals[i] = currentV;
} else {
vals[i] = getOutputFormat().attribute(i).indexOfValue(replace);
}
}
}
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy
}
return true;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String selectedAttributesTipText() {
return "The attributes (index range string or explicit "
+ "comma-separated attribute names) to work on";
}
public void setSelectedAttributes(String atts) {
m_selectedColsString = atts;
}
public String getSelectedAttributes() {
return m_selectedColsString;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String valueReplacementsTipText() {
return "A comma separated list of values to replace and their "
+ "replacements. E.g. red:green, blue:purple, fred:bob";
}
public void setValueReplacements(String v) {
m_renameVals = v;
}
public String getValueReplacements() {
return m_renameVals;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Determines whether to apply the operation to the specified."
+ " attributes, or all attributes but the specified ones."
+ " If set to true, all attributes but the speficied ones will be affected.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_invert;
}
/**
* Set whether selected columns should be removed or kept. If true the
* selected columns are kept and unselected columns are deleted. If false
* selected columns are deleted and unselected columns are kept.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_invert = invert;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoreCaseTipText() {
return "Whether to ignore case when matching nominal values";
}
public void setIgnoreCase(boolean ignore) {
m_ignoreCase = ignore;
}
public boolean getIgnoreCase() {
return m_ignoreCase;
}
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector
.addElement(new Option(
"\tAttributes to act on. Can be either a range\n"
+ "\tstring (e.g. 1,2,6-10) OR a comma-separated list of named attributes\n\t"
+ "(default none)", "R", 1, "-R <1,2-4 | attName1,attName2,...>"));
newVector
.addElement(new Option(
"\tInvert matching sense (i.e. act on all attributes other than those specified)",
"V", 0, "-V"));
newVector.addElement(new Option(
"\tNominal labels and their replacement values.\n\t"
+ "E.g. red:blue, black:white, fred:bob", "N", 1,
"-N <label:label,label:label,...>"));
newVector.addElement(new Option(
"\tIgnore case when matching nominal values", "I", 0, "-I"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R
* Attributes to act on. Can be either a range
* string (e.g. 1,2,6-10) OR a comma-separated list of named attributes
* (default none)
* </pre>
*
* <pre>
* -V
* Invert matching sense (i.e. act on all attributes other than those specified)
* </pre>
*
* <pre>
* -N
* Nominal labels and their replacement values.
* E.g. red:blue, black:white, fred:bob
* </pre>
*
* <pre>
* -I
* Ignore case when matching nominal values
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String atts = Utils.getOption('R', options);
if (atts.length() > 0) {
setSelectedAttributes(atts);
}
String replacements = Utils.getOption('N', options);
if (replacements.length() > 0) {
setValueReplacements(replacements);
}
setInvertSelection(Utils.getFlag('V', options));
setIgnoreCase(Utils.getFlag('I', options));
Utils.checkForRemainingOptions(options);
}
@Override
public String[] getOptions() {
List<String> opts = new ArrayList<String>();
if (getSelectedAttributes() != null && getSelectedAttributes().length() > 0) {
opts.add("-R");
opts.add(getSelectedAttributes());
}
if (getInvertSelection()) {
opts.add("-V");
}
if (getValueReplacements() != null && getValueReplacements().length() > 0) {
opts.add("-N");
opts.add(getValueReplacements());
}
if (getIgnoreCase()) {
opts.add("-I");
}
return opts.toArray(new String[opts.size()]);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RenameNominalValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Reorder.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Reorder.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.*;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that generates output with a new order of
* the attributes. Useful if one wants to move an attribute to the end of the list of attributes to use it
* as class attribute (e.g., using "-R 2-last,1").<br/><br/>
* It is not only possible to change the order of the attributes. Attributes can also be left out.
* E.g. if you have 10 attributes, you can
* generate the following output order: 1,3,5,7,9,10 or 10,1-5.<br/><br/>
* You can also duplicate attributes, e.g., for further processing later on: e.g., using
* 1,1,1,4,4,4,2,2,2 if one needs to process two copies of the attributes with other filters but also
* needs to keep the original attributes.<br/><br/>
* One can simply reverse the order of the attributes via 'last-first'.<br/><br/>
* After applying the filter, the index of the class attribute is set to the index of the last
* attribute.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specifies the order of the attributes (default first-last).
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Reorder extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -1135571321097202292L;
/** Stores which columns to reorder */
protected String m_NewOrderCols = "first-last";
/**
* Stores the indexes of the selected attributes in order, once the dataset is
* seen
*/
protected int[] m_SelectedAttributes;
/**
* Contains an index of string attributes in the input format that survive the
* filtering process -- some entries may be duplicated
*/
protected int[] m_InputStringIndex;
/**
* Whether to set all attribute weights to 1.0 in the reordered data.
*/
protected boolean m_setAllAttributeWeightsToOne;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option(
"\tSpecifies the order of the attributes (default first-last).", "R", 1,
"-R <index1,index2-index4,...>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <index1,index2-index4,...>
* Specifies the order of the attributes (default first-last).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String orderList = Utils.getOption('R', options);
if (orderList.length() != 0) {
setAttributeIndices(orderList);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (!getAttributeIndices().equals("")) {
options.add("-R");
options.add(getAttributeIndices());
}
return options.toArray(new String[0]);
}
/**
* parses the index string and returns the corresponding int index
*
* @param s the index string to parse
* @param numAttributes necessary for "last" and OutOfBounds checks
* @return the int index determined form the index string
* @throws Exception if index is not valid
*/
protected int determineIndex(String s, int numAttributes) throws Exception {
int result;
if (s.equals("first")) {
result = 0;
} else if (s.equals("last")) {
result = numAttributes - 1;
} else {
result = Integer.parseInt(s) - 1;
}
// out of bounds?
if ((result < 0) || (result > numAttributes - 1)) {
throw new IllegalArgumentException("'" + s
+ "' is not a valid index for the range '1-" + numAttributes + "'!");
}
return result;
}
/**
* parses the range string and returns an array with the indices
*
* @param numAttributes necessary for "last" and OutOfBounds checks
* @return the indices determined form the range string
* @see #m_NewOrderCols
* @throws Exception if range is not valid
*/
protected int[] determineIndices(int numAttributes) throws Exception {
int[] result;
Vector<Integer> list;
int i;
StringTokenizer tok;
String token;
String[] range;
int from;
int to;
list = new Vector<Integer>();
// parse range
tok = new StringTokenizer(m_NewOrderCols, ",");
while (tok.hasMoreTokens()) {
token = tok.nextToken();
if (token.indexOf("-") > -1) {
range = token.split("-");
if (range.length != 2) {
throw new IllegalArgumentException("'" + token
+ "' is not a valid range!");
}
from = determineIndex(range[0], numAttributes);
to = determineIndex(range[1], numAttributes);
if (from <= to) {
for (i = from; i <= to; i++) {
list.add(i);
}
} else {
for (i = from; i >= to; i--) {
list.add(i);
}
}
} else {
list.add(determineIndex(token, numAttributes));
}
}
// turn vector into int array
result = new int[list.size()];
for (i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attribute
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.NO_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
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 a problem occurs setting the input format
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
// An array to keep track of how of how often each attribute is chosen
int[] frequency = new int[instanceInfo.numAttributes()];
m_SelectedAttributes = determineIndices(instanceInfo.numAttributes());
boolean atLeastOneAttributeOccursMoreThanOnce = false;
for (int current : m_SelectedAttributes) {
frequency[current]++;
if (frequency[current] > 1) {
if (current == instanceInfo.classIndex()) {
throw new IllegalArgumentException("Reorder filter: Cannot duplicate class attribute");
}
atLeastOneAttributeOccursMoreThanOnce = true;
break;
}
}
Arrays.fill(frequency, 0);
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
int outputClass = -1;
for (int current : m_SelectedAttributes) {
if (instanceInfo.classIndex() == current) {
outputClass = attributes.size();
}
String newName = instanceInfo.attribute(current).name();
if (atLeastOneAttributeOccursMoreThanOnce) {
newName += "_" + (++frequency[current]); // Make sure attribute names in filtered data are unique
}
Attribute keep = (Attribute) instanceInfo.attribute(current).copy(newName);
if (m_setAllAttributeWeightsToOne) {
keep.setWeight(1.0);
}
attributes.add(keep);
}
initInputLocators(instanceInfo, m_SelectedAttributes);
Instances outputFormat = new Instances(instanceInfo.relationName(),
attributes, 0);
outputFormat.setClassIndex(outputClass);
setOutputFormat(outputFormat);
return true;
}
/**
* Whether to set all attribute weights to one in output data.
*/
public void setAllAttributeWeightsToOne(boolean b) {
m_setAllAttributeWeightsToOne = b;
}
/**
* 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.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
double[] vals = new double[outputFormatPeek().numAttributes()];
for (int i = 0; i < m_SelectedAttributes.length; i++) {
int current = m_SelectedAttributes[i];
vals[i] = instance.value(current);
}
Instance inst = null;
if (instance instanceof SparseInstance) {
inst = new SparseInstance(instance.weight(), vals);
} else {
inst = new DenseInstance(instance.weight(), vals);
}
copyValues(inst, false, instance.dataset(), outputFormatPeek());
push(inst); // No need to copy
return true;
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that generates output with a new order of the "
+ "attributes. Useful if one wants to move an attribute to the end of the list of attributes to "
+ "use it as class attribute (e.g., using \"-R 2-last,1\").\n\n"
+ "It is not only possible to change the order of the attributes. "
+ "Attributes can also be left out. E.g. if you have 10 attributes, you "
+ "can generate the following output order: 1,3,5,7,9,10 or 10,1-5.\n\n"
+ "You can also duplicate attributes, e.g., for further processing later "
+ "on: e.g., using 1,1,1,4,4,4,2,2,2 if one needs to process two copies of the attributes "
+ "with other filters but also needs to keep the original attributes.\n\n"
+ "One can simply reverse the order of the attributes via 'last-first'.\n\n"
+ "After applying the filter, the index of the class attribute is set to the index of the "
+ "last attribute.";
}
/**
* Get the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_NewOrderCols;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last<br>
* Note: use this method before you call
* <code>setInputFormat(Instances)</code>, since the output format is
* determined in that method.
* @throws Exception if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) throws Exception {
// simple test
if (rangeList.replaceAll("[afilrst0-9\\-,]*", "").length() != 0) {
throw new IllegalArgumentException("Not a valid range string!");
}
m_NewOrderCols = rangeList;
}
/**
* Set which attributes are to be copied (or kept if invert is true)
*
* @param attributes an array containing indexes of attributes to select.
* Since the array will typically come from a program, attributes are
* indexed from 0.<br>
* Note: use this method before you call
* <code>setInputFormat(Instances)</code>, since the output format is
* determined in that method.
* @throws Exception if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) throws Exception {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Reorder(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ReplaceMissingValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ReplaceMissingValues.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Sourcable;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Replaces all missing values for nominal and numeric attributes in a dataset with the modes and means
* from the training data. The class attribute is skipped by default.
* <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>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class ReplaceMissingValues extends PotentialClassIgnorer implements UnsupervisedFilter, Sourcable, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 8349568310991609867L;
/** The modes and means */
private double[] m_ModesAndMeans = null;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Replaces all missing values for nominal and numeric attributes in a " + "dataset with the modes and means from the training data. The class attribute is skipped by default.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
this.m_ModesAndMeans = null;
return true;
}
/**
* Input an instance for filtering. Filter requires all
* training 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 set.
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.m_ModesAndMeans == null) {
this.bufferInput(instance);
return false;
} else {
this.convertInstance(instance);
return true;
}
}
/**
* Signify 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 InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_ModesAndMeans == null) {
// Compute modes and means
double sumOfWeights = this.getInputFormat().sumOfWeights();
double[][] counts = new double[this.getInputFormat().numAttributes()][];
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
if (this.getInputFormat().attribute(i).isNominal()) {
counts[i] = new double[this.getInputFormat().attribute(i).numValues()];
if (counts[i].length > 0) {
counts[i][0] = sumOfWeights;
}
}
}
double[] sums = new double[this.getInputFormat().numAttributes()];
for (int i = 0; i < sums.length; i++) {
sums[i] = sumOfWeights;
}
double[] results = new double[this.getInputFormat().numAttributes()];
for (int j = 0; j < this.getInputFormat().numInstances(); j++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Instance inst = this.getInputFormat().instance(j);
for (int i = 0; i < inst.numValues(); i++) {
if (!inst.isMissingSparse(i)) {
double value = inst.valueSparse(i);
if (inst.attributeSparse(i).isNominal()) {
if (counts[inst.index(i)].length > 0) {
counts[inst.index(i)][(int) value] += inst.weight();
counts[inst.index(i)][0] -= inst.weight();
}
} else if (inst.attributeSparse(i).isNumeric()) {
results[inst.index(i)] += inst.weight() * inst.valueSparse(i);
}
} else {
if (inst.attributeSparse(i).isNominal()) {
if (counts[inst.index(i)].length > 0) {
counts[inst.index(i)][0] -= inst.weight();
}
} else if (inst.attributeSparse(i).isNumeric()) {
sums[inst.index(i)] -= inst.weight();
}
}
}
}
this.m_ModesAndMeans = new double[this.getInputFormat().numAttributes()];
for (int i = 0; i < this.getInputFormat().numAttributes(); i++) {
if (this.getInputFormat().attribute(i).isNominal()) {
if (counts[i].length == 0) {
this.m_ModesAndMeans[i] = Utils.missingValue();
} else {
this.m_ModesAndMeans[i] = Utils.maxIndex(counts[i]);
}
} else if (this.getInputFormat().attribute(i).isNumeric()) {
if (Utils.gr(sums[i], 0)) {
this.m_ModesAndMeans[i] = results[i] / sums[i];
}
}
}
// Convert pending input instances
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
this.convertInstance(this.getInputFormat().instance(i));
}
}
// Free memory
this.flushInput();
this.m_NewBatch = true;
return (this.numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is
* added to the end of the output queue.
*
* @param instance the instance to convert
*/
private void convertInstance(final Instance instance) {
Instance inst = null;
if (instance instanceof SparseInstance) {
double[] vals = new double[instance.numValues()];
int[] indices = new int[instance.numValues()];
int num = 0;
for (int j = 0; j < instance.numValues(); j++) {
if (instance.isMissingSparse(j) && (this.getInputFormat().classIndex() != instance.index(j)) && (instance.attributeSparse(j).isNominal() || instance.attributeSparse(j).isNumeric())) {
if (this.m_ModesAndMeans[instance.index(j)] != 0.0) {
vals[num] = this.m_ModesAndMeans[instance.index(j)];
indices[num] = instance.index(j);
num++;
}
} else {
vals[num] = instance.valueSparse(j);
indices[num] = instance.index(j);
num++;
}
}
if (num == instance.numValues()) {
inst = new SparseInstance(instance.weight(), vals, indices, instance.numAttributes());
} else {
double[] tempVals = new double[num];
int[] tempInd = new int[num];
System.arraycopy(vals, 0, tempVals, 0, num);
System.arraycopy(indices, 0, tempInd, 0, num);
inst = new SparseInstance(instance.weight(), tempVals, tempInd, instance.numAttributes());
}
} else {
double[] vals = new double[this.getInputFormat().numAttributes()];
for (int j = 0; j < instance.numAttributes(); j++) {
if (instance.isMissing(j) && (this.getInputFormat().classIndex() != j) && (this.getInputFormat().attribute(j).isNominal() || this.getInputFormat().attribute(j).isNumeric())) {
vals[j] = this.m_ModesAndMeans[j];
} else {
vals[j] = instance.value(j);
}
}
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
this.push(inst, false); // No need to copy
}
/**
* Returns a string that describes the filter as source. The
* filter will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain two methods with these signatures:
* <pre><code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
@Override
public String toSource(final String className, final Instances data) throws Exception {
StringBuffer result;
boolean[] numeric;
boolean[] nominal;
String[] modes;
double[] means;
int i;
result = new StringBuffer();
// determine what attributes were processed
numeric = new boolean[data.numAttributes()];
nominal = new boolean[data.numAttributes()];
modes = new String[data.numAttributes()];
means = new double[data.numAttributes()];
for (i = 0; i < data.numAttributes(); i++) {
numeric[i] = (data.attribute(i).isNumeric() && (i != data.classIndex()));
nominal[i] = (data.attribute(i).isNominal() && (i != data.classIndex()));
if (numeric[i]) {
means[i] = this.m_ModesAndMeans[i];
} else {
means[i] = Double.NaN;
}
if (nominal[i]) {
modes[i] = data.attribute(i).value((int) this.m_ModesAndMeans[i]);
} else {
modes[i] = null;
}
}
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /** lists which numeric attributes will be processed */\n");
result.append(" protected final static boolean[] NUMERIC = new boolean[]{" + Utils.arrayToString(numeric) + "};\n");
result.append("\n");
result.append(" /** lists which nominal attributes will be processed */\n");
result.append(" protected final static boolean[] NOMINAL = new boolean[]{" + Utils.arrayToString(nominal) + "};\n");
result.append("\n");
result.append(" /** the means */\n");
result.append(" protected final static double[] MEANS = new double[]{" + Utils.arrayToString(means).replaceAll("NaN", "Double.NaN") + "};\n");
result.append("\n");
result.append(" /** the modes */\n");
result.append(" protected final static String[] MODES = new String[]{");
for (i = 0; i < modes.length; i++) {
if (i > 0) {
result.append(",");
}
if (nominal[i]) {
result.append("\"" + Utils.quote(modes[i]) + "\"");
} else {
result.append(modes[i]);
}
}
result.append("};\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" Object[] result;\n");
result.append("\n");
result.append(" result = new Object[i.length];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" if (i[n] == null) {\n");
result.append(" if (NUMERIC[n])\n");
result.append(" result[n] = MEANS[n];\n");
result.append(" else if (NOMINAL[n])\n");
result.append(" result[n] = MODES[n];\n");
result.append(" else\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" else {\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" Object[][] result;\n");
result.append("\n");
result.append(" result = new Object[i.length][];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" result[n] = filter(i[n]);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter:
* use -h for help
*/
public static void main(final String[] argv) {
runFilter(new ReplaceMissingValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ReplaceMissingWithUserConstant.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ReplaceMissingWithUserConstant.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Replaces all missing values for nominal, string,
* numeric and date attributes in the dataset with user-supplied constant
* values.
* <p/>
* <!-- globalinfo-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class ReplaceMissingWithUserConstant extends PotentialClassIgnorer
implements UnsupervisedFilter, StreamableFilter, EnvironmentHandler,
WeightedInstancesHandler, WeightedAttributesHandler {
/** For serialization */
private static final long serialVersionUID = -7334039452189350356L;
/** Environment variables */
protected transient Environment m_env;
/** Range of columns to consider */
protected Range m_selectedRange;
protected String m_range = "first-last";
protected String m_resolvedRange = "";
/** Constant for replacing missing values in nominal/string atts with */
protected String m_nominalStringConstant = "";
/** Replacement value for nominal/string atts after resolving environment vars */
protected String m_resolvedNominalStringConstant = "";
/** Constant for replacing missing values in numeric attributes with */
protected String m_numericConstant = "0";
/** Replacement value for numeric atts after resolving environment vars */
protected String m_resolvedNumericConstant = "";
/** Parsed numeric constant value */
protected double m_numericConstVal = 0;
/** Constant for replacing missing values in date attributes with */
protected String m_dateConstant = "";
/** Replacement value for date atts after resolving environment vars */
protected String m_resolvedDateConstant = "";
/** Parsed date value as a double */
protected double m_dateConstVal = 0;
/** Formatting string to use for parsing the date constant */
protected String m_defaultDateFormat = "yyyy-MM-dd'T'HH:mm:ss";
/** Formatting string after resolving environment vars */
protected String m_resolvedDateFormat = "";
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Replaces all missing values for nominal, string, numeric and date "
+ "attributes in the dataset with user-supplied constant values.";
}
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
@Override
public Enumeration<Option> listOptions() {
Vector<Option> opts = new Vector<Option>(5);
opts
.addElement(new Option(
"\tSpecify list of attributes to replace missing values for "
+ "\n\t(as weka range list of indices or a comma separated list of attribute names).\n"
+ "\t(default: consider all attributes)", "R", 1,
"-A <index1,index2-index4,... | att-name1,att-name2,...>"));
opts.addElement(new Option(
"\tSpecify the replacement constant for nominal/string attributes", "N",
1, "-N"));
opts.addElement(new Option(
"\tSpecify the replacement constant for numeric attributes"
+ "\n\t(default: 0)", "R", 1, "-R"));
opts.addElement(new Option(
"\tSpecify the replacement constant for date attributes", "D", 1, "-D"));
opts.addElement(new Option(
"\tSpecify the date format for parsing the replacement date constant"
+ "\n\t(default: yyyy-MM-dd'T'HH:mm:ss)", "F", 1, "-F"));
opts.addAll(Collections.list(super.listOptions()));
return opts.elements();
}
/**
*
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -A <index1,index2-index4,... | att-name1,att-name2,...>
* Specify list of attributes to replace missing values for
* (as weka range list of indices or a comma separated list of attribute names).
* (default: consider all attributes)
* </pre>
*
* <pre>
* -N
* Specify the replacement constant for nominal/string attributes
* </pre>
*
* <pre>
* -R
* Specify the replacement constant for numeric attributes
* (default: 0)
* </pre>
*
* <pre>
* -D
* Specify the replacement constant for date attributes
* </pre>
*
* <pre>
* -F
* Specify the date format for parsing the replacement date constant
* (default: yyyy-MM-dd'T'HH:mm:ss)
* </pre>
*
* <pre>
* -unset-class-temporarily
* Unsets the class index temporarily before the filter is
* applied to the data.
* (default: no)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String atts = Utils.getOption('A', options);
if (atts.length() > 0) {
setAttributes(atts);
}
String nomString = Utils.getOption('N', options);
if (nomString.length() > 0) {
setNominalStringReplacementValue(nomString);
}
String numString = Utils.getOption('R', options);
if (numString.length() > 0) {
setNumericReplacementValue(numString);
}
String dateString = Utils.getOption('D', options);
if (dateString.length() > 0) {
setDateReplacementValue(dateString);
}
String formatString = Utils.getOption('F', options);
if (formatString.length() > 0) {
setDateFormat(formatString);
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
@Override
public String[] getOptions() {
ArrayList<String> options = new ArrayList<String>();
if (getAttributes().length() > 0) {
options.add("-A");
options.add(getAttributes());
}
if (getNominalStringReplacementValue().length() > 0) {
options.add("-N");
options.add(getNominalStringReplacementValue());
}
if (getNumericReplacementValue().length() > 0) {
options.add("-R");
options.add(getNumericReplacementValue());
}
if (getDateReplacementValue().length() > 0) {
options.add("-D");
options.add(getDateReplacementValue());
}
if (getDateFormat().length() > 0) {
options.add("-F");
options.add(getDateFormat());
}
Collections.addAll(options, super.getOptions());
return options.toArray(new String[1]);
}
/**
* Tip text for this property suitable for displaying in the GUI.
*
* @return the tip text for this property.
*/
public String attributesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\". Can alternatively"
+ " specify a comma separated list of attribute names. Note that "
+ " you can't mix indices and attribute names in the same list";
}
/**
* Set the list of attributes to consider for replacing missing values
*
* @param range the list of attributes to consider
*/
public void setAttributes(String range) {
m_range = range;
}
/**
* Get the list of attributes to consider for replacing missing values
*
* @return the list of attributes to consider
*/
public String getAttributes() {
return m_range;
}
/**
* Tip text for this property suitable for displaying in the GUI.
*
* @return the tip text for this property.
*/
public String nominalStringReplacementValueTipText() {
return "The constant to replace missing values in nominal/string attributes with";
}
/**
* Get the nominal/string replacement value
*
* @return the nominal/string replacement value
*/
public String getNominalStringReplacementValue() {
return m_nominalStringConstant;
}
/**
* Set the nominal/string replacement value
*
* @param nominalStringConstant the nominal/string constant to use
*/
public void setNominalStringReplacementValue(String nominalStringConstant) {
m_nominalStringConstant = nominalStringConstant;
}
/**
* Tip text for this property suitable for displaying in the GUI.
*
* @return the tip text for this property.
*/
public String numericReplacementValueTipText() {
return "The constant to replace missing values in numeric attributes with";
}
/**
* Get the numeric replacement value
*
* @return the numeric replacement value
*/
public String getNumericReplacementValue() {
return m_numericConstant;
}
/**
* Set the numeric replacement value
*
* @param numericConstant the numeric replacement value
*/
public void setNumericReplacementValue(String numericConstant) {
m_numericConstant = numericConstant;
}
/**
* Tip text for this property suitable for displaying in the GUI.
*
* @return the tip text for this property.
*/
public String dateReplacementValueTipText() {
return "The constant to replace missing values in date attributes with";
}
/**
* Set the date replacement value
*
* @param dateConstant the date replacement value
*/
public void setDateReplacementValue(String dateConstant) {
m_dateConstant = dateConstant;
}
/**
* Get the date replacement value
*
* @return the date replacement value
*/
public String getDateReplacementValue() {
return m_dateConstant;
}
/**
* Tip text for this property suitable for displaying in the GUI.
*
* @return the tip text for this property.
*/
public String dateFormatTipText() {
return "The formatting string to use for parsing the date replacement value";
}
/**
* Set the date format to use for parsing the date replacement constant
*
* @param dateFormat the date format to use
*/
public void setDateFormat(String dateFormat) {
m_defaultDateFormat = dateFormat;
}
/**
* Get the date format to use for parsing the date replacement constant
*
* @return the date format to use
*/
public String getDateFormat() {
return m_defaultDateFormat;
}
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_resolvedNominalStringConstant = m_nominalStringConstant;
m_resolvedNumericConstant = m_numericConstant;
m_resolvedDateConstant = m_dateConstant;
m_resolvedDateFormat = m_defaultDateFormat;
m_resolvedRange = m_range;
if (m_env == null) {
m_env = Environment.getSystemWide();
}
try {
if (m_resolvedNominalStringConstant != null
&& m_resolvedNominalStringConstant.length() > 0) {
m_resolvedNominalStringConstant = m_env
.substitute(m_resolvedNominalStringConstant);
}
if (m_resolvedNumericConstant != null
&& m_resolvedNumericConstant.length() > 0) {
m_resolvedNumericConstant = m_env.substitute(m_resolvedNumericConstant);
}
if (m_resolvedDateConstant != null && m_resolvedDateConstant.length() > 0) {
m_resolvedDateConstant = m_env.substitute(m_resolvedDateConstant);
}
if (m_resolvedDateFormat != null && m_resolvedDateFormat.length() > 0) {
m_resolvedDateFormat = m_env.substitute(m_resolvedDateFormat);
}
if (m_resolvedRange != null && m_resolvedRange.length() > 0) {
m_resolvedRange = m_env.substitute(m_resolvedRange);
}
} catch (Exception ex) {
}
// try and set up a Range first directly from the supplied string
m_selectedRange = new Range(m_resolvedRange);
try {
m_selectedRange.setUpper(instanceInfo.numAttributes() - 1);
} catch (IllegalArgumentException e) {
// now try as a list of named attributes
String[] parts = m_resolvedRange.split(",");
if (parts.length == 0) {
throw new Exception(
"Must specify which attributes to replace missing values for!");
}
StringBuffer indexList = new StringBuffer();
for (String att : parts) {
att = att.trim();
Attribute a = instanceInfo.attribute(att);
if (a == null) {
throw new Exception("I can't find the requested attribute '" + att
+ "' in the incoming instances.");
}
indexList.append(",").append(a.index() + 1);
}
String result = indexList.toString();
result = result.substring(1, result.length());
m_selectedRange = new Range(result);
m_selectedRange.setUpper(instanceInfo.numAttributes() - 1);
}
boolean hasNominal = false;
boolean hasString = false;
boolean hasNumeric = false;
boolean hasDate = false;
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (m_selectedRange.isInRange(i)) {
if (instanceInfo.attribute(i).isNominal()) {
hasNominal = true;
} else if (instanceInfo.attribute(i).isString()) {
hasString = true;
} else if (instanceInfo.attribute(i).isDate()) {
hasDate = true;
} else if (instanceInfo.attribute(i).isNumeric()) {
hasNumeric = true;
}
}
}
if (hasNominal || hasString) {
if (m_resolvedNominalStringConstant == null
|| m_resolvedNominalStringConstant.length() == 0) {
if (m_resolvedNumericConstant != null
&& m_resolvedNumericConstant.length() > 0) {
// use the supplied numeric constant as a nominal value
m_resolvedNominalStringConstant = "" + m_resolvedNumericConstant;
} else {
throw new Exception("Data contains nominal/string attributes and no "
+ "replacement constant has been supplied");
}
}
}
if (hasNumeric) {
if (m_numericConstant == null || m_numericConstant.length() == 0) {
if (m_resolvedNominalStringConstant != null
&& m_resolvedNominalStringConstant.length() > 0) {
// use the supplied nominal constant as numeric replacement
// value (if we can parse it as a number)
try {
Double.parseDouble(m_resolvedNominalStringConstant);
m_resolvedNumericConstant = m_resolvedNominalStringConstant;
} catch (NumberFormatException e) {
throw new Exception(
"Data contains numeric attributes and no numeric "
+ "constant has been supplied. Unable to parse nominal "
+ "constant as a number either.");
}
} else {
throw new Exception("Data contains numeric attributes and no "
+ "replacement constant has been supplied");
}
}
try {
m_numericConstVal = Double.parseDouble(m_resolvedNumericConstant);
} catch (NumberFormatException e) {
throw new Exception("Unable to parse numeric constant");
}
}
if (hasDate) {
if (m_resolvedDateConstant == null
|| m_resolvedDateConstant.length() == 0) {
throw new Exception(
"Data contains date attributes and no replacement constant has been "
+ "supplied");
}
SimpleDateFormat sdf = new SimpleDateFormat(m_resolvedDateFormat);
Date d = sdf.parse(m_resolvedDateConstant);
m_dateConstVal = d.getTime();
}
Instances outputFormat = new Instances(instanceInfo, 0);
// check for nominal attributes and add the supplied constant to the
// list of legal values (if necessary)
ArrayList<Attribute> updatedNoms = new ArrayList<Attribute>();
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i != instanceInfo.classIndex() && m_selectedRange.isInRange(i)) {
Attribute temp = instanceInfo.attribute(i);
if (temp.isNominal()) {
if (temp.indexOfValue(m_resolvedNominalStringConstant) < 0) {
List<String> values = new ArrayList<String>();
values.add(m_resolvedNominalStringConstant);
for (int j = 0; j < temp.numValues(); j++) {
values.add(temp.value(j));
}
Attribute newAtt = new Attribute(temp.name(), values);
newAtt.setWeight(temp.weight());
updatedNoms.add(newAtt);
}
}
}
}
if (updatedNoms.size() > 0) {
int nomCount = 0;
ArrayList<Attribute> atts = new ArrayList<Attribute>();
for (int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i != instanceInfo.classIndex() && m_selectedRange.isInRange(i)) {
if (instanceInfo.attribute(i).isNominal()) {
atts.add(updatedNoms.get(nomCount++));
} else {
atts.add(instanceInfo.attribute(i)); // Copy not necessary
}
} else {
atts.add(instanceInfo.attribute(i)); // Copy not necessary
}
}
outputFormat = new Instances(instanceInfo.relationName(), atts, 0);
outputFormat.setClassIndex(getInputFormat().classIndex());
}
setOutputFormat(outputFormat);
return true;
}
@Override
public boolean input(Instance inst) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
double[] vals = new double[inst.numAttributes()];
for (int i = 0; i < inst.numAttributes(); i++) {
if (inst.isMissing(i) && m_selectedRange.isInRange(i)) {
if (i != inst.classIndex()) {
if (inst.attribute(i).isDate()) {
vals[i] = m_dateConstVal;
} else if (inst.attribute(i).isNumeric()) {
vals[i] = m_numericConstVal;
} else if (inst.attribute(i).isNominal()) {
// vals[i] = inst.attribute(i).numValues();
int temp = inst.attribute(i).indexOfValue(
m_resolvedNominalStringConstant);
// vals[i] = (temp >= 0) ? temp : inst.attribute(i).numValues();
vals[i] = (temp >= 0) ? temp : 0;
} else if (inst.attribute(i).isString()) {
// a bit of a hack here to try and detect if we're running in
// streaming
// mode or batch mode. If the string attribute has only one value in
// the
// header then it is likely that we're running in streaming mode
// (where only one
// value, the current instance's value, is maintained in memory)
if (inst.attribute(i).numValues() <= 1) {
outputFormatPeek().attribute(i).setStringValue(
m_resolvedNominalStringConstant);
vals[i] = 0;
} else {
vals[i] = outputFormatPeek().attribute(i).addStringValue(
m_resolvedNominalStringConstant);
}
} else {
vals[i] = inst.value(i);
}
} else {
vals[i] = inst.value(i);
}
} else {
if (m_selectedRange.isInRange(i)) {
// in range but not missing
if (inst.attribute(i).isString()) {
// a bit of a hack here to try and detect if we're running in
// streaming
// mode or batch mode. If the string attribute has only one value in
// the
// header then it is likely that we're running in streaming mode
// (where only one
// value, the current instance's value, is maintained in memory)
if (inst.attribute(i).numValues() <= 1) {
outputFormatPeek().attribute(i).setStringValue(
inst.stringValue(i));
} else {
outputFormatPeek().attribute(i).addStringValue(
inst.stringValue(i));
}
vals[i] = outputFormatPeek().attribute(i).indexOfValue(
inst.stringValue(i));
} else if (inst.attribute(i).isNominal() && i != inst.classIndex()) {
// vals[i] = inst.value(i) + 1;
vals[i] = outputFormatPeek().attribute(i).indexOfValue(inst.stringValue(i));
} else {
vals[i] = inst.value(i);
}
} else {
// missing but not in range
vals[i] = inst.value(i);
}
}
}
Instance newInst = null;
if (inst instanceof SparseInstance) {
newInst = new SparseInstance(inst.weight(), vals);
} else {
newInst = new DenseInstance(inst.weight(), vals);
}
newInst.setDataset(getOutputFormat());
/*
* copyValues(newInst, false, inst.dataset(), getOutputFormat());
* newInst.setDataset(getOutputFormat());
*/
push(newInst, false); // No need to copy
return true;
}
@Override
public void setEnvironment(Environment env) {
m_env = env;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain arguments to the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new ReplaceMissingWithUserConstant(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/ReplaceWithMissingValue.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* ReplaceWithMissingValue.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.filters.SimpleBatchFilter;
import weka.filters.UnsupervisedFilter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
/**
* <!-- globalinfo-start -->
* A filter that can be used to introduce missing values in a dataset.
* The specified probability is used to flip a biased coin to decide whether to replace a particular
* attribute value in an instance with a missing value (i.e., a probability of 0.9 means 90% of values
* will be replaced with missing values). This filter only modifies the first batch of data that is processed.
* The class attribute is skipped by default.
* <br><br>
* <!-- globalinfo-end -->
*
* <!-- options-start -->
* Valid options are: <p>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of columns to modify. First and last are valid indexes.
* (default: first-last)</pre>
*
* <pre> -V
* Invert matching sense of column indexes.</pre>
*
* <pre> -S <num>
* Specify the random number seed (default 1)</pre>
*
* <pre> -P <double>
* Specify the probability (default 0.1)</pre>
*
* <pre> -unset-class-temporarily
* Unsets the class index temporarily before the filter is
* applied to the data.
* (default: no)</pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 10215 $
*/
public class ReplaceWithMissingValue extends SimpleBatchFilter
implements UnsupervisedFilter, Randomizable, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = -2356630932899796239L;
/** Stores which columns to turn into nominals */
protected Range m_Cols = new Range("first-last");
/** The default columns to turn into nominals */
protected String m_DefaultCols = "first-last";
/** The seed for the random number generator */
protected int m_Seed = 1;
/** The probability */
protected double m_Probability = 0.1;
/** True if the class is to be unset */
protected boolean m_IgnoreClass = false;
/**
* Gets an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>(4);
result.addElement(new Option(
"\tSpecifies list of columns to modify. 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(
"\tSpecify the random number seed (default 1)", "S", 1, "-S <num>"));
result.addElement(new Option(
"\tSpecify the probability (default 0.1)", "P", 1, "-P <double>"));
result.addElement(new Option(
"\tUnsets the class index temporarily before the filter is\n"
+ "\tapplied to the data.\n" + "\t(default: no)",
"unset-class-temporarily", 1, "-unset-class-temporarily"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start -->
* Valid options are: <p>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of columns to modify. First and last are valid indexes.
* (default: first-last)</pre>
*
* <pre> -V
* Invert matching sense of column indexes.</pre>
*
* <pre> -S <num>
* Specify the random number seed (default 1)</pre>
*
* <pre> -P <double>
* Specify the probability (default 0.1)</pre>
*
* <pre> -unset-class-temporarily
* Unsets the class index temporarily before the filter is
* applied to the data.
* (default: no)</pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
setInvertSelection(Utils.getFlag('V', options));
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices(m_DefaultCols);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
setSeed(Integer.parseInt(seedString));
} else {
setSeed(1);
}
String probString = Utils.getOption('P', options);
if (probString.length() != 0) {
setProbability(Double.parseDouble(probString));
} else {
setProbability(0.1);
}
setIgnoreClass(Utils.getFlag("unset-class-temporarily", options));
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (!getAttributeIndices().equals("")) {
result.add("-R");
result.add(getAttributeIndices());
}
if (getInvertSelection()) {
result.add("-V");
}
result.add("-S");
result.add("" + getSeed());
result.add("-P");
result.add("" + getProbability());
if (getIgnoreClass()) {
result.add("-unset-class-temporarily");
}
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String ignoreClassTipText() {
return "The class index will be unset temporarily before the filter is applied.";
}
/**
* Set the IgnoreClass value. Set this to true if the class index is to be
* unset before the filter is applied.
*
* @param newIgnoreClass The new IgnoreClass value.
*/
public void setIgnoreClass(boolean newIgnoreClass) {
m_IgnoreClass = newIgnoreClass;
}
/**
* Gets the IgnoreClass value. If this to true then the class index is to
* unset before the filter is applied.
*
* @return the current IgnoreClass value.
*/
public boolean getIgnoreClass() {
return m_IgnoreClass;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String probabilityTipText() {
return "Probability to use for replacement.";
}
/**
* Get the probability.
*
* @return the probability.
*/
public double getProbability() {
return m_Probability;
}
/**
* Set the probability to use.
*
* @param newProbability the probability to use.
*/
public void setProbability(double newProbability) {
m_Probability = newProbability;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "Seed for the random number generator.";
}
/**
* Get the random number generator seed value.
*
* @return random number generator seed value.
*/
public int getSeed() {
return m_Seed;
}
/**
* Set the random number generator seed value.
*
* @param newSeed value to use as the random number generator seed.
*/
public void setSeed(int newSeed) {
m_Seed = newSeed;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " attributes will be modified'; if"
+ " true, only non-selected attributes will be modified.";
}
/**
* Gets whether the supplied columns are to be worked on or the others.
*
* @return true if the supplied columns will be worked on
*/
public boolean getInvertSelection() {
return m_Cols.getInvert();
}
/**
* Sets whether selected columns should be worked on or all the others apart
* from these. If true all the other columns are considered for
* "nominalization".
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_Cols.setInvert(value);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_Cols.getRanges();
}
/**
* Sets which attributes are to be "nominalized" (only numeric attributes
* among the selection will be transformed).
*
* @param value a string representing the list of attributes. Since the string
* will typically come from a user, attributes are indexed from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String value) {
m_Cols.setRanges(value);
}
/**
* Sets which attributes are to be transoformed to nominal. (only numeric
* attributes among the selection will be transformed).
*
* @param value an array containing indexes of attributes to nominalize. Since
* the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] value) {
setAttributeIndices(Range.indicesToRangeList(value));
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capabilities.Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capabilities.Capability.MISSING_CLASS_VALUES);
result.enable(Capabilities.Capability.NO_CLASS);
return result;
}
/**
* returns true if the output format is immediately available after the input
* format has been set and not only after all the data has been seen (see
* batchFinished())
*
* @return true
*/
@Override
protected boolean hasImmediateOutputFormat() {
return true;
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat) throws Exception {
return inputFormat;
}
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A filter that can be used to introduce missing values in a dataset. The specified probability is used to" +
" flip a biased coin to decide whether to replace a particular attribute value in an instance with a" +
" missing value (i.e., a probability of 0.9 means 90% of values will be replaced with missing values). " +
"This filter only modifies the first batch of data that is processed. The class attribute is skipped by default.";
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
if (isFirstBatchDone()) {
return instances;
}
Instances newData = new Instances(instances, instances.numInstances());
Random random = new Random(getSeed());
m_Cols.setUpper(newData.numAttributes() - 1);
for (Instance inst : instances) {
double[] values = inst.toDoubleArray();
for (int i = 0; i < values.length; i++) {
if (m_Cols.isInRange(i) && (i != instances.classIndex() || getIgnoreClass())) {
if (random.nextDouble() < getProbability()) {
values[i] = Utils.missingValue();
}
}
}
if (inst instanceof SparseInstance) {
newData.add(new SparseInstance(inst.weight(), values));
} else {
newData.add(new DenseInstance(inst.weight(), values));
}
}
return newData;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 10215 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new ReplaceWithMissingValue(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/SortLabels.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SortLabels.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.attribute;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleStreamFilter;
/**
* <!-- globalinfo-start --> A simple filter for sorting the labels of nominal
* attributes.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of attributes to process.
* (default: select all nominal attributes)
* </pre>
*
* <pre>
* -V
* Inverts the matching sense of the selection.
* </pre>
*
* <pre>
* -S <CASE|NON-CASE>
* Determines the type of sorting:
* CASE = Case-sensitive
* NON-CASE = Case-insensitive
* (default: CASE)
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class SortLabels extends SimpleStreamFilter implements WeightedInstancesHandler, WeightedAttributesHandler{
/** for serialization. */
private static final long serialVersionUID = 7815204879694105691L;
/**
* Represents a case-sensitive comparator for two strings.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class CaseSensitiveComparator implements Comparator<String>,
Serializable {
/** for serialization. */
private static final long serialVersionUID = 7071450356783873277L;
/**
* compares the two strings, returns -1 if o1 is smaller than o2, 0 if equal
* and +1 if greater.
*
* @param o1 the first string to compare
* @param o2 the second string to compare
* @return returns -1 if o1 is smaller than o2, 0 if equal and +1 if greater
*/
@Override
public int compare(String o1, String o2) {
String s1;
String s2;
if ((o1 == null) && (o2 == null)) {
return 0;
} else if (o1 == null) {
return -1;
} else if (o2 == null) {
return +1;
}
s1 = o1;
s2 = o2;
return s1.compareTo(s2);
}
}
/**
* Represents a case-insensitive comparator for two strings.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class CaseInsensitiveComparator implements Comparator<String>,
Serializable {
/** for serialization. */
private static final long serialVersionUID = -4515292733342486066L;
/**
* compares the two strings, returns -1 if o1 is smaller than o2, 0 if equal
* and +1 if greater.
*
* @param o1 the first string to compare
* @param o2 the second string to compare
* @return returns -1 if o1 is smaller than o2, 0 if equal and +1 if greater
*/
@Override
public int compare(String o1, String o2) {
String s1;
String s2;
if ((o1 == null) && (o2 == null)) {
return 0;
} else if (o1 == null) {
return -1;
} else if (o2 == null) {
return +1;
}
s1 = o1;
s2 = o2;
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
/** sorts the strings case-sensitive. */
public final static int SORT_CASESENSITIVE = 0;
/** sorts the strings case-insensitive. */
public final static int SORT_CASEINSENSITIVE = 1;
/** Tag allowing selection of sort type. */
public final static Tag[] TAGS_SORTTYPE = {
new Tag(SORT_CASESENSITIVE, "case", "Case-sensitive"),
new Tag(SORT_CASEINSENSITIVE, "non-case", "Case-insensitive") };
/**
* the range of attributes to process (only relational ones will be
* processed).
*/
protected Range m_AttributeIndices = new Range("first-last");
/** the new order for the labels. */
protected int[][] m_NewOrder = null;
/** the sort type. */
protected int m_SortType = SORT_CASEINSENSITIVE;
/** the comparator to use for sorting. */
protected Comparator<String> m_Comparator = new CaseSensitiveComparator();
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "A simple filter for sorting the labels of nominal attributes.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSpecify list of attributes to process.\n"
+ "\t(default: select all nominal attributes)", "R", 1,
"-R <index1,index2-index4,...>"));
result.addElement(new Option(
"\tInverts the matching sense of the selection.", "V", 0, "-V"));
String desc = "";
for (Tag element : TAGS_SORTTYPE) {
SelectedTag tag = new SelectedTag(element.getID(), TAGS_SORTTYPE);
desc += "\t" + tag.getSelectedTag().getIDStr() + " = "
+ tag.getSelectedTag().getReadable() + "\n";
}
result.addElement(new Option("\tDetermines the type of sorting:\n" + desc
+ "\t(default: " + new SelectedTag(SORT_CASESENSITIVE, TAGS_SORTTYPE)
+ ")", "S", 1, "-S " + Tag.toOptionList(TAGS_SORTTYPE)));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses the options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Turns on output of debugging information.
* </pre>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of attributes to process.
* (default: select all nominal attributes)
* </pre>
*
* <pre>
* -V
* Inverts the matching sense of the selection.
* </pre>
*
* <pre>
* -S <CASE|NON-CASE>
* Determines the type of sorting:
* CASE = Case-sensitive
* NON-CASE = Case-insensitive
* (default: CASE)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0) {
setSortType(new SelectedTag(tmpStr, TAGS_SORTTYPE));
} else {
setSortType(new SelectedTag(SORT_CASESENSITIVE, TAGS_SORTTYPE));
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
result.add(getAttributeIndices());
if (getInvertSelection()) {
result.add("-V");
}
result.add("-S");
result.add("" + getSortType());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on; "
+ "this is a comma separated list of attribute indices, with "
+ "\"first\" and \"last\" valid values; Specify an inclusive "
+ "range with \"-\"; eg: \"first-3,5,6-10,last\".";
}
/**
* Set the range of attributes to process.
*
* @param value the new range.
*/
public void setAttributeIndices(String value) {
m_AttributeIndices = new Range(value);
}
/**
* Gets the current selected attributes.
*
* @return current selection.
*/
public String getAttributeIndices() {
return m_AttributeIndices.getRanges();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected "
+ "attributes in the range will be worked on; if "
+ "true, only non-selected attributes will be processed.";
}
/**
* Sets whether selected columns should be processed or skipped.
*
* @param value the new invert setting
*/
public void setInvertSelection(boolean value) {
m_AttributeIndices.setInvert(value);
}
/**
* Gets whether the supplied columns are to be processed or skipped.
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_AttributeIndices.getInvert();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String sortTypeTipText() {
return "The type of sorting to use.";
}
/**
* Sets the sort type to be used.
*
* @param type the type of sorting
*/
public void setSortType(SelectedTag type) {
if (type.getTags() == TAGS_SORTTYPE) {
m_SortType = type.getSelectedTag().getID();
if (m_SortType == SORT_CASESENSITIVE) {
m_Comparator = new CaseSensitiveComparator();
} else if (m_SortType == SORT_CASEINSENSITIVE) {
m_Comparator = new CaseInsensitiveComparator();
} else {
throw new IllegalStateException("Unhandled sort type '" + type + "'!");
}
}
}
/**
* Gets the sort type to be used.
*
* @return the sort type
*/
public SelectedTag getSortType() {
return new SelectedTag(m_SortType, TAGS_SORTTYPE);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
Instances result;
Attribute att;
Attribute attSorted;
ArrayList<Attribute> atts;
ArrayList<String> values;
Vector<String> sorted;
int i;
int n;
m_AttributeIndices.setUpper(inputFormat.numAttributes() - 1);
// determine sorted indices
atts = new ArrayList<Attribute>();
m_NewOrder = new int[inputFormat.numAttributes()][];
for (i = 0; i < inputFormat.numAttributes(); i++) {
att = inputFormat.attribute(i);
if (!att.isNominal() || !m_AttributeIndices.isInRange(i)) {
m_NewOrder[i] = new int[0];
atts.add((Attribute) inputFormat.attribute(i).copy());
continue;
}
// sort labels
sorted = new Vector<String>();
for (n = 0; n < att.numValues(); n++) {
sorted.add(att.value(n));
}
Collections.sort(sorted, m_Comparator);
// determine new indices
m_NewOrder[i] = new int[att.numValues()];
values = new ArrayList<String>();
for (n = 0; n < att.numValues(); n++) {
m_NewOrder[i][n] = sorted.indexOf(att.value(n));
values.add(sorted.get(n));
}
attSorted = new Attribute(att.name(), values);
attSorted.setWeight(att.weight());
atts.add(attSorted);
}
// generate new header
result = new Instances(inputFormat.relationName(), atts, 0);
result.setClassIndex(inputFormat.classIndex());
return result;
}
/**
* processes the given instance (may change the provided instance) and returns
* the modified version.
*
* @param instance the instance to process
* @return the modified data
* @throws Exception in case the processing goes wrong
*/
@Override
protected Instance process(Instance instance) throws Exception {
Instance result;
Attribute att;
double[] values;
int i;
// adjust indices
values = new double[instance.numAttributes()];
for (i = 0; i < instance.numAttributes(); i++) {
att = instance.attribute(i);
if (!att.isNominal() || !m_AttributeIndices.isInRange(i)
|| instance.isMissing(i)) {
values[i] = instance.value(i);
} else {
values[i] = m_NewOrder[i][(int) instance.value(i)];
}
}
// create new instance
result = new DenseInstance(instance.weight(), values);
// copy possible strings, relational values...
copyValues(result, false, instance.dataset(), outputFormatPeek());
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the filter with the given arguments.
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new SortLabels(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Standardize.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Standardize.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Sourcable;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Standardizes all numeric attributes in the given dataset to have zero mean and unit variance (apart from 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>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Standardize
extends PotentialClassIgnorer
implements UnsupervisedFilter, Sourcable, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -6830769026855053281L;
/** The means */
private double [] m_Means;
/** The variances */
private double [] m_StdDevs;
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Standardizes all numeric attributes in the given dataset "
+ "to have zero mean and unit variance (apart from the class attribute, if set).";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
m_Means = m_StdDevs = null;
return true;
}
/**
* Input an instance for filtering. Filter requires all
* training 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 set.
*/
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (m_Means == null) {
bufferInput(instance);
return false;
} else {
convertInstance(instance);
return true;
}
}
/**
* Signify 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 Exception if an error occurs
* @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_Means == null) {
Instances input = getInputFormat();
m_Means = new double[input.numAttributes()];
m_StdDevs = new double[input.numAttributes()];
for (int i = 0; i < input.numAttributes(); i++) {
if (input.attribute(i).isNumeric() &&
(input.classIndex() != i)) {
m_Means[i] = input.meanOrMode(i);
m_StdDevs[i] = Math.sqrt(input.variance(i));
}
}
// Convert pending input instances
for (int i = 0; i < input.numInstances(); i++) {
convertInstance(input.instance(i));
}
}
// Free memory
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Convert a single instance over. The converted instance is
* added to the end of the output queue.
*
* @param instance the instance to convert
* @exception Exception if an error occurs
*/
private void convertInstance(Instance instance) throws Exception {
Instance inst = null;
if (instance instanceof SparseInstance) {
double[] newVals = new double[instance.numAttributes()];
int[] newIndices = new int[instance.numAttributes()];
double[] vals = instance.toDoubleArray();
int ind = 0;
for (int j = 0; j < instance.numAttributes(); j++) {
double value;
if (instance.attribute(j).isNumeric() &&
(!Utils.isMissingValue(vals[j])) &&
(getInputFormat().classIndex() != j)) {
// Just subtract the mean if the standard deviation is zero
if (m_StdDevs[j] > 0) {
value = (vals[j] - m_Means[j]) / m_StdDevs[j];
} else {
value = vals[j] - m_Means[j];
}
if (Double.isNaN(value)) {
throw new Exception("A NaN value was generated "
+ "while standardizing attribute "
+ instance.attribute(j).name());
}
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
} else {
value = vals[j];
if (value != 0.0) {
newVals[ind] = value;
newIndices[ind] = j;
ind++;
}
}
}
double[] tempVals = new double[ind];
int[] tempInd = new int[ind];
System.arraycopy(newVals, 0, tempVals, 0, ind);
System.arraycopy(newIndices, 0, tempInd, 0, ind);
inst = new SparseInstance(instance.weight(), tempVals, tempInd,
instance.numAttributes());
} else {
double[] vals = instance.toDoubleArray();
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
if (instance.attribute(j).isNumeric() &&
(!Utils.isMissingValue(vals[j])) &&
(getInputFormat().classIndex() != j)) {
// Just subtract the mean if the standard deviation is zero
if (m_StdDevs[j] > 0) {
vals[j] = (vals[j] - m_Means[j]) / m_StdDevs[j];
} else {
vals[j] = (vals[j] - m_Means[j]);
}
if (Double.isNaN(vals[j])) {
throw new Exception("A NaN value was generated "
+ "while standardizing attribute "
+ instance.attribute(j).name());
}
}
}
inst = new DenseInstance(instance.weight(), vals);
}
inst.setDataset(instance.dataset());
push(inst, false); // No need to copy
}
/**
* Returns a string that describes the filter as source. The
* filter will be contained in a class with the given name (there may
* be auxiliary classes),
* and will contain two methods with these signatures:
* <pre><code>
* // converts one row
* public static Object[] filter(Object[] i);
* // converts a full dataset (first dimension is row index)
* public static Object[][] filter(Object[][] i);
* </code></pre>
* where the array <code>i</code> contains elements that are either
* Double, String, with missing values represented as null. The generated
* code is public domain and comes with no warranty.
*
* @param className the name that should be given to the source class.
* @param data the dataset used for initializing the filter
* @return the object source described by a string
* @throws Exception if the source can't be computed
*/
public String toSource(String className, Instances data) throws Exception {
StringBuffer result;
boolean[] process;
int i;
result = new StringBuffer();
// determine what attributes were processed
process = new boolean[data.numAttributes()];
for (i = 0; i < data.numAttributes(); i++) {
process[i] = (data.attribute(i).isNumeric() && (i != data.classIndex()));
}
result.append("class " + className + " {\n");
result.append("\n");
result.append(" /** lists which attributes will be processed */\n");
result.append(" protected final static boolean[] PROCESS = new boolean[]{" + Utils.arrayToString(process) + "};\n");
result.append("\n");
result.append(" /** the computed means */\n");
result.append(" protected final static double[] MEANS = new double[]{" + Utils.arrayToString(m_Means) + "};\n");
result.append("\n");
result.append(" /** the computed standard deviations */\n");
result.append(" protected final static double[] STDEVS = new double[]{" + Utils.arrayToString(m_StdDevs) + "};\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters a single row\n");
result.append(" * \n");
result.append(" * @param i the row to process\n");
result.append(" * @return the processed row\n");
result.append(" */\n");
result.append(" public static Object[] filter(Object[] i) {\n");
result.append(" Object[] result;\n");
result.append("\n");
result.append(" result = new Object[i.length];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" if (PROCESS[n] && (i[n] != null)) {\n");
result.append(" if (STDEVS[n] > 0)\n");
result.append(" result[n] = (((Double) i[n]) - MEANS[n]) / STDEVS[n];\n");
result.append(" else\n");
result.append(" result[n] = ((Double) i[n]) - MEANS[n];\n");
result.append(" }\n");
result.append(" else {\n");
result.append(" result[n] = i[n];\n");
result.append(" }\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("\n");
result.append(" /**\n");
result.append(" * filters multiple rows\n");
result.append(" * \n");
result.append(" * @param i the rows to process\n");
result.append(" * @return the processed rows\n");
result.append(" */\n");
result.append(" public static Object[][] filter(Object[][] i) {\n");
result.append(" Object[][] result;\n");
result.append("\n");
result.append(" result = new Object[i.length][];\n");
result.append(" for (int n = 0; n < i.length; n++) {\n");
result.append(" result[n] = filter(i[n]);\n");
result.append(" }\n");
result.append("\n");
result.append(" return result;\n");
result.append(" }\n");
result.append("}\n");
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter:
* use -h for help
*/
public static void main(String [] argv) {
runFilter(new Standardize(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/StringToNominal.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* StringToNominal.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Converts a range of string attributes (unspecified
* number of values) to nominal (set number of values). You should ensure that
* all string values that will appear are represented in the first batch of the
* data.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col>
* Sets the range of attribute indices ("first" and "last" are valid values
* and ranges and lists can also be used) (default "last").
* </pre>
*
* <pre>
* -V <col>
* Invert the range specified by -R.
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (len@reeltwo.com)
* @version $Revision$
*/
public class StringToNominal extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
private static final long serialVersionUID = 4864084427902797605L;
/** The attribute's range indices setting. */
private final Range m_AttIndices = new Range("last");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Converts a range of string attributes (unspecified number of values) to nominal "
+ "(set number of values). You should ensure that all string values that "
+ "will appear are represented in the first batch of the data.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if the selected attribute a
* string attribute.
* @throws Exception if the input format can't be set successfully.
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndices.setUpper(instanceInfo.numAttributes() - 1);
return false;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @param instance the input instance.
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input structure has been defined.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isOutputFormatDefined()) {
Instance newInstance = (Instance) instance.copy();
// make sure that we get the right indexes set for the converted
// string attributes when operating on a second batch of instances
for (int i = 0; i < newInstance.numAttributes(); i++) {
if (newInstance.attribute(i).isString() && !newInstance.isMissing(i)
&& m_AttIndices.isInRange(i)) {
Attribute outAtt = outputFormatPeek().attribute(i);
String inVal = newInstance.stringValue(i);
int outIndex = outAtt.indexOfValue(inVal);
if (outIndex < 0) {
newInstance.setMissing(i);
} else {
newInstance.setValue(i, outIndex);
}
}
}
push(newInstance, false); // No need to copy
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.
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isOutputFormatDefined()) {
setOutputFormat();
// Convert pending input instances
for (int i = 0; i < getInputFormat().numInstances(); i++) {
push((Instance) getInputFormat().instance(i).copy(), false); // No need to copy
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(1);
newVector.addElement(new Option(
"\tSets which attributes to process (\"first\" and \"last\" are valid values "
+ "and ranges and lists can also be used) (default \"last\").", "R", 1,
"-R <col>"));
newVector.addElement(new Option("\tInvert the range specified by -R.", "V",
1, "-V <col>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <col>
* Sets the range of attribute indices ("first" and "last" are valid values
* and ranges and lists can also be used) (default "last").
* </pre>
*
* <pre>
* -V <col>
* Invert the range specified by -R.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndices = Utils.getOption('R', options);
if (attIndices.length() != 0) {
setAttributeRange(attIndices);
} else {
setAttributeRange("last");
}
String invertSelection = Utils.getOption('V', options);
if (invertSelection.length() != 0) {
m_AttIndices.setInvert(true);
} else {
m_AttIndices.setInvert(false);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-R");
options.add("" + (getAttributeRange()));
if (this.m_AttIndices.getInvert()) {
options.add("-V");
}
return options.toArray(new String[0]);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeRangeTipText() {
return "Sets which attributes to process (\"first\" and \"last\" are valid values "
+ "and ranges and lists can also be used).";
}
/**
* Get the range of indices of the attributes used.
*
* @return the index of the attribute
*/
public String getAttributeRange() {
return m_AttIndices.getRanges();
}
/**
* Sets range of indices of the attributes used.
*
* @param rangeList the list of attribute indices
*/
public void setAttributeRange(String rangeList) {
m_AttIndices.setRanges(rangeList);
}
/**
* Set the output format. Takes the current average class values and
* m_InputFormat and calls setOutputFormat(Instances) appropriately.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts;
ArrayList<String> newVals;
// Compute new attributes
newAtts = new ArrayList<Attribute>(getInputFormat().numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (!m_AttIndices.isInRange(j) || !att.isString()) {
// We don't have to copy the attribute because the
// attribute index remains unchanged.
newAtts.add(att);
} else {
// Compute list of attribute values
newVals = new ArrayList<String>(att.numValues());
for (int i = 0; i < att.numValues(); i++) {
newVals.add(att.value(i));
}
Attribute newAtt = new Attribute(att.name(), newVals);
newAtt.setWeight(att.weight());
newAtts.add(newAtt);
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new StringToNominal(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/StringToWordVector.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* StringToWordVector.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.core.stopwords.StopwordsHandler;
import weka.core.stopwords.Null;
import weka.core.stemmers.NullStemmer;
import weka.core.stemmers.Stemmer;
import weka.core.tokenizers.Tokenizer;
import weka.core.tokenizers.WordTokenizer;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Converts string attributes into a set of numeric attributes representing word occurrence
* information from the text contained in the strings. The dictionary is determined from the first batch of data
* filtered (typically training data). Note that this filter is not strictly unsupervised when a class attribute is set
* because it creates a separate dictionary for each class and then merges them.
* <br><br>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p>
*
* <pre> -C
* Output word counts rather than boolean word presence.
* </pre>
*
* <pre> -R <index1,index2-index4,...>
* Specify list of string attributes to convert to words (as weka Range).
* (default: select all string attributes)</pre>
*
* <pre> -V
* Invert matching sense of column indexes.</pre>
*
* <pre> -P <attribute name prefix>
* Specify a prefix for the created attribute names.
* (default: "")</pre>
*
* <pre> -W <number of words to keep>
* Specify approximate number of word fields to create.
* Surplus words will be discarded..
* (default: 1000)</pre>
*
* <pre> -prune-rate <rate as a percentage of dataset>
* Specify the rate (e.g., every 10% of the input dataset) at which to periodically prune the dictionary.
* -W prunes after creating a full dictionary. You may not have enough memory for this approach.
* (default: no periodic pruning)</pre>
*
* <pre> -T
* Transform the word frequencies into log(1+fij)
* where fij is the frequency of word i in jth document(instance).
* </pre>
*
* <pre> -I
* Transform each word frequency into:
* fij*log(num of Documents/num of documents containing word i)
* where fij if frequency of word i in jth document(instance)</pre>
*
* <pre> -N
* Whether to 0=not normalize/1=normalize all data/2=normalize test data only
* to average length of training documents (default 0=don't normalize).</pre>
*
* <pre> -L
* Convert all tokens to lowercase before adding to the dictionary.</pre>
*
* <pre> -stopwords-handler
* The stopwords handler to use (default Null).</pre>
*
* <pre> -stemmer <spec>
* The stemming algorithm (classname plus parameters) to use.</pre>
*
* <pre> -M <int>
* The minimum term frequency (default = 1).</pre>
*
* <pre> -O
* If this is set, the maximum number of words and the
* minimum term frequency is not enforced on a per-class
* basis but based on the documents in all the classes
* (even if a class attribute is set).</pre>
*
* <pre> -tokenizer <spec>
* The tokenizing algorihtm (classname plus parameters) to use.
* (default: weka.core.tokenizers.WordTokenizer)</pre>
*
* <pre> -dictionary <path to save to>
* The file to save the dictionary to.
* (default is not to save the dictionary)</pre>
*
* <pre> -binary-dict
* Save the dictionary file as a binary serialized object
* instead of in plain text form. Use in conjunction with
* -dictionary</pre>
*
<!-- options-end -->
*
* @author Len Trigg (len@reeltwo.com)
* @author Stuart Inglis (stuart@reeltwo.com)
* @author Gordon Paynter (gordon.paynter@ucr.edu)
* @author Asrhaf M. Kibriya (amk14@cs.waikato.ac.nz)
* @version $Revision$
*/
public class StringToWordVector extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedInstancesHandler {
/** Used to build and manage the dictionary + vectorization */
protected DictionaryBuilder m_dictionaryBuilder = new DictionaryBuilder();
/** for serialization. */
static final long serialVersionUID = 8249106275278565424L;
/**
* The percentage at which to periodically prune the dictionary.
*/
private double m_PeriodicPruningRate = -1;
/** The normalization to apply. */
protected int m_filterType = FILTER_NONE;
/** normalization: No normalization. */
public static final int FILTER_NONE = 0;
/** normalization: Normalize all data. */
public static final int FILTER_NORMALIZE_ALL = 1;
/** normalization: Normalize test data only. */
public static final int FILTER_NORMALIZE_TEST_ONLY = 2;
/**
* Specifies whether document's (instance's) word frequencies are to be
* normalized. The are normalized to average length of documents specified as
* input format.
*/
public static final Tag[] TAGS_FILTER = {
new Tag(FILTER_NONE, "No normalization"),
new Tag(FILTER_NORMALIZE_ALL, "Normalize all data"),
new Tag(FILTER_NORMALIZE_TEST_ONLY, "Normalize test data only"), };
/** File to save the dictionary to */
protected File m_dictionaryFile = new File("-- set me --");
/**
* Whether to save the dictionary in serialized form rather than
* as plain text
*/
protected boolean m_dictionaryIsBinary;
/**
* Default constructor. Targets 1000 words in the output.
*/
public StringToWordVector() {
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result
.addElement(new Option(
"\tOutput word counts rather than boolean word presence.\n", "C", 0,
"-C"));
result.addElement(new Option(
"\tSpecify list of string attributes to convert to words (as weka Range).\n"
+ "\t(default: select all string attributes)", "R", 1,
"-R <index1,index2-index4,...>"));
result.addElement(new Option("\tInvert matching sense of column indexes.",
"V", 0, "-V"));
result.addElement(new Option(
"\tSpecify a prefix for the created attribute names.\n"
+ "\t(default: \"\")", "P", 1, "-P <attribute name prefix>"));
result.addElement(new Option(
"\tSpecify approximate number of word fields to create.\n"
+ "\tSurplus words will be discarded..\n" + "\t(default: 1000)", "W",
1, "-W <number of words to keep>"));
result
.addElement(new Option(
"\tSpecify the rate (e.g., every 10% of the input dataset) at which to periodically prune the dictionary.\n"
+ "\t-W prunes after creating a full dictionary. You may not have enough memory for this approach.\n"
+ "\t(default: no periodic pruning)", "prune-rate", 1,
"-prune-rate <rate as a percentage of dataset>"));
result
.addElement(new Option(
"\tTransform the word frequencies into log(1+fij)\n"
+ "\twhere fij is the frequency of word i in jth document(instance).\n",
"T", 0, "-T"));
result.addElement(new Option("\tTransform each word frequency into:\n"
+ "\tfij*log(num of Documents/num of documents containing word i)\n"
+ "\t where fij if frequency of word i in jth document(instance)", "I",
0, "-I"));
result
.addElement(new Option(
"\tWhether to 0=not normalize/1=normalize all data/2=normalize test data only\n"
+ "\tto average length of training documents "
+ "(default 0=don\'t normalize).", "N", 1, "-N"));
result.addElement(new Option("\tConvert all tokens to lowercase before "
+ "adding to the dictionary.", "L", 0, "-L"));
result.addElement(new Option("\tThe stopwords handler to use (default Null).",
"-stopwords-handler", 1, "-stopwords-handler"));
result.addElement(new Option(
"\tThe stemming algorithm (classname plus parameters) to use.",
"stemmer", 1, "-stemmer <spec>"));
result.addElement(new Option("\tThe minimum term frequency (default = 1).",
"M", 1, "-M <int>"));
result.addElement(new Option(
"\tIf this is set, the maximum number of words and the \n"
+ "\tminimum term frequency is not enforced on a per-class \n"
+ "\tbasis but based on the documents in all the classes \n"
+ "\t(even if a class attribute is set).", "O", 0, "-O"));
result.addElement(new Option(
"\tThe tokenizing algorithm (classname plus parameters) to use.\n"
+ "\t(default: " + WordTokenizer.class.getName() + ")", "tokenizer", 1,
"-tokenizer <spec>"));
result.addElement(new Option("\tThe file to save the dictionary to.\n"
+ "\t(default is not to save the dictionary)", "dictionary", 1,
"-dictionary <path to save to>"));
result.addElement(new Option("\tSave the dictionary file as a binary "
+ "serialized object\n\tinstead of in plain text form. Use in conjunction "
+ "with\n\t-dictionary", "binary-dict", 0, "-binary-dict"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
<!-- options-start -->
* Valid options are: <p>
*
* <pre> -C
* Output word counts rather than boolean word presence.
* </pre>
*
* <pre> -R <index1,index2-index4,...>
* Specify list of string attributes to convert to words (as weka Range).
* (default: select all string attributes)</pre>
*
* <pre> -V
* Invert matching sense of column indexes.</pre>
*
* <pre> -P <attribute name prefix>
* Specify a prefix for the created attribute names.
* (default: "")</pre>
*
* <pre> -W <number of words to keep>
* Specify approximate number of word fields to create.
* Surplus words will be discarded..
* (default: 1000)</pre>
*
* <pre> -prune-rate <rate as a percentage of dataset>
* Specify the rate (e.g., every 10% of the input dataset) at which to periodically prune the dictionary.
* -W prunes after creating a full dictionary. You may not have enough memory for this approach.
* (default: no periodic pruning)</pre>
*
* <pre> -T
* Transform the word frequencies into log(1+fij)
* where fij is the frequency of word i in jth document(instance).
* </pre>
*
* <pre> -I
* Transform each word frequency into:
* fij*log(num of Documents/num of documents containing word i)
* where fij if frequency of word i in jth document(instance)</pre>
*
* <pre> -N
* Whether to 0=not normalize/1=normalize all data/2=normalize test data only
* to average length of training documents (default 0=don't normalize).</pre>
*
* <pre> -L
* Convert all tokens to lowercase before adding to the dictionary.</pre>
*
* <pre> -stopwords-handler
* The stopwords handler to use (default Null).</pre>
*
* <pre> -stemmer <spec>
* The stemming algorithm (classname plus parameters) to use.</pre>
*
* <pre> -M <int>
* The minimum term frequency (default = 1).</pre>
*
* <pre> -O
* If this is set, the maximum number of words and the
* minimum term frequency is not enforced on a per-class
* basis but based on the documents in all the classes
* (even if a class attribute is set).</pre>
*
* <pre> -tokenizer <spec>
* The tokenizing algorihtm (classname plus parameters) to use.
* (default: weka.core.tokenizers.WordTokenizer)</pre>
*
* <pre> -dictionary <path to save to>
* The file to save the dictionary to.
* (default is not to save the dictionary)</pre>
*
* <pre> -binary-dict
* Save the dictionary file as a binary serialized object
* instead of in plain text form. Use in conjunction with
* -dictionary</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String value = Utils.getOption('R', options);
if (value.length() != 0) {
setSelectedRange(value);
} else {
setSelectedRange("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
value = Utils.getOption('P', options);
if (value.length() != 0) {
setAttributeNamePrefix(value);
} else {
setAttributeNamePrefix("");
}
value = Utils.getOption('W', options);
if (value.length() != 0) {
setWordsToKeep(Integer.valueOf(value).intValue());
} else {
setWordsToKeep(1000);
}
value = Utils.getOption("prune-rate", options);
if (value.length() > 0) {
setPeriodicPruning(Double.parseDouble(value));
} else {
setPeriodicPruning(-1);
}
value = Utils.getOption('M', options);
if (value.length() != 0) {
setMinTermFreq(Integer.valueOf(value).intValue());
} else {
setMinTermFreq(1);
}
setOutputWordCounts(Utils.getFlag('C', options));
setTFTransform(Utils.getFlag('T', options));
setIDFTransform(Utils.getFlag('I', options));
setDoNotOperateOnPerClassBasis(Utils.getFlag('O', options));
String nString = Utils.getOption('N', options);
if (nString.length() != 0) {
setNormalizeDocLength(new SelectedTag(Integer.parseInt(nString),
TAGS_FILTER));
} else {
setNormalizeDocLength(new SelectedTag(FILTER_NONE, TAGS_FILTER));
}
setLowerCaseTokens(Utils.getFlag('L', options));
String stemmerString = Utils.getOption("stemmer", options);
if (stemmerString.length() == 0) {
setStemmer(null);
} else {
String[] stemmerSpec = Utils.splitOptions(stemmerString);
if (stemmerSpec.length == 0) {
throw new Exception("Invalid stemmer specification string");
}
String stemmerName = stemmerSpec[0];
stemmerSpec[0] = "";
Stemmer stemmer = (Stemmer) Utils.forName(Class.forName("weka.core.stemmers.Stemmer"), stemmerName, stemmerSpec);
setStemmer(stemmer);
}
String stopwordsHandlerString = Utils.getOption("stopwords-handler", options);
if (stopwordsHandlerString.length() == 0) {
setStopwordsHandler(null);
} else {
String[] stopwordsHandlerSpec = Utils.splitOptions(stopwordsHandlerString);
if (stopwordsHandlerSpec.length == 0) {
throw new Exception("Invalid StopwordsHandler specification string");
}
String stopwordsHandlerName = stopwordsHandlerSpec[0];
stopwordsHandlerSpec[0] = "";
StopwordsHandler stopwordsHandler =
(StopwordsHandler) Utils.forName(Class.forName("weka.core.stopwords.StopwordsHandler"),
stopwordsHandlerName, stopwordsHandlerSpec);
setStopwordsHandler(stopwordsHandler);
}
String tokenizerString = Utils.getOption("tokenizer", options);
if (tokenizerString.length() == 0) {
setTokenizer(new WordTokenizer());
} else {
String[] tokenizerSpec = Utils.splitOptions(tokenizerString);
if (tokenizerSpec.length == 0) {
throw new Exception("Invalid tokenizer specification string");
}
String tokenizerName = tokenizerSpec[0];
tokenizerSpec[0] = "";
Tokenizer tokenizer = (Tokenizer) Utils.forName(Class.forName("weka.core.tokenizers.Tokenizer"), tokenizerName,
tokenizerSpec);
setTokenizer(tokenizer);
}
String dictFile = Utils.getOption("dictionary", options);
setDictionaryFileToSaveTo(new File(dictFile));
setSaveDictionaryInBinaryForm(Utils.getFlag("binary-dict", options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
result.add(getSelectedRange().getRanges());
if (getInvertSelection()) {
result.add("-V");
}
if (!"".equals(getAttributeNamePrefix())) {
result.add("-P");
result.add(getAttributeNamePrefix());
}
result.add("-W");
result.add(String.valueOf(getWordsToKeep()));
result.add("-prune-rate");
result.add(String.valueOf(getPeriodicPruning()));
if (getOutputWordCounts()) {
result.add("-C");
}
if (getTFTransform()) {
result.add("-T");
}
if (getIDFTransform()) {
result.add("-I");
}
result.add("-N");
result.add("" + m_filterType);
if (getLowerCaseTokens()) {
result.add("-L");
}
if (getStemmer() != null) {
result.add("-stemmer");
String spec = getStemmer().getClass().getName();
if (getStemmer() instanceof OptionHandler) {
spec += " "
+ Utils.joinOptions(((OptionHandler) getStemmer()).getOptions());
}
result.add(spec.trim());
}
if (getStopwordsHandler() != null) {
result.add("-stopwords-handler");
String spec = getStopwordsHandler().getClass().getName();
if (getStopwordsHandler() instanceof OptionHandler) {
spec += " "
+ Utils.joinOptions(((OptionHandler) getStopwordsHandler()).getOptions());
}
result.add(spec.trim());
}
result.add("-M");
result.add(String.valueOf(getMinTermFreq()));
if (getDoNotOperateOnPerClassBasis()) {
result.add("-O");
}
result.add("-tokenizer");
String spec = getTokenizer().getClass().getName();
if (getTokenizer() instanceof OptionHandler) {
spec += " "
+ Utils.joinOptions(((OptionHandler) getTokenizer()).getOptions());
}
result.add(spec.trim());
if (m_dictionaryFile != null && m_dictionaryFile.toString().length() > 0 &&
!m_dictionaryFile.toString().equalsIgnoreCase("-- set me --")) {
result.add("-dictionary");
result.add(m_dictionaryFile.toString());
if (getSaveDictionaryInBinaryForm()) {
result.add("-binary-dict");
}
}
return result.toArray(new String[result.size()]);
}
/**
* Constructor that allows specification of the target number of words in the
* output.
*
* @param wordsToKeep the number of words in the output vector (per class if
* assigned).
*/
public StringToWordVector(int wordsToKeep) {
m_dictionaryBuilder.setWordsToKeep(wordsToKeep);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_dictionaryBuilder.reset();
m_dictionaryBuilder.setSortDictionary(true);
m_dictionaryBuilder.setNormalize(false);
m_dictionaryBuilder.setup(instanceInfo);
return false;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
Instance inst = m_dictionaryBuilder.vectorizeInstance(instance);
push(inst, false); // No need to copy
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify 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.
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
// We only need to do something in this method
// if the first batch hasn't been processed. Otherwise
// input() has already done all the work.
if (!isFirstBatchDone()) {
long pruneRate = Math.round((m_PeriodicPruningRate / 100.0)
* getInputFormat().numInstances());
m_dictionaryBuilder.setPeriodicPruning(pruneRate);
// m_dictionaryBuilder.setNormalize(m_filterType == FILTER_NORMALIZE_ALL);
for (int i = 0; i < getInputFormat().numInstances(); i++) {
Instance toProcess = getInputFormat().instance(i);
m_dictionaryBuilder.processInstance(toProcess);
}
m_dictionaryBuilder.finalizeDictionary();
setOutputFormat(m_dictionaryBuilder.getVectorizedFormat());
m_dictionaryBuilder.setNormalize(m_filterType != FILTER_NONE);
Instances converted = m_dictionaryBuilder.vectorizeBatch( getInputFormat(),
m_filterType != FILTER_NONE);
// save the dictionary?
if (m_dictionaryFile != null && m_dictionaryFile.toString().length() > 0 &&
!m_dictionaryFile.toString().equalsIgnoreCase("-- set me --")) {
m_dictionaryBuilder.saveDictionary(m_dictionaryFile, !m_dictionaryIsBinary);
}
// push all instances into the output queue
for (int i = 0; i < converted.numInstances(); i++) {
push(converted.instance(i), false);
}
}
// Flush the input
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Tip text for this property
*
* @return the tip text for this property
*/
public String dictionaryFileToSaveToTipText() {
return "The path to save the dictionary file to - "
+ "an empty path or a path '-- set me --' means "
+ "do not save the dictionary.";
}
/**
* Set the dictionary file to save the dictionary to. A file with an
* empty path or a path "-- set me --" means do not save the dictionary.
*
* @param toSaveTo the path to save the dictionary to
*/
public void setDictionaryFileToSaveTo(File toSaveTo) {
m_dictionaryFile = toSaveTo;
}
/**
* Set the dictionary file to save the dictionary to. A file with an
* empty path or a path "-- set me --" means do not save the dictionary.
*
* @return the path to save the dictionary to
*/
public File getDictionaryFileToSaveTo() {
return m_dictionaryFile;
}
public String saveDictionaryInBinaryFormTipText() {
return "Save the dictionary as a binary serialized java object instead of "
+ "in plain text form.";
}
/**
* Set whether to save the dictionary in binary serialized form rather than
* as plain text
*
* @param saveAsBinary true to save the dictionary in binary form
*/
public void setSaveDictionaryInBinaryForm(boolean saveAsBinary) {
m_dictionaryIsBinary = saveAsBinary;
}
/**
* Set whether to save the dictionary in binary serialized form rather than
* as plain text
*
* @return true to save the dictionary in binary form
*/
public boolean getSaveDictionaryInBinaryForm() {
return m_dictionaryIsBinary;
}
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Converts string attributes into a set of numeric attributes representing word occurrence" +
" information from the text contained in the strings. The dictionary is determined from the first batch of data" +
" filtered (typically training data). Note that this filter is not strictly unsupervised when a class attribute is set" +
" because it creates a separate dictionary for each class and then merges them.";
}
/**
* Gets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @return true if word counts should be output.
*/
public boolean getOutputWordCounts() {
return m_dictionaryBuilder.getOutputWordCounts();
}
/**
* Sets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @param outputWordCounts true if word counts should be output.
*/
public void setOutputWordCounts(boolean outputWordCounts) {
m_dictionaryBuilder.setOutputWordCounts(outputWordCounts);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputWordCountsTipText() {
return "Output word counts rather than boolean 0 or 1"
+ "(indicating presence or absence of a word).";
}
/**
* Get the value of m_SelectedRange.
*
* @return Value of m_SelectedRange.
*/
public Range getSelectedRange() {
return m_dictionaryBuilder.getSelectedRange();
}
/**
* Set the value of m_SelectedRange.
*
* @param newSelectedRange Value to assign to m_SelectedRange.
*/
public void setSelectedRange(String newSelectedRange) {
m_dictionaryBuilder.setSelectedRange(newSelectedRange);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndicesTipText() {
return "Specify range of attributes to act on."
+ " This is a comma separated list of attribute indices, with"
+ " \"first\" and \"last\" valid values. Specify an inclusive"
+ " range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
* Gets the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_dictionaryBuilder.getAttributeIndices();
}
/**
* Sets which attributes are to be worked on.
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) {
m_dictionaryBuilder.setAttributeIndices(rangeList);
}
/**
* Sets which attributes are to be processed.
*
* @param attributes an array containing indexes of attributes to process.
* Since the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) {
m_dictionaryBuilder.setAttributeIndicesArray(attributes);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Set attribute selection mode. If false, only selected"
+ " attributes in the range will be worked on; if"
+ " true, only non-selected attributes will be processed.";
}
/**
* Gets whether the supplied columns are to be processed or skipped.
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_dictionaryBuilder.getInvertSelection();
}
/**
* Sets whether selected columns should be processed or skipped.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_dictionaryBuilder.setInvertSelection(invert);
}
/**
* Get the attribute name prefix.
*
* @return The current attribute name prefix.
*/
public String getAttributeNamePrefix() {
return m_dictionaryBuilder.getAttributeNamePrefix();
}
/**
* Set the attribute name prefix.
*
* @param newPrefix String to use as the attribute name prefix.
*/
public void setAttributeNamePrefix(String newPrefix) {
m_dictionaryBuilder.setAttributeNamePrefix(newPrefix);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeNamePrefixTipText() {
return "Prefix for the created attribute names. " + "(default: \"\")";
}
/**
* Gets the number of words (per class if there is a class attribute assigned)
* to attempt to keep.
*
* @return the target number of words in the output vector (per class if
* assigned).
*/
public int getWordsToKeep() {
return m_dictionaryBuilder.getWordsToKeep();
}
/**
* Sets the number of words (per class if there is a class attribute assigned)
* to attempt to keep.
*
* @param newWordsToKeep the target number of words in the output vector (per
* class if assigned).
*/
public void setWordsToKeep(int newWordsToKeep) {
m_dictionaryBuilder.setWordsToKeep(newWordsToKeep);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String wordsToKeepTipText() {
return "The number of words (per class if there is a class attribute "
+ "assigned) to attempt to keep.";
}
/**
* Gets the rate at which the dictionary is periodically pruned, as a
* percentage of the dataset size.
*
* @return the rate at which the dictionary is periodically pruned
*/
public double getPeriodicPruning() {
return m_PeriodicPruningRate;
}
/**
* Sets the rate at which the dictionary is periodically pruned, as a
* percentage of the dataset size.
*
* @param newPeriodicPruning the rate at which the dictionary is periodically
* pruned
*/
public void setPeriodicPruning(double newPeriodicPruning) {
m_PeriodicPruningRate = newPeriodicPruning;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String periodicPruningTipText() {
return "Specify the rate (x% of the input dataset) at which to periodically prune the dictionary. "
+ "wordsToKeep prunes after creating a full dictionary. You may not have enough "
+ "memory for this approach.";
}
/**
* Gets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @return true if word frequencies are to be transformed.
*/
public boolean getTFTransform() {
return m_dictionaryBuilder.getTFTransform();
}
/**
* Sets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @param TFTransform true if word frequencies are to be transformed.
*/
public void setTFTransform(boolean TFTransform) {
m_dictionaryBuilder.setTFTransform(TFTransform);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String TFTransformTipText() {
return "Sets whether if the word frequencies should be transformed into"
+ " log(1+fij) where fij is the frequency of word i in document (instance) j.";
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @return true if the word frequencies are to be transformed.
*/
public boolean getIDFTransform() {
return m_dictionaryBuilder.getIDFTransform();
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @param IDFTransform true if the word frequecies are to be transformed
*/
public void setIDFTransform(boolean IDFTransform) {
m_dictionaryBuilder.setIDFTransform(IDFTransform);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String IDFTransformTipText() {
return "Sets whether if the word frequencies in a document should be "
+ "transformed into: \n"
+ " fij*log(num of Docs/num of Docs with word i) \n"
+ " where fij is the frequency of word i in document (instance) j.";
}
/**
* Gets whether if the word frequencies for a document (instance) should be
* normalized or not.
*
* @return true if word frequencies are to be normalized.
*/
public SelectedTag getNormalizeDocLength() {
return new SelectedTag(m_filterType, TAGS_FILTER);
}
/**
* Sets whether if the word frequencies for a document (instance) should be
* normalized or not.
*
* @param newType the new type.
*/
public void setNormalizeDocLength(SelectedTag newType) {
if (newType.getTags() == TAGS_FILTER) {
m_filterType = newType.getSelectedTag().getID();
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String normalizeDocLengthTipText() {
return "Sets whether if the word frequencies for a document (instance) "
+ "should be normalized or not.";
}
/**
* Gets whether if the tokens are to be downcased or not.
*
* @return true if the tokens are to be downcased.
*/
public boolean getLowerCaseTokens() {
return m_dictionaryBuilder.getLowerCaseTokens();
}
/**
* Sets whether if the tokens are to be downcased or not. (Doesn't affect
* non-alphabetic characters in tokens).
*
* @param downCaseTokens should be true if only lower case tokens are to be
* formed.
*/
public void setLowerCaseTokens(boolean downCaseTokens) {
m_dictionaryBuilder.setLowerCaseTokens(downCaseTokens);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String doNotOperateOnPerClassBasisTipText() {
return "If this is set, the maximum number of words and the "
+ "minimum term frequency is not enforced on a per-class "
+ "basis but based on the documents in all the classes "
+ "(even if a class attribute is set).";
}
/**
* Get the DoNotOperateOnPerClassBasis value.
*
* @return the DoNotOperateOnPerClassBasis value.
*/
public boolean getDoNotOperateOnPerClassBasis() {
return m_dictionaryBuilder.getDoNotOperateOnPerClassBasis();
}
/**
* Set the DoNotOperateOnPerClassBasis value.
*
* @param newDoNotOperateOnPerClassBasis The new DoNotOperateOnPerClassBasis
* value.
*/
public void setDoNotOperateOnPerClassBasis(
boolean newDoNotOperateOnPerClassBasis) {
m_dictionaryBuilder.setDoNotOperateOnPerClassBasis(newDoNotOperateOnPerClassBasis);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String minTermFreqTipText() {
return "Sets the minimum term frequency. This is enforced "
+ "on a per-class basis.";
}
/**
* Get the MinTermFreq value.
*
* @return the MinTermFreq value.
*/
public int getMinTermFreq() {
return m_dictionaryBuilder.getMinTermFreq();
}
/**
* Set the MinTermFreq value.
*
* @param newMinTermFreq The new MinTermFreq value.
*/
public void setMinTermFreq(int newMinTermFreq) {
m_dictionaryBuilder.setMinTermFreq(newMinTermFreq);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String lowerCaseTokensTipText() {
return "If set then all the word tokens are converted to lower case "
+ "before being added to the dictionary.";
}
/**
* the stemming algorithm to use, null means no stemming at all (i.e., the
* NullStemmer is used).
*
* @param value the configured stemming algorithm, or null
* @see NullStemmer
*/
public void setStemmer(Stemmer value) {
if (value != null) {
m_dictionaryBuilder.setStemmer(value);
} else {
m_dictionaryBuilder.setStemmer(new NullStemmer());
}
}
/**
* Returns the current stemming algorithm, null if none is used.
*
* @return the current stemming algorithm, null if none set
*/
public Stemmer getStemmer() {
return m_dictionaryBuilder.getStemmer();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String stemmerTipText() {
return "The stemming algorithm to use on the words.";
}
/**
* Sets the stopwords handler to use.
*
* @param value the stopwords handler, if null, Null is used
*/
public void setStopwordsHandler(StopwordsHandler value) {
if (value != null) {
m_dictionaryBuilder.setStopwordsHandler(value);
} else {
m_dictionaryBuilder.setStopwordsHandler(new Null());
}
}
/**
* Gets the stopwords handler.
*
* @return the stopwords handler
*/
public StopwordsHandler getStopwordsHandler() {
return m_dictionaryBuilder.getStopwordsHandler();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String stopwordsHandlerTipText() {
return "The stopwords handler to use (Null means no stopwords are used).";
}
/**
* the tokenizer algorithm to use.
*
* @param value the configured tokenizing algorithm
*/
public void setTokenizer(Tokenizer value) {
m_dictionaryBuilder.setTokenizer(value);
}
/**
* Returns the current tokenizer algorithm.
*
* @return the current tokenizer algorithm
*/
public Tokenizer getTokenizer() {
return m_dictionaryBuilder.getTokenizer();
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String tokenizerTipText() {
return "The tokenizing algorithm to use on the strings.";
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new StringToWordVector(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/SwapValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SwapValues.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Swaps two values of a nominal attribute.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the first value's index (default first).
* </pre>
*
* <pre>
* -S <value index>
* Sets the second value's index (default last).
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class SwapValues extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 6155834679414275855L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** The first value's index setting. */
private final SingleIndex m_FirstIndex = new SingleIndex("first");
/** The second value's index setting. */
private final SingleIndex m_SecondIndex = new SingleIndex("last");
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Swaps two values of a nominal attribute.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if the selected attribute is not
* nominal or if it only has one value.
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
m_FirstIndex.setUpper(instanceInfo.attribute(m_AttIndex.getIndex())
.numValues() - 1);
m_SecondIndex.setUpper(instanceInfo.attribute(m_AttIndex.getIndex())
.numValues() - 1);
if (!instanceInfo.attribute(m_AttIndex.getIndex()).isNominal()) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute not nominal.");
}
if (instanceInfo.attribute(m_AttIndex.getIndex()).numValues() < 2) {
throw new UnsupportedAttributeTypeException(
"Chosen attribute has less than " + "two values.");
}
setOutputFormat();
return true;
}
/**
* Input an instance for filtering. The instance is processed and made
* available for output immediately.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws IllegalStateException if no input structure has been defined.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
Instance newInstance = (Instance) instance.copy();
if (!newInstance.isMissing(m_AttIndex.getIndex())) {
if ((int) newInstance.value(m_AttIndex.getIndex()) == m_SecondIndex.getIndex()) {
newInstance.setValue(m_AttIndex.getIndex(), m_FirstIndex.getIndex());
} else if ((int) newInstance.value(m_AttIndex.getIndex()) == m_FirstIndex.getIndex()) {
newInstance.setValue(m_AttIndex.getIndex(), m_SecondIndex.getIndex());
}
}
push(newInstance, false); // No need to copy
return true;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(3);
newVector.addElement(new Option(
"\tSets the attribute index (default last).", "C", 1, "-C <col>"));
newVector.addElement(new Option(
"\tSets the first value's index (default first).", "F", 1,
"-F <value index>"));
newVector.addElement(new Option(
"\tSets the second value's index (default last).", "S", 1,
"-S <value index>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <col>
* Sets the attribute index (default last).
* </pre>
*
* <pre>
* -F <value index>
* Sets the first value's index (default first).
* </pre>
*
* <pre>
* -S <value index>
* Sets the second value's index (default last).
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
setAttributeIndex(attIndex);
} else {
setAttributeIndex("last");
}
String firstValIndex = Utils.getOption('F', options);
if (firstValIndex.length() != 0) {
setFirstValueIndex(firstValIndex);
} else {
setFirstValueIndex("first");
}
String secondValIndex = Utils.getOption('S', options);
if (secondValIndex.length() != 0) {
setSecondValueIndex(secondValIndex);
} else {
setSecondValueIndex("last");
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + (getAttributeIndex()));
options.add("-F");
options.add("" + (getFirstValueIndex()));
options.add("-S");
options.add("" + (getSecondValueIndex()));
return options.toArray(new String[0]);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Sets which attribute to process. This "
+ "attribute must be nominal (\"first\" and \"last\" are valid values)";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String firstValueIndexTipText() {
return "The index of the first value "
+ "(\"first\" and \"last\" are valid values).";
}
/**
* Get the index of the first value used.
*
* @return the index of the first value
*/
public String getFirstValueIndex() {
return m_FirstIndex.getSingleIndex();
}
/**
* Sets index of the first value used.
*
* @param firstIndex the index of the first value
*/
public void setFirstValueIndex(String firstIndex) {
m_FirstIndex.setSingleIndex(firstIndex);
}
/**
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String secondValueIndexTipText() {
return "The index of the second value "
+ "(\"first\" and \"last\" are valid values).";
}
/**
* Get the index of the second value used.
*
* @return the index of the second value
*/
public String getSecondValueIndex() {
return m_SecondIndex.getSingleIndex();
}
/**
* Sets index of the second value used.
*
* @param secondIndex the index of the second value
*/
public void setSecondValueIndex(String secondIndex) {
m_SecondIndex.setSingleIndex(secondIndex);
}
/**
* Set the output format. Swapss the desired nominal attribute values in the
* header and calls setOutputFormat(Instances) appropriately.
*/
private void setOutputFormat() {
Instances newData;
ArrayList<Attribute> newAtts;
ArrayList<String> newVals;
// Compute new attributes
newAtts = new ArrayList<Attribute>(getInputFormat().numAttributes());
for (int j = 0; j < getInputFormat().numAttributes(); j++) {
Attribute att = getInputFormat().attribute(j);
if (j != m_AttIndex.getIndex()) {
newAtts.add((Attribute) att.copy());
} else {
// Compute list of attribute values
newVals = new ArrayList<String>(att.numValues());
for (int i = 0; i < att.numValues(); i++) {
if (i == m_FirstIndex.getIndex()) {
newVals.add(att.value(m_SecondIndex.getIndex()));
} else if (i == m_SecondIndex.getIndex()) {
newVals.add(att.value(m_FirstIndex.getIndex()));
} else {
newVals.add(att.value(i));
}
}
Attribute newAtt = new Attribute(att.name(), newVals);
newAtt.setWeight(att.weight());
newAtts.add(newAtt);
}
}
// Construct new header
newData = new Instances(getInputFormat().relationName(), newAtts, 0);
newData.setClassIndex(getInputFormat().classIndex());
setOutputFormat(newData);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new SwapValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/TimeSeriesDelta.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* TimeSeriesDelta.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.UnsupportedAttributeTypeException;
import weka.core.Utils;
/**
<!-- globalinfo-start -->
* An instance filter that assumes instances form time-series data and replaces attribute values in the current instance with the difference between the current value and the equivalent attribute attribute value of some previous (or future) instance. For instances where the time-shifted value is unknown either the instance may be dropped, or missing values used. Skips the class attribute if it is set.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -R <index1,index2-index4,...>
* Specify list of columns to translate in time. First and
* last are valid indexes. (default none)</pre>
*
* <pre> -V
* Invert matching sense (i.e. calculate for all non-specified columns)</pre>
*
* <pre> -I <num>
* The number of instances forward to translate values
* between. A negative number indicates taking values from
* a past instance. (default -1)</pre>
*
* <pre> -M
* For instances at the beginning or end of the dataset where
* the translated values are not known, remove those instances
* (default is to use missing values).</pre>
*
<!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class TimeSeriesDelta
extends TimeSeriesTranslate {
/** for serialization */
static final long serialVersionUID = 3101490081896634942L;
/**
* Returns a string describing this classifier
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "An instance filter that assumes instances form time-series data and "
+ "replaces attribute values in the current instance with the difference "
+ "between the current value and the equivalent attribute attribute value "
+ "of some previous (or future) instance. For instances where the time-shifted "
+ "value is unknown either the instance may be dropped, or missing values "
+ "used. Skips the class attribute if it is set.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if selected
* attributes are not numeric.
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
if ((instanceInfo.classIndex() > 0) && (!getFillWithMissing())) {
throw new IllegalArgumentException("TimeSeriesDelta: Need to fill in missing values " +
"using appropriate option when class index is set.");
}
super.setInputFormat(instanceInfo);
// Create the output buffer
Instances outputFormat = new Instances(instanceInfo, 0);
for(int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i != instanceInfo.classIndex()) {
if (m_SelectedCols.isInRange(i)) {
if (outputFormat.attribute(i).isNumeric()) {
outputFormat.renameAttribute(i, outputFormat.attribute(i).name()
+ " d"
+ (m_InstanceRange < 0 ? '-' : '+')
+ Math.abs(m_InstanceRange));
} else {
throw new UnsupportedAttributeTypeException("Time delta attributes must be numeric!");
}
}
}
}
outputFormat.setClassIndex(instanceInfo.classIndex());
setOutputFormat(outputFormat);
return true;
}
/**
* Creates a new instance the same as one instance (the "destination")
* but with some attribute values copied from another instance
* (the "source")
*
* @param source the source instance
* @param dest the destination instance
* @return the new merged instance
*/
protected Instance mergeInstances(Instance source, Instance dest) {
Instances outputFormat = outputFormatPeek();
double[] vals = new double[outputFormat.numAttributes()];
for(int i = 0; i < vals.length; i++) {
if ((i != outputFormat.classIndex()) && (m_SelectedCols.isInRange(i))) {
if ((source != null) && !source.isMissing(i) && !dest.isMissing(i)) {
vals[i] = dest.value(i) - source.value(i);
} else {
vals[i] = Utils.missingValue();
}
} else {
vals[i] = dest.value(i);
}
}
Instance inst = null;
if (dest instanceof SparseInstance) {
inst = new SparseInstance(dest.weight(), vals);
} else {
inst = new DenseInstance(dest.weight(), vals);
}
inst.setDataset(dest.dataset());
return inst;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String [] argv) {
runFilter(new TimeSeriesDelta(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/TimeSeriesTranslate.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* TimeSeriesTranslate.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.UnsupportedAttributeTypeException;
import weka.core.Utils;
/**
<!-- globalinfo-start -->
* An instance filter that assumes instances form time-series data and replaces attribute values in the current instance with the equivalent attribute values of some previous (or future) instance. For instances where the desired value is unknown either the instance may be dropped, or missing values used. Skips the class attribute if it is set.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -R <index1,index2-index4,...>
* Specify list of columns to translate in time. First and
* last are valid indexes. (default none)</pre>
*
* <pre> -V
* Invert matching sense (i.e. calculate for all non-specified columns)</pre>
*
* <pre> -I <num>
* The number of instances forward to translate values
* between. A negative number indicates taking values from
* a past instance. (default -1)</pre>
*
* <pre> -M
* For instances at the beginning or end of the dataset where
* the translated values are not known, remove those instances
* (default is to use missing values).</pre>
*
<!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class TimeSeriesTranslate
extends AbstractTimeSeries {
/** for serialization */
static final long serialVersionUID = -8901621509691785705L;
/**
* Returns a string describing this classifier
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"An instance filter that assumes instances form time-series data and "
+ "replaces attribute values in the current instance with the equivalent "
+ "attribute values of some previous (or future) instance. For "
+ "instances where the desired value is unknown either the instance may "
+ "be dropped, or missing values used. Skips the class attribute if it is set.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 UnsupportedAttributeTypeException if selected
* attributes are not numeric or nominal.
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
if ((instanceInfo.classIndex() > 0) && (!getFillWithMissing())) {
throw new IllegalArgumentException("TimeSeriesTranslate: Need to fill in missing values " +
"using appropriate option when class index is set.");
}
super.setInputFormat(instanceInfo);
// Create the output buffer
Instances outputFormat = new Instances(instanceInfo, 0);
for(int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i != instanceInfo.classIndex()) {
if (m_SelectedCols.isInRange(i)) {
if (outputFormat.attribute(i).isNominal()
|| outputFormat.attribute(i).isNumeric()) {
outputFormat.renameAttribute(i, outputFormat.attribute(i).name()
+ (m_InstanceRange < 0 ? '-' : '+')
+ Math.abs(m_InstanceRange));
} else {
throw new UnsupportedAttributeTypeException("Only numeric and nominal attributes may be "
+ " manipulated in time series.");
}
}
}
}
outputFormat.setClassIndex(instanceInfo.classIndex());
setOutputFormat(outputFormat);
return true;
}
/**
* Creates a new instance the same as one instance (the "destination")
* but with some attribute values copied from another instance
* (the "source")
*
* @param source the source instance
* @param dest the destination instance
* @return the new merged instance
*/
protected Instance mergeInstances(Instance source, Instance dest) {
Instances outputFormat = outputFormatPeek();
double[] vals = new double[outputFormat.numAttributes()];
for(int i = 0; i < vals.length; i++) {
if ((i != outputFormat.classIndex()) && (m_SelectedCols.isInRange(i))) {
if (source != null) {
vals[i] = source.value(i);
} else {
vals[i] = Utils.missingValue();
}
} else {
vals[i] = dest.value(i);
}
}
Instance inst = null;
if (dest instanceof SparseInstance) {
inst = new SparseInstance(dest.weight(), vals);
} else {
inst = new DenseInstance(dest.weight(), vals);
}
inst.setDataset(dest.dataset());
return inst;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String [] argv) {
runFilter(new TimeSeriesTranslate(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/attribute/Transpose.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Transpose.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.attribute;
import java.util.ArrayList;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
import weka.filters.UnsupervisedFilter;
/**
<!-- globalinfo-start -->
* Transposes the data: instances become attributes and attributes become instances. If the first attribute in the
* original data is a nominal or string identifier attribute, this identifier attribute will be used to create attribute
* names in the transposed data. All attributes other than the identifier attribute must be numeric. The attribute names
* in the original data are used to create an identifier attribute of type string in the transposed data.<br/>
* <br/>
* This filter can only process one batch of data, e.g., it cannot be used in the the FilteredClassifier.<br/>
* <br/>
* This filter can only be applied when no class attribute has been set.<br/>
* <br/>
* Date values will be turned into simple numeric values.<br/>
* <br/>
* <p/>
<!-- globalinfo-end -->
*
* @author Eibe Frank
* @version $Revision: 10215 $
*/
public class Transpose extends SimpleBatchFilter
implements UnsupervisedFilter, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 213999899640387499L;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Transposes the data: instances become attributes and attributes"
+ " become instances. If the first attribute in the original data"
+ " is a nominal or string identifier attribute, this identifier attribute"
+ " will be used to create attribute names in the transposed data. All"
+ " attributes other than the identifier attribute must be numeric. The"
+ " attribute names in the original data are used to create an identifier"
+ " attribute of type string in the transposed data.\n\n"
+ "This filter can only process one batch of data, e.g., it cannot be used"
+ " in the the FilteredClassifier.\n\n"
+ "This filter can only be applied when no class attribute has been set.\n\n"
+ "Date values will be turned into simple numeric values.\n\n";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.STRING_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns this. In
* case the output format cannot be returned immediately, i.e.,
* immediateOutputFormat() returns false, then this method will be called from
* batchFinished().
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
* @see #hasImmediateOutputFormat()
* @see #batchFinished()
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
ArrayList<Attribute> newAtts = new ArrayList<Attribute>(
inputFormat.numInstances());
newAtts.add(new Attribute("Identifier", (ArrayList<String>) null));
for (int i = 0; i < inputFormat.numInstances(); i++) {
if (inputFormat.attribute(0).isNominal()
|| inputFormat.attribute(0).isString()) {
// We have a proper identifier
newAtts.add(new Attribute(inputFormat.instance(i).stringValue(0)));
} else {
// Just use a simple identifier
newAtts.add(new Attribute("" + (i + 1)));
}
newAtts.get(i).setWeight(inputFormat.instance(i).weight());
}
return new Instances(inputFormat.relationName(), newAtts,
inputFormat.numAttributes());
}
/**
* Processes the given data (may change the provided dataset) and returns the
* modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
if (isFirstBatchDone()) {
throw new Exception(
"The Transpose filter can only process one batch of instances.");
}
setOutputFormat(determineOutputFormat(instances));
// Do we have an identifier in the original data?
int offset = (instances.attribute(0).isNominal() || instances.attribute(0)
.isString()) ? 1 : 0;
// Transpose data
double[][] newData = new double[instances.numAttributes() - offset][instances
.numInstances() + 1];
for (int i = 0; i < instances.numInstances(); i++) {
for (int j = offset; j < instances.numAttributes(); j++) {
newData[j - offset][0] = getOutputFormat().attribute(0).addStringValue(
instances.attribute(j).name());
if (!instances.attribute(j).isNumeric()) {
throw new Exception("Only numeric attributes can be transposed: "
+ instances.attribute(j).name() + " is not numeric.");
}
newData[j - offset][i + 1] = instances.instance(i).value(j);
}
}
// Create instances
Instances result = getOutputFormat();
for (int i = 0; i < newData.length; i++) {
result.add(new DenseInstance(instances.attribute(i + offset).weight(),
newData[i]));
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 10215 $");
}
/**
* runs the filter with the given arguments
*
* @param args the commandline arguments
*/
public static void main(String[] args) {
runFilter(new Transpose(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/NonSparseToSparse.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* NonSparseToSparse.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> An instance filter that converts all incoming
* instances into sparse format.
* <p/>
* <!-- globalinfo-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NonSparseToSparse extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 4694489111366063852L;
protected boolean m_encodeMissingAsZero = false;
/**
* 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 converts all incoming instances"
+ " into sparse format.";
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.add(new Option("\tTreat missing values as zero.", "M", 0, "-M"));
return result.elements();
}
@Override
public void setOptions(String[] options) throws Exception {
m_encodeMissingAsZero = Utils.getFlag('M', options);
Utils.checkForRemainingOptions(options);
}
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (m_encodeMissingAsZero) {
result.add("-M");
}
return result.toArray(new String[result.size()]);
}
/**
* Set whether missing values should be treated in the same way as zeros
*
* @param m true if missing values are to be treated the same as zeros
*/
public void setTreatMissingValuesAsZero(boolean m) {
m_encodeMissingAsZero = m;
}
/**
* Get whether missing values are to be treated in the same way as zeros
*
* @return true if missing values are to be treated in the same way as zeros
*/
public boolean getTreatMissingValuesAsZero() {
return m_encodeMissingAsZero;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String treatMissingValuesAsZeroTipText() {
return "Treat missing values in the same way as zeros.";
}
/**
* 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 format cannot be processed
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
Instances instNew = instanceInfo;
setOutputFormat(instNew);
return true;
}
/**
* 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 set.
*/
@Override
public boolean input(Instance instance) {
Instance newInstance = null;
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (m_encodeMissingAsZero) {
Instance tempInst = (Instance) instance.copy();
tempInst.setDataset(getInputFormat());
for (int i = 0; i < tempInst.numAttributes(); i++) {
if (tempInst.isMissing(i)) {
tempInst.setValue(i, 0);
}
}
instance = tempInst;
}
newInstance = new SparseInstance(instance);
newInstance.setDataset(instance.dataset());
push(newInstance, false); // No need to copy
/*
* Instance inst = new SparseInstance(instance);
* inst.setDataset(instance.dataset()); push(inst);
*/
return true;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new NonSparseToSparse(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/Randomize.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Randomize.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Randomizable;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.core.WeightedInstancesHandler;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
import weka.gui.ProgrammaticProperty;
/**
* <!-- globalinfo-start --> Randomly shuffles the order of instances passed
* through it. The random number generator is reset with the seed value whenever
* a new set of instances is passed in.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 42)
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Randomize extends Filter implements UnsupervisedFilter, OptionHandler, Randomizable, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 8854479785121877582L;
/** The random number seed */
protected int m_Seed = 42;
/** The current random number generator */
protected Random m_Random;
/**
* Returns a string describing this classifier
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Randomly shuffles the order of instances passed through it. " + "The random number generator is reset with the seed value whenever " + "a new set of instances is passed in.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(1);
newVector.addElement(new Option("\tSpecify the random number seed (default 42)", "S", 1, "-S <num>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 42)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String seedString = Utils.getOption('S', options);
if (seedString.length() != 0) {
this.setRandomSeed(Integer.parseInt(seedString));
} else {
this.setRandomSeed(42);
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-S");
options.add("" + this.getRandomSeed());
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String randomSeedTipText() {
return "Seed for the random number generator.";
}
/**
* Get the random number generator seed value.
*
* @return random number generator seed value.
*/
public int getRandomSeed() {
return this.m_Seed;
}
/**
* Set the random number generator seed value.
*
* @param newRandomSeed value to use as the random number generator seed.
*/
public void setRandomSeed(final int newRandomSeed) {
this.m_Seed = newRandomSeed;
}
@Override
@ProgrammaticProperty
public void setSeed(final int seed) {
this.setRandomSeed(seed);
}
@Override
@ProgrammaticProperty
public int getSeed() {
return this.getRandomSeed();
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 format cannot be processed
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
this.m_Random = new Random(this.m_Seed);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isFirstBatchDone()) {
this.push(instance);
return true;
} else {
this.bufferInput(instance);
return false;
}
}
/**
* Signify 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. Any subsequent instances filtered should
* be filtered based on setting obtained from the first batch (unless the
* setInputFormat has been re-assigned or new options have been set). This
* implementation randomizes all the instances received in the batch.
*
* @return true if there are instances pending output
* @throws InterruptedException
* @throws IllegalStateException if no input format has been set.
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!this.isFirstBatchDone()) {
this.getInputFormat().randomize(this.m_Random);
}
for (int i = 0; i < this.getInputFormat().numInstances(); i++) {
this.push(this.getInputFormat().instance(i), false); // No need to copy because of bufferInput()
}
this.flushInput();
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new Randomize(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveDuplicates.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* SubsetByExpression.java
* Copyright (C) 2008-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.unsupervised.instance;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.SimpleBatchFilter;
import weka.classifiers.rules.DecisionTableHashKey;
import java.util.HashSet;
/**
<!-- globalinfo-start -->
* Removes all duplicate instances from the first batch of data it receives.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* Turns on output of debugging information.</pre>
*
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 9804 $
*/
public class RemoveDuplicates extends SimpleBatchFilter implements WeightedAttributesHandler, WeightedInstancesHandler{
/** for serialization. */
private static final long serialVersionUID = 4518686110979589602L;
/**
* Returns a string describing this filter.
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Removes all duplicate instances from the first batch of data it receives.";
}
/**
* Input an instance for filtering. Filter requires all
* training instances be read before producing output (calling the method
* batchFinished() makes the data available). If this instance is part of
* a new batch, m_NewBatch is set to false.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @throws IllegalStateException if no input structure has been defined
* @throws Exception if something goes wrong
* @see #batchFinished()
*/
@Override
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null)
throw new IllegalStateException("No input instance format defined");
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.STRING_ATTRIBUTES);
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.STRING_CLASS);
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Determines the output format based on the input format and returns
* this.
*
* @param inputFormat the input format to base the output format on
* @return the output format
* @throws Exception in case the determination goes wrong
*/
@Override
protected Instances determineOutputFormat(Instances inputFormat)
throws Exception {
return new Instances(inputFormat, 0);
}
/**
* returns true if the output format is immediately available after the
* input format has been set and not only after all the data has been
* seen (see batchFinished())
*
* @return true if the output format is immediately available
* @see #batchFinished()
* @see #setInputFormat(Instances)
*/
protected boolean hasImmediateOutputFormat() {
return true;
}
/**
* Processes the given data (may change the provided dataset) and returns
* the modified version. This method is called in batchFinished().
*
* @param instances the data to process
* @return the modified data
* @throws Exception in case the processing goes wrong
* @see #batchFinished()
*/
@Override
protected Instances process(Instances instances) throws Exception {
if (!isFirstBatchDone()) {
HashSet<DecisionTableHashKey> hs = new HashSet<DecisionTableHashKey>();
Instances newInstances = new Instances(instances, instances.numInstances());
for (Instance inst : instances) {
DecisionTableHashKey key = new DecisionTableHashKey(inst,
instances.numAttributes(), true);
if (hs.add(key)) {
newInstances.add(inst);
}
}
newInstances.compactify();
return newInstances;
}
throw new Exception("The process method should never be called for subsequent batches.");
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 9804 $");
}
/**
* Main method for running this filter.
*
* @param args arguments for the filter: use -h for help
*/
public static void main(String[] args) {
runFilter(new RemoveDuplicates(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveFolds.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveFolds.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> This filter takes a dataset and outputs a specified
* fold for cross validation. If you want the folds to be stratified use the
* supervised version.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <pre>
* -N <number of folds>
* Specifies number of folds dataset is split into.
* (default 10)
* </pre>
*
* <pre>
* -F <fold>
* Specifies which fold is selected. (default 1)
* </pre>
*
* <pre>
* -S <seed>
* Specifies random number seed. (default 0, no randomizing)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveFolds extends Filter implements UnsupervisedFilter, OptionHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 8220373305559055700L;
/** Indicates if inverse of selection is to be output. */
private boolean m_Inverse = false;
/** Number of folds to split dataset into */
private int m_NumFolds = 10;
/** Fold to output */
private int m_Fold = 1;
/** Random number seed. */
private long m_Seed = 0;
/**
* Gets an enumeration describing the available options..
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tSpecifies if inverse of selection is to be output.\n", "V", 0, "-V"));
newVector.addElement(new Option("\tSpecifies number of folds dataset is split into. \n" + "\t(default 10)\n", "N", 1, "-N <number of folds>"));
newVector.addElement(new Option("\tSpecifies which fold is selected. (default 1)\n", "F", 1, "-F <fold>"));
newVector.addElement(new Option("\tSpecifies random number seed. (default 0, no randomizing)\n", "S", 1, "-S <seed>"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <pre>
* -N <number of folds>
* Specifies number of folds dataset is split into.
* (default 10)
* </pre>
*
* <pre>
* -F <fold>
* Specifies which fold is selected. (default 1)
* </pre>
*
* <pre>
* -S <seed>
* Specifies random number seed. (default 0, no randomizing)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
this.setInvertSelection(Utils.getFlag('V', options));
String numFolds = Utils.getOption('N', options);
if (numFolds.length() != 0) {
this.setNumFolds(Integer.parseInt(numFolds));
} else {
this.setNumFolds(10);
}
String fold = Utils.getOption('F', options);
if (fold.length() != 0) {
this.setFold(Integer.parseInt(fold));
} else {
this.setFold(1);
}
String seed = Utils.getOption('S', options);
if (seed.length() != 0) {
this.setSeed(Integer.parseInt(seed));
} else {
this.setSeed(0);
}
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-S");
options.add("" + this.getSeed());
if (this.getInvertSelection()) {
options.add("-V");
}
options.add("-N");
options.add("" + this.getNumFolds());
options.add("-F");
options.add("" + this.getFold());
return options.toArray(new String[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 "This filter takes a dataset and outputs a specified fold for " + "cross validation. If you want the folds to be stratified use the " + "supervised version.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to invert the selection.";
}
/**
* Gets if selection is to be inverted.
*
* @return true if the selection is to be inverted
*/
public boolean getInvertSelection() {
return this.m_Inverse;
}
/**
* Sets if selection is to be inverted.
*
* @param inverse true if inversion is to be performed
*/
public void setInvertSelection(final boolean inverse) {
this.m_Inverse = inverse;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numFoldsTipText() {
return "The number of folds to split the dataset into.";
}
/**
* Gets the number of folds in which dataset is to be split into.
*
* @return the number of folds the dataset is to be split into.
*/
public int getNumFolds() {
return this.m_NumFolds;
}
/**
* Sets the number of folds the dataset is split into. If the number of folds
* is zero, it won't split it into folds.
*
* @param numFolds number of folds dataset is to be split into
* @throws IllegalArgumentException if number of folds is negative
*/
public void setNumFolds(final int numFolds) {
if (numFolds < 0) {
throw new IllegalArgumentException("Number of folds has to be positive or zero.");
}
this.m_NumFolds = numFolds;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String foldTipText() {
return "The fold which is selected.";
}
/**
* Gets the fold which is selected.
*
* @return the fold which is selected
*/
public int getFold() {
return this.m_Fold;
}
/**
* Selects a fold.
*
* @param fold the fold to be selected.
* @throws IllegalArgumentException if fold's index is smaller than 1
*/
public void setFold(final int fold) {
if (fold < 1) {
throw new IllegalArgumentException("Fold's index has to be greater than 0.");
}
this.m_Fold = fold;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String seedTipText() {
return "the random number seed for shuffling the dataset. If seed is negative, shuffling will not be performed.";
}
/**
* Gets the random number seed used for shuffling the dataset.
*
* @return the random number seed
*/
public long getSeed() {
return this.m_Seed;
}
/**
* Sets the random number seed for shuffling the dataset. If seed is negative,
* shuffling won't be performed.
*
* @param seed the random number seed
*/
public void setSeed(final long seed) {
this.m_Seed = seed;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 because outputFormat can be collected immediately
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
if ((this.m_NumFolds > 0) && (this.m_NumFolds < this.m_Fold)) {
throw new IllegalArgumentException("Fold has to be smaller or equal to " + "number of folds.");
}
super.setInputFormat(instanceInfo);
this.setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isFirstBatchDone()) {
this.push(instance);
return true;
} else {
this.bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished. Output() may
* now be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @throws InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
Instances instances;
if (!this.isFirstBatchDone()) {
if (this.m_Seed > 0) {
// User has provided a random number seed.
this.getInputFormat().randomize(new Random(this.m_Seed));
}
// Push instances for output into output queue
// Select out a fold
if (!this.m_Inverse) {
instances = this.getInputFormat().testCV(this.m_NumFolds, this.m_Fold - 1);
} else {
instances = this.getInputFormat().trainCV(this.m_NumFolds, this.m_Fold - 1);
}
} else {
instances = this.getInputFormat();
}
this.flushInput();
for (int i = 0; i < instances.numInstances(); i++) {
this.push(instances.instance(i), false); // No need to copy instance because of bufferInput()
}
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new RemoveFolds(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveFrequentValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveFrequentValues.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.AttributeStats;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.SingleIndex;
import weka.core.UnsupportedAttributeTypeException;
import weka.core.Utils;
import weka.core.WeightedAttributesHandler;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Determines which values (frequent or infrequent
* ones) of an (nominal) attribute are retained and filters the instances
* accordingly. In case of values with the same frequency, they are kept in the
* way they appear in the original instances object. E.g. if you have the values
* "1,2,3,4" with the frequencies "10,5,5,3" and you chose to keep the 2 most
* common values, the values "1,2" would be returned, since the value "2" comes
* before "3", even though they have the same frequency.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <num>
* Choose attribute to be used for selection.
* </pre>
*
* <pre>
* -N <num>
* Number of values to retain for the specified attribute,
* i.e. the ones with the most instances (default 2).
* </pre>
*
* <pre>
* -L
* Instead of values with the most instances the ones with the
* least are retained.
* </pre>
*
* <pre>
* -H
* When selecting on nominal attributes, removes header
* references to excluded values.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class RemoveFrequentValues extends Filter implements OptionHandler, UnsupervisedFilter, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = -2447432930070059511L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** the number of values to retain. */
protected int m_NumValues = 2;
/** whether to retain values with least instances instead of most. */
protected boolean m_LeastValues = false;
/** whether to invert the matching sense. */
protected boolean m_Invert = false;
/** Modify header for nominal attributes? */
protected boolean m_ModifyHeader = false;
/** If m_ModifyHeader, stores a mapping from old to new indexes */
protected int[] m_NominalMapping;
/** contains the values to retain */
protected HashSet<String> m_Values = null;
/**
* Returns a string describing this filter
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Determines which values (frequent or infrequent ones) of an " + "(nominal) attribute are retained and filters the instances " + "accordingly. In case of values with the same frequency, they are "
+ "kept in the way they appear in the original instances object. E.g. " + "if you have the values \"1,2,3,4\" with the frequencies \"10,5,5,3\" " + "and you chose to keep the 2 most common values, the values \"1,2\" "
+ "would be returned, since the value \"2\" comes before \"3\", even " + "though they have the same frequency.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(5);
newVector.addElement(new Option("\tChoose attribute to be used for selection.", "C", 1, "-C <num>"));
newVector.addElement(new Option("\tNumber of values to retain for the specified attribute, \n" + "\ti.e. the ones with the most instances (default 2).", "N", 1, "-N <num>"));
newVector.addElement(new Option("\tInstead of values with the most instances the ones with the \n" + "\tleast are retained.\n", "L", 0, "-L"));
newVector.addElement(new Option("\tWhen selecting on nominal attributes, removes header\n" + "\treferences to excluded values.", "H", 0, "-H"));
newVector.addElement(new Option("\tInvert matching sense.", "V", 0, "-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <num>
* Choose attribute to be used for selection.
* </pre>
*
* <pre>
* -N <num>
* Number of values to retain for the sepcified attribute,
* i.e. the ones with the most instances (default 2).
* </pre>
*
* <pre>
* -L
* Instead of values with the most instances the ones with the
* least are retained.
* </pre>
*
* <pre>
* -H
* When selecting on nominal attributes, removes header
* references to excluded values.
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(final String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
this.setAttributeIndex(attIndex);
} else {
this.setAttributeIndex("last");
}
String numValues = Utils.getOption('N', options);
if (numValues.length() != 0) {
this.setNumValues(Integer.parseInt(numValues));
} else {
this.setNumValues(2);
}
this.setUseLeastValues(Utils.getFlag('L', options));
this.setModifyHeader(Utils.getFlag('H', options));
this.setInvertSelection(Utils.getFlag('V', options));
if (this.getInputFormat() != null) {
this.setInputFormat(this.getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-C");
options.add("" + (this.getAttributeIndex()));
options.add("-N");
options.add("" + (this.getNumValues()));
if (this.getUseLeastValues()) {
options.add("-H");
}
if (this.getModifyHeader()) {
options.add("-H");
}
if (this.getInvertSelection()) {
options.add("-V");
}
return options.toArray(new String[0]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Choose attribute to be used for selection (default last).";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return this.m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(final String attIndex) {
this.m_AttIndex.setSingleIndex(attIndex);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numValuesTipText() {
return "The number of values to retain.";
}
/**
* Gets how many values are retained
*
* @return how many values are retained
*/
public int getNumValues() {
return this.m_NumValues;
}
/**
* Sets how many values are retained
*
* @param numValues the number of values to retain
*/
public void setNumValues(final int numValues) {
this.m_NumValues = numValues;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String useLeastValuesTipText() {
return "Retains values with least instance instead of most.";
}
/**
* Gets whether to use values with least or most instances
*
* @return true if values with least instances are retained
*/
public boolean getUseLeastValues() {
return this.m_LeastValues;
}
/**
* Sets whether to use values with least or most instances
*
* @param leastValues whether values with least or most instances are retained
*/
public void setUseLeastValues(final boolean leastValues) {
this.m_LeastValues = leastValues;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String modifyHeaderTipText() {
return "When selecting on nominal attributes, removes header references to " + "excluded values.";
}
/**
* Gets whether the header will be modified when selecting on nominal
* attributes.
*
* @return true if so.
*/
public boolean getModifyHeader() {
return this.m_ModifyHeader;
}
/**
* Sets whether the header will be modified when selecting on nominal
* attributes.
*
* @param newModifyHeader true if so.
*/
public void setModifyHeader(final boolean newModifyHeader) {
this.m_ModifyHeader = newModifyHeader;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Invert matching sense.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return this.m_Invert;
}
/**
* Set whether selected values should be removed or kept. If true the selected
* values are kept and unselected values are deleted.
*
* @param invert the new invert setting
*/
public void setInvertSelection(final boolean invert) {
this.m_Invert = invert;
}
/**
* Returns true if selection attribute is nominal.
*
* @return true if selection attribute is nominal
*/
public boolean isNominal() {
if (this.getInputFormat() == null) {
return false;
} else {
return this.getInputFormat().attribute(this.m_AttIndex.getIndex()).isNominal();
}
}
/**
* determines the values to retain, it is always at least 1 and up to the
* maximum number of distinct values
*
* @param inst the Instances to determine the values from which are kept
* @throws InterruptedException
*/
public void determineValues(final Instances inst) throws InterruptedException {
int i;
AttributeStats stats;
int attIdx;
int min;
int max;
int count;
this.m_AttIndex.setUpper(inst.numAttributes() - 1);
attIdx = this.m_AttIndex.getIndex();
// init names
this.m_Values = new HashSet<String>();
// number of values to retain
stats = inst.attributeStats(attIdx);
if (this.m_Invert) {
count = stats.nominalCounts.length - this.m_NumValues;
} else {
count = this.m_NumValues;
}
// out of bounds? -> fix
if (count < 1) {
count = 1; // at least one value!
}
if (count > stats.nominalCounts.length) {
count = stats.nominalCounts.length; // at max the existing values
}
// determine min/max occurences
Arrays.sort(stats.nominalCounts);
if (this.m_LeastValues) {
min = stats.nominalCounts[0];
max = stats.nominalCounts[count - 1];
} else {
min = stats.nominalCounts[(stats.nominalCounts.length - 1) - count + 1];
max = stats.nominalCounts[stats.nominalCounts.length - 1];
}
// add values if they are inside min/max (incl. borders) and not more than
// count
stats = inst.attributeStats(attIdx);
for (i = 0; i < stats.nominalCounts.length; i++) {
if ((stats.nominalCounts[i] >= min) && (stats.nominalCounts[i] <= max) && (this.m_Values.size() < count)) {
this.m_Values.add(inst.attribute(attIdx).value(i));
}
}
}
/**
* modifies the header of the Instances and returns the format w/o any
* instances
*
* @param instanceInfo the instances structure to modify
* @return the new structure (w/o instances!)
*/
protected Instances modifyHeader(Instances instanceInfo) {
instanceInfo = new Instances(this.getInputFormat(), 0); // copy before modifying
Attribute oldAtt = instanceInfo.attribute(this.m_AttIndex.getIndex());
int[] selection = new int[this.m_Values.size()];
Iterator<String> iter = this.m_Values.iterator();
int i = 0;
while (iter.hasNext()) {
selection[i] = oldAtt.indexOfValue(iter.next().toString());
i++;
}
ArrayList<String> newVals = new ArrayList<String>();
for (i = 0; i < selection.length; i++) {
newVals.add(oldAtt.value(selection[i]));
}
Attribute newAtt = new Attribute(oldAtt.name(), newVals);
newAtt.setWeight(oldAtt.weight());
instanceInfo.replaceAttributeAt(newAtt, this.m_AttIndex.getIndex());
this.m_NominalMapping = new int[oldAtt.numValues()];
for (i = 0; i < this.m_NominalMapping.length; i++) {
boolean found = false;
for (int j = 0; j < selection.length; j++) {
if (selection[j] == i) {
this.m_NominalMapping[i] = j;
found = true;
break;
}
}
if (!found) {
this.m_NominalMapping[i] = -1;
}
}
return instanceInfo;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 can be collected immediately
* @throws UnsupportedAttributeTypeException if the specified attribute is not
* nominal.
*/
@Override
public boolean setInputFormat(final Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
this.m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
if (!this.isNominal()) {
throw new UnsupportedAttributeTypeException("Can only handle nominal attributes.");
}
this.m_Values = null;
return false;
}
/**
* Set the output format. Takes the currently defined Values to retain and
* m_InputFormat and calls setOutputFormat(Instances) appropriately. Those
* instances that have a value to retain are "push"ed to the output.
*/
protected void setOutputFormat() {
Instances instances;
int i;
Instance instance;
if (this.m_Values == null) {
this.setOutputFormat(null);
return;
}
// get structure
if (this.getModifyHeader()) {
instances = this.modifyHeader(this.getInputFormat());
} else {
instances = new Instances(this.getInputFormat(), 0);
}
this.setOutputFormat(instances);
// remove instances with unwanted values, for the others change the values
// value if m_ModifyHeader is set
for (i = 0; i < this.getInputFormat().numInstances(); i++) {
instance = this.getInputFormat().instance(i);
if (instance.isMissing(this.m_AttIndex.getIndex())) {
this.push(instance, false); // No need to copy because of bufferInput()
continue;
}
if (this.m_Values.contains(instance.stringValue(this.m_AttIndex.getIndex()))) {
if (this.getModifyHeader()) {
instance.setValue(this.m_AttIndex.getIndex(), this.m_NominalMapping[(int) instance.value(this.m_AttIndex.getIndex())]);
}
this.push(instance, false); // No need to copy because of bufferInput()
}
}
}
/**
* 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 set.
*/
@Override
public boolean input(final Instance instance) {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (this.m_NewBatch) {
this.resetQueue();
this.m_NewBatch = false;
}
if (this.isFirstBatchDone()) {
this.push(instance);
return true;
} else {
this.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 InterruptedException
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws InterruptedException {
if (this.getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
// process input
if (this.m_Values == null) {
this.determineValues(this.getInputFormat());
this.setOutputFormat();
}
this.flushInput();
this.m_NewBatch = true;
this.m_FirstBatchDone = true;
return (this.numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(final String[] argv) {
runFilter(new RemoveFrequentValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveMisclassified.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveMisclassified.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.Classifier;
import weka.core.*;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that removes instances which are
* incorrectly classified. Useful for removing outliers.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <classifier specification>
* Full class name of classifier to use, followed
* by scheme options. eg:
* "weka.classifiers.bayes.NaiveBayes -D"
* (default: weka.classifiers.rules.ZeroR)
* </pre>
*
* <pre>
* -C <class index>
* Attribute on which misclassifications are based.
* If < 0 will use any current set class or default to the last attribute.
* </pre>
*
* <pre>
* -F <number of folds>
* The number of folds to use for cross-validation cleansing.
* (<2 = no cross-validation - default).
* </pre>
*
* <pre>
* -T <threshold>
* Threshold for the max error when predicting numeric class.
* (Value should be >= 0, default = 0.1).
* </pre>
*
* <pre>
* -I
* The maximum number of cleansing iterations to perform.
* (<1 = until fully cleansed - default)
* </pre>
*
* <pre>
* -V
* Invert the match so that correctly classified instances are discarded.
* </pre>
*
* <!-- options-end -->
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Malcolm Ware (mfw4@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveMisclassified extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = 5469157004717663171L;
/** The classifier used to do the cleansing */
protected Classifier m_cleansingClassifier = new weka.classifiers.rules.ZeroR();
/** The attribute to treat as the class for purposes of cleansing. */
protected int m_classIndex = -1;
/**
* The number of cross validation folds to perform (<2 = no cross
* validation)
*/
protected int m_numOfCrossValidationFolds = 0;
/**
* The maximum number of cleansing iterations to perform (<1 = until fully
* cleansed)
*/
protected int m_numOfCleansingIterations = 0;
/** The threshold for deciding when a numeric value is correctly classified */
protected double m_numericClassifyThreshold = 0.1;
/**
* Whether to invert the match so the correctly classified instances are
* discarded
*/
protected boolean m_invertMatching = false;
/** Have we processed the first batch (i.e. training data)? */
protected boolean m_firstBatchFinished = false;
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result;
if (getClassifier() == null) {
result = super.getCapabilities();
result.disableAll();
} else {
result = getClassifier().getCapabilities();
}
result.setMinimumNumberInstances(0);
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 inputFormat can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
m_firstBatchFinished = false;
return true;
}
/**
* Cleanses the data based on misclassifications when used training data.
*
* @param data the data to train with and cleanse
* @return the cleansed data
* @throws Exception if something goes wrong
*/
private Instances cleanseTrain(Instances data) throws Exception {
Instance inst;
Instances buildSet = new Instances(data);
Instances temp;
Instances inverseSet = new Instances(data, data.numInstances());
int count = 0;
double ans;
int iterations = 0;
int classIndex = m_classIndex;
if (classIndex < 0) {
classIndex = data.classIndex();
}
if (classIndex < 0) {
classIndex = data.numAttributes() - 1;
}
// loop until perfect
while (count != buildSet.numInstances()) {
// check if hit maximum number of iterations
iterations++;
if (m_numOfCleansingIterations > 0
&& iterations > m_numOfCleansingIterations) {
break;
}
// build classifier
count = buildSet.numInstances();
buildSet.setClassIndex(classIndex);
m_cleansingClassifier.buildClassifier(buildSet);
temp = new Instances(buildSet, buildSet.numInstances());
// test on training data
for (int i = 0; i < buildSet.numInstances(); i++) {
inst = buildSet.instance(i);
ans = m_cleansingClassifier.classifyInstance(inst);
if (buildSet.classAttribute().isNumeric()) {
if (ans >= inst.classValue() - m_numericClassifyThreshold
&& ans <= inst.classValue() + m_numericClassifyThreshold) {
temp.add(inst);
} else if (m_invertMatching) {
inverseSet.add(inst);
}
} else { // class is nominal
if (ans == inst.classValue()) {
temp.add(inst);
} else if (m_invertMatching) {
inverseSet.add(inst);
}
}
}
buildSet = temp;
}
if (m_invertMatching) {
inverseSet.setClassIndex(data.classIndex());
return inverseSet;
} else {
buildSet.setClassIndex(data.classIndex());
return buildSet;
}
}
/**
* Cleanses the data based on misclassifications when performing
* cross-validation.
*
* @param data the data to train with and cleanse
* @return the cleansed data
* @throws Exception if something goes wrong
*/
private Instances cleanseCross(Instances data) throws Exception {
Instance inst;
Instances crossSet = new Instances(data);
Instances temp = new Instances(data, data.numInstances());
Instances inverseSet = new Instances(data, data.numInstances());
int count = 0;
double ans;
int iterations = 0;
int classIndex = m_classIndex;
if (classIndex < 0) {
classIndex = data.classIndex();
}
if (classIndex < 0) {
classIndex = data.numAttributes() - 1;
}
// loop until perfect
while (count != crossSet.numInstances()
&& crossSet.numInstances() >= m_numOfCrossValidationFolds) {
count = crossSet.numInstances();
// check if hit maximum number of iterations
iterations++;
if (m_numOfCleansingIterations > 0
&& iterations > m_numOfCleansingIterations) {
break;
}
crossSet.setClassIndex(classIndex);
if (crossSet.classAttribute().isNominal()) {
crossSet.stratify(m_numOfCrossValidationFolds);
}
// do the folds
temp = new Instances(crossSet, crossSet.numInstances());
for (int fold = 0; fold < m_numOfCrossValidationFolds; fold++) {
Instances train = crossSet.trainCV(m_numOfCrossValidationFolds, fold);
m_cleansingClassifier.buildClassifier(train);
Instances test = crossSet.testCV(m_numOfCrossValidationFolds, fold);
// now test
for (int i = 0; i < test.numInstances(); i++) {
inst = test.instance(i);
ans = m_cleansingClassifier.classifyInstance(inst);
if (crossSet.classAttribute().isNumeric()) {
if (ans >= inst.classValue() - m_numericClassifyThreshold
&& ans <= inst.classValue() + m_numericClassifyThreshold) {
temp.add(inst);
} else if (m_invertMatching) {
inverseSet.add(inst);
}
} else { // class is nominal
if (ans == inst.classValue()) {
temp.add(inst);
} else if (m_invertMatching) {
inverseSet.add(inst);
}
}
}
}
crossSet = temp;
}
if (m_invertMatching) {
inverseSet.setClassIndex(data.classIndex());
return inverseSet;
} else {
crossSet.setClassIndex(data.classIndex());
return crossSet;
}
}
/**
* Input an instance for filtering.
*
* @param instance the input instance
* @return true if the filtered instance may now be collected with output().
* @throws NullPointerException if the input format has not been defined.
* @throws Exception if the input instance was not of the correct format or if
* there was a problem with the filtering.
*/
@Override
public boolean input(Instance instance) throws Exception {
if (inputFormatPeek() == null) {
throw new NullPointerException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (m_firstBatchFinished) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @throws IllegalStateException if no input structure has been defined
*/
@Override
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!m_firstBatchFinished) {
Instances filtered;
if (m_numOfCrossValidationFolds < 2) {
filtered = cleanseTrain(getInputFormat());
} else {
filtered = cleanseCross(getInputFormat());
}
for (int i = 0; i < filtered.numInstances(); i++) {
push(filtered.instance(i), false); // No need to copy
}
m_firstBatchFinished = true;
flushInput();
}
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(6);
newVector.addElement(new Option(
"\tFull class name of classifier to use, followed\n"
+ "\tby scheme options. eg:\n"
+ "\t\t\"weka.classifiers.bayes.NaiveBayes -D\"\n"
+ "\t(default: weka.classifiers.rules.ZeroR)", "W", 1,
"-W <classifier specification>"));
newVector
.addElement(new Option(
"\tAttribute on which misclassifications are based.\n"
+ "\tIf < 0 will use any current set class or default to the last attribute.",
"C", 1, "-C <class index>"));
newVector.addElement(new Option(
"\tThe number of folds to use for cross-validation cleansing.\n"
+ "\t(<2 = no cross-validation - default).", "F", 1,
"-F <number of folds>"));
newVector
.addElement(new Option(
"\tThreshold for the max error when predicting numeric class.\n"
+ "\t(Value should be >= 0, default = 0.1).", "T", 1,
"-T <threshold>"));
newVector.addElement(new Option(
"\tThe maximum number of cleansing iterations to perform.\n"
+ "\t(<1 = until fully cleansed - default)", "I", 1, "-I"));
newVector
.addElement(new Option(
"\tInvert the match so that correctly classified instances are discarded.\n",
"V", 0, "-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -W <classifier specification>
* Full class name of classifier to use, followed
* by scheme options. eg:
* "weka.classifiers.bayes.NaiveBayes -D"
* (default: weka.classifiers.rules.ZeroR)
* </pre>
*
* <pre>
* -C <class index>
* Attribute on which misclassifications are based.
* If < 0 will use any current set class or default to the last attribute.
* </pre>
*
* <pre>
* -F <number of folds>
* The number of folds to use for cross-validation cleansing.
* (<2 = no cross-validation - default).
* </pre>
*
* <pre>
* -T <threshold>
* Threshold for the max error when predicting numeric class.
* (Value should be >= 0, default = 0.1).
* </pre>
*
* <pre>
* -I
* The maximum number of cleansing iterations to perform.
* (<1 = until fully cleansed - default)
* </pre>
*
* <pre>
* -V
* Invert the match so that correctly classified instances are discarded.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String classifierString = Utils.getOption('W', options);
if (classifierString.length() == 0) {
classifierString = weka.classifiers.rules.ZeroR.class.getName();
}
String[] classifierSpec = Utils.splitOptions(classifierString);
if (classifierSpec.length == 0) {
throw new Exception("Invalid classifier specification string");
}
String classifierName = classifierSpec[0];
classifierSpec[0] = "";
setClassifier(AbstractClassifier.forName(classifierName, classifierSpec));
String cString = Utils.getOption('C', options);
if (cString.length() != 0) {
setClassIndex((new Double(cString)).intValue());
} else {
setClassIndex(-1);
}
String fString = Utils.getOption('F', options);
if (fString.length() != 0) {
setNumFolds((new Double(fString)).intValue());
} else {
setNumFolds(0);
}
String tString = Utils.getOption('T', options);
if (tString.length() != 0) {
setThreshold((new Double(tString)).doubleValue());
} else {
setThreshold(0.1);
}
String iString = Utils.getOption('I', options);
if (iString.length() != 0) {
setMaxIterations((new Double(iString)).intValue());
} else {
setMaxIterations(0);
}
if (Utils.getFlag('V', options)) {
setInvert(true);
} else {
setInvert(false);
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-W");
options.add("" + getClassifierSpec());
options.add("-C");
options.add("" + getClassIndex());
options.add("-F");
options.add("" + getNumFolds());
options.add("-T");
options.add("" + getThreshold());
options.add("-I");
options.add("" + getMaxIterations());
if (getInvert()) {
options.add("-V");
}
return options.toArray(new String[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 "A filter that removes instances which are incorrectly classified. "
+ "Useful for removing outliers.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classifierTipText() {
return "The classifier upon which to base the misclassifications.";
}
/**
* Sets the classifier to classify instances with.
*
* @param classifier The classifier to be used (with its options set).
*/
public void setClassifier(Classifier classifier) {
m_cleansingClassifier = classifier;
}
/**
* Gets the classifier used by the filter.
*
* @return The classifier to be used.
*/
public Classifier getClassifier() {
return m_cleansingClassifier;
}
/**
* Gets the classifier specification string, which contains the class name of
* the classifier and any options to the classifier.
*
* @return the classifier string.
*/
protected String getClassifierSpec() {
Classifier c = getClassifier();
if (c instanceof OptionHandler) {
return c.getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler) c).getOptions());
}
return c.getClass().getName();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String classIndexTipText() {
return "Index of the class upon which to base the misclassifications. "
+ "If < 0 will use any current set class or default to the last attribute.";
}
/**
* Sets the attribute on which misclassifications are based. If < 0 will
* use any current set class or default to the last attribute.
*
* @param classIndex the class index.
*/
public void setClassIndex(int classIndex) {
m_classIndex = classIndex;
}
/**
* Gets the attribute on which misclassifications are based.
*
* @return the class index.
*/
public int getClassIndex() {
return m_classIndex;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numFoldsTipText() {
return "The number of cross-validation folds to use. If < 2 then no cross-validation will be performed.";
}
/**
* Sets the number of cross-validation folds to use - < 2 means no
* cross-validation.
*
* @param numOfFolds the number of folds.
*/
public void setNumFolds(int numOfFolds) {
m_numOfCrossValidationFolds = numOfFolds;
}
/**
* Gets the number of cross-validation folds used by the filter.
*
* @return the number of folds.
*/
public int getNumFolds() {
return m_numOfCrossValidationFolds;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String thresholdTipText() {
return "Threshold for the max allowable error when predicting a numeric class. Should be >= 0.";
}
/**
* Sets the threshold for the max error when predicting a numeric class. The
* value should be >= 0.
*
* @param threshold the numeric theshold.
*/
public void setThreshold(double threshold) {
m_numericClassifyThreshold = threshold;
}
/**
* Gets the threshold for the max error when predicting a numeric class.
*
* @return the numeric threshold.
*/
public double getThreshold() {
return m_numericClassifyThreshold;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxIterationsTipText() {
return "The maximum number of iterations to perform. < 1 means filter will go until fully cleansed.";
}
/**
* Sets the maximum number of cleansing iterations to perform - < 1 means
* go until fully cleansed
*
* @param iterations the maximum number of iterations.
*/
public void setMaxIterations(int iterations) {
m_numOfCleansingIterations = iterations;
}
/**
* Gets the maximum number of cleansing iterations performed
*
* @return the maximum number of iterations.
*/
public int getMaxIterations() {
return m_numOfCleansingIterations;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertTipText() {
return "Whether or not to invert the selection. If true, correctly classified instances will be discarded.";
}
/**
* Set whether selection is inverted.
*
* @param invert whether or not to invert selection.
*/
public void setInvert(boolean invert) {
m_invertMatching = invert;
}
/**
* Get whether selection is inverted.
*
* @return whether or not selection is inverted.
*/
public boolean getInvert() {
return m_invertMatching;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RemoveMisclassified(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemovePercentage.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemovePercentage.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that removes a given percentage of a
* dataset.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -P <percentage>
* Specifies percentage of instances to select. (default 50)
* </pre>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <!-- options-end -->
*
* @author Richard Kirkby (eibe@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemovePercentage extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 2150341191158533133L;
/** Percentage of instances to select. */
private double m_Percentage = 50;
/** Indicates if inverse of selection is to be output. */
private boolean m_Inverse = false;
/**
* Gets an enumeration describing the available options..
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option(
"\tSpecifies percentage of instances to select. (default 50)\n", "P", 1,
"-P <percentage>"));
newVector.addElement(new Option(
"\tSpecifies if inverse of selection is to be output.\n", "V", 0, "-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -P <percentage>
* Specifies percentage of instances to select. (default 50)
* </pre>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String percent = Utils.getOption('P', options);
if (percent.length() != 0) {
setPercentage(Double.parseDouble(percent));
} else {
setPercentage(50.0);
}
setInvertSelection(Utils.getFlag('V', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-P");
options.add("" + getPercentage());
if (getInvertSelection()) {
options.add("-V");
}
return options.toArray(new String[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 "A filter that removes a given percentage of a dataset.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String percentageTipText() {
return "The percentage of the data to select.";
}
/**
* Gets the percentage of instances to select.
*
* @return the percentage.
*/
public double getPercentage() {
return m_Percentage;
}
/**
* Sets the percentage of intances to select.
*
* @param percent the percentage
* @throws IllegalArgumentException if percentage out of range
*/
public void setPercentage(double percent) {
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException(
"Percentage must be between 0 and 100.");
}
m_Percentage = percent;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to invert the selection.";
}
/**
* Gets if selection is to be inverted.
*
* @return true if the selection is to be inverted
*/
public boolean getInvertSelection() {
return m_Inverse;
}
/**
* Sets if selection is to be inverted.
*
* @param inverse true if inversion is to be performed
*/
public void setInvertSelection(boolean inverse) {
m_Inverse = inverse;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 because outputFormat can be collected immediately
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
return true;
}
/**
* 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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished. 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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
// Push instances for output into output queue
Instances toFilter = getInputFormat();
int cutOff = (int) Math.round(toFilter.numInstances() * m_Percentage / 100);
if (m_Inverse) {
for (int i = 0; i < cutOff; i++) {
push(toFilter.instance(i), false); // No need to copy
}
} else {
for (int i = cutOff; i < toFilter.numInstances(); i++) {
push(toFilter.instance(i), false); // No need to copy
}
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RemovePercentage(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveRange.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveRange.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> A filter that removes a given range of instances of
* a dataset.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <inst1,inst2-inst4,...>
* Specifies list of instances to select. First and last
* are valid indexes. (required)
* </pre>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveRange extends Filter implements UnsupervisedFilter,
OptionHandler, WeightedAttributesHandler, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -3064641215340828695L;
/** Range of instances requested by the user. */
private final Range m_Range = new Range("first-last");
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(2);
newVector.addElement(new Option(
"\tSpecifies list of instances to select. First and last\n"
+ "\tare valid indexes. (required)\n", "R", 1,
"-R <inst1,inst2-inst4,...>"));
newVector.addElement(new Option(
"\tSpecifies if inverse of selection is to be output.\n", "V", 0, "-V"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -R <inst1,inst2-inst4,...>
* Specifies list of instances to select. First and last
* are valid indexes. (required)
* </pre>
*
* <pre>
* -V
* Specifies if inverse of selection is to be output.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of string.s
* @throws Exception if an option is not supported.
*/
@Override
public void setOptions(String[] options) throws Exception {
String str = Utils.getOption('R', options);
if (str.length() != 0) {
setInstancesIndices(str);
} else {
setInstancesIndices("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions.
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getInvertSelection()) {
options.add("-V");
}
options.add("-R");
options.add(getInstancesIndices());
return options.toArray(new String[0]);
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for displaying in the GUI.
*/
public String globalInfo() {
return "A filter that removes a given range of instances of a dataset.";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String instancesIndicesTipText() {
return "The range of instances to select. First and last are valid indexes.";
}
/**
* Gets ranges of instances selected.
*
* @return a string containing a comma-separated list of ranges
*/
public String getInstancesIndices() {
return m_Range.getRanges();
}
/**
* Sets the ranges of instances to be selected. If provided string is null,
* ranges won't be used for selecting instances.
*
* @param rangeList a string representing the list of instances. eg:
* first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setInstancesIndices(String rangeList) {
m_Range.setRanges(rangeList);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Whether to invert the selection.";
}
/**
* Gets if selection is to be inverted.
*
* @return true if the selection is to be inverted
*/
public boolean getInvertSelection() {
return m_Range.getInvert();
}
/**
* Sets if selection is to be inverted.
*
* @param inverse true if inversion is to be performed
*/
public void setInvertSelection(boolean inverse) {
m_Range.setInvert(inverse);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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 because outputFormat can be collected immediately
* @throws Exception if the input format can't be set successfully
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify that this batch of input to the filter is finished. 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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isFirstBatchDone()) {
// Push instances for output into output queue
m_Range.setUpper(getInputFormat().numInstances() - 1);
for (int i = 0; i < getInputFormat().numInstances(); i++) {
if (!m_Range.isInRange(i)) {
push(getInputFormat().instance(i), false); // No need to copy
}
}
} else {
for (int i = 0; i < getInputFormat().numInstances(); i++) {
push(getInputFormat().instance(i), false); // No need to copy
}
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RemoveRange(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/RemoveWithValues.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* RemoveWithValues.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.StreamableFilter;
import weka.filters.UnsupervisedFilter;
/**
* <!-- globalinfo-start --> Filters instances according to the value of an
* attribute.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <num>
* Choose attribute to be used for selection.
* </pre>
*
* <pre>
* -S <num>
* Numeric value to be used for selection on numeric
* attribute.
* Instances with values smaller than given value will
* be selected. (default 0)
* </pre>
*
* <pre>
* -L <index1,index2-index4,...>
* Range of label indices to be used for selection on
* nominal attribute.
* First and last are valid indexes. (default all values)
* </pre>
*
* <pre>
* -M
* Missing values count as a match. This setting is
* independent of the -V option.
* (default missing values don't match)
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -H
* When selecting on nominal attributes, removes header
* references to excluded values.
* </pre>
*
* <pre>
* -F
* Do not apply the filter to instances that arrive after the first
* (training) batch. The default is to apply the filter (i.e.
* the filter may not return an instance if it matches the remove criteria)
* </pre>
*
* <!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class RemoveWithValues extends Filter implements UnsupervisedFilter,
StreamableFilter, OptionHandler, WeightedInstancesHandler, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 4752870193679263361L;
/** The attribute's index setting. */
private final SingleIndex m_AttIndex = new SingleIndex("last");
/** Stores which values of nominal attribute are to be used for filtering. */
protected Range m_Values;
/** Stores which value of a numeric attribute is to be used for filtering. */
protected double m_Value = 0;
/** True if missing values should count as a match */
protected boolean m_MatchMissingValues = false;
/** Modify header for nominal attributes? */
protected boolean m_ModifyHeader = false;
/** If m_ModifyHeader, stores a mapping from old to new indexes */
protected int[] m_NominalMapping;
/** Whether to filter instances after the first batch has been processed */
protected boolean m_dontFilterAfterFirstBatch = false;
/**
* Returns a string describing this classifier
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Filters instances according to the value of an attribute.";
}
/** Default constructor */
public RemoveWithValues() {
m_Values = new Range("first-last");
m_Values.setInvert(true);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(7);
newVector.addElement(new Option(
"\tChoose attribute to be used for selection.", "C", 1, "-C <num>"));
newVector.addElement(new Option(
"\tNumeric value to be used for selection on numeric\n"
+ "\tattribute.\n"
+ "\tInstances with values smaller than given value will\n"
+ "\tbe selected. (default 0)", "S", 1, "-S <num>"));
newVector.addElement(new Option(
"\tRange of label indices to be used for selection on\n"
+ "\tnominal attribute.\n"
+ "\tFirst and last are valid indexes. (default all values)", "L", 1,
"-L <index1,index2-index4,...>"));
newVector.addElement(new Option(
"\tMissing values count as a match. This setting is\n"
+ "\tindependent of the -V option.\n"
+ "\t(default missing values don't match)", "M", 0, "-M"));
newVector.addElement(new Option("\tInvert matching sense.", "V", 0, "-V"));
newVector.addElement(new Option(
"\tWhen selecting on nominal attributes, removes header\n"
+ "\treferences to excluded values.", "H", 0, "-H"));
newVector
.addElement(new Option(
"\tDo not apply the filter to instances that arrive after the first\n"
+ "\t(training) batch. The default is to apply the filter (i.e.\n"
+ "\tthe filter may not return an instance if it matches the remove criteria)",
"F", 0, "-F"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C <num>
* Choose attribute to be used for selection.
* </pre>
*
* <pre>
* -S <num>
* Numeric value to be used for selection on numeric
* attribute.
* Instances with values smaller than given value will
* be selected. (default 0)
* </pre>
*
* <pre>
* -L <index1,index2-index4,...>
* Range of label indices to be used for selection on
* nominal attribute.
* First and last are valid indexes. (default all values)
* </pre>
*
* <pre>
* -M
* Missing values count as a match. This setting is
* independent of the -V option.
* (default missing values don't match)
* </pre>
*
* <pre>
* -V
* Invert matching sense.
* </pre>
*
* <pre>
* -H
* When selecting on nominal attributes, removes header
* references to excluded values.
* </pre>
*
* <pre>
* -F
* Do not apply the filter to instances that arrive after the first
* (training) batch. The default is to apply the filter (i.e.
* the filter may not return an instance if it matches the remove criteria)
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String attIndex = Utils.getOption('C', options);
if (attIndex.length() != 0) {
setAttributeIndex(attIndex);
} else {
setAttributeIndex("last");
}
String splitPoint = Utils.getOption('S', options);
if (splitPoint.length() != 0) {
setSplitPoint((new Double(splitPoint)).doubleValue());
} else {
setSplitPoint(0);
}
String convertList = Utils.getOption('L', options);
if (convertList.length() != 0) {
setNominalIndices(convertList);
} else {
setNominalIndices("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
setMatchMissingValues(Utils.getFlag('M', options));
setModifyHeader(Utils.getFlag('H', options));
setDontFilterAfterFirstBatch(Utils.getFlag('F', options));
// Re-initialize output format according to new options
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
options.add("-S");
options.add("" + getSplitPoint());
options.add("-C");
options.add("" + (getAttributeIndex()));
if (!getNominalIndices().equals("")) {
options.add("-L");
options.add(getNominalIndices());
}
if (getInvertSelection()) {
options.add("-V");
}
if (getMatchMissingValues()) {
options.add("-M");
}
if (getModifyHeader()) {
options.add("-H");
}
if (getDontFilterAfterFirstBatch()) {
options.add("-F");
}
return options.toArray(new String[0]);
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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).
* @throws UnsupportedAttributeTypeException if the specified attribute is
* neither numeric or nominal.
* @return true because outputFormat can be collected immediately
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_AttIndex.setUpper(instanceInfo.numAttributes() - 1);
if (!isNumeric() && !isNominal()) {
throw new UnsupportedAttributeTypeException("Can only handle numeric "
+ "or nominal attributes.");
}
m_Values
.setUpper(instanceInfo.attribute(m_AttIndex.getIndex()).numValues() - 1);
if (isNominal() && m_ModifyHeader) {
instanceInfo = new Instances(instanceInfo, 0); // copy before modifying
Attribute oldAtt = instanceInfo.attribute(m_AttIndex.getIndex());
int[] selection = m_Values.getSelection();
ArrayList<String> newVals = new ArrayList<String>();
for (int element : selection) {
newVals.add(oldAtt.value(element));
}
Attribute newAtt = new Attribute(oldAtt.name(), newVals);
newAtt.setWeight(oldAtt.weight());
instanceInfo.replaceAttributeAt(newAtt, m_AttIndex.getIndex());
m_NominalMapping = new int[oldAtt.numValues()];
for (int i = 0; i < m_NominalMapping.length; i++) {
boolean found = false;
for (int j = 0; j < selection.length; j++) {
if (selection[j] == i) {
m_NominalMapping[i] = j;
found = true;
break;
}
}
if (!found) {
m_NominalMapping[i] = -1;
}
}
}
setOutputFormat(instanceInfo);
return true;
}
/**
* 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 set.
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone() && m_dontFilterAfterFirstBatch) {
push((Instance) instance.copy(), false); // No need to copy
return true;
}
if (instance.isMissing(m_AttIndex.getIndex())) {
if (!getMatchMissingValues()) {
push((Instance) instance.copy(), false); // No need to copy
return true;
} else {
return false;
}
}
if (isNumeric()) {
if (!m_Values.getInvert()) {
if (instance.value(m_AttIndex.getIndex()) < m_Value) {
push((Instance) instance.copy(), false); // No need to copy
return true;
}
} else {
if (instance.value(m_AttIndex.getIndex()) >= m_Value) {
push((Instance) instance.copy(), false); // No need to copy
return true;
}
}
}
if (isNominal()) {
if (m_Values.isInRange((int) instance.value(m_AttIndex.getIndex()))) {
Instance temp = (Instance) instance.copy();
if (getModifyHeader()) {
temp.setValue(m_AttIndex.getIndex(),
m_NominalMapping[(int) instance.value(m_AttIndex.getIndex())]);
}
push(temp, false); // No need to copy
return true;
}
}
return false;
}
/**
* RemoveWithValues may return false from input() (thus not making an instance
* available immediately) even after the first batch has been completed due to
* matching a value that the user wants to remove. Therefore this method
* returns true.
*
* @return true
*/
@Override
public boolean mayRemoveInstanceAfterFirstBatchDone() {
return true;
}
/**
* Returns true if selection attribute is nominal.
*
* @return true if selection attribute is nominal
*/
public boolean isNominal() {
if (getInputFormat() == null) {
return false;
} else {
return getInputFormat().attribute(m_AttIndex.getIndex()).isNominal();
}
}
/**
* Returns true if selection attribute is numeric.
*
* @return true if selection attribute is numeric
*/
public boolean isNumeric() {
if (getInputFormat() == null) {
return false;
} else {
return getInputFormat().attribute(m_AttIndex.getIndex()).isNumeric();
}
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String modifyHeaderTipText() {
return "When selecting on nominal attributes, removes header references to "
+ "excluded values.";
}
/**
* Gets whether the header will be modified when selecting on nominal
* attributes.
*
* @return true if so.
*/
public boolean getModifyHeader() {
return m_ModifyHeader;
}
/**
* Sets whether the header will be modified when selecting on nominal
* attributes.
*
* @param newModifyHeader true if so.
*/
public void setModifyHeader(boolean newModifyHeader) {
m_ModifyHeader = newModifyHeader;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeIndexTipText() {
return "Choose attribute to be used for selection (default last).";
}
/**
* Get the index of the attribute used.
*
* @return the index of the attribute
*/
public String getAttributeIndex() {
return m_AttIndex.getSingleIndex();
}
/**
* Sets index of the attribute used.
*
* @param attIndex the index of the attribute
*/
public void setAttributeIndex(String attIndex) {
m_AttIndex.setSingleIndex(attIndex);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String splitPointTipText() {
return "Numeric value to be used for selection on numeric attribute. "
+ "Instances with values smaller than given value will be selected.";
}
/**
* Get the split point used for numeric selection
*
* @return the numeric split point
*/
public double getSplitPoint() {
return m_Value;
}
/**
* Split point to be used for selection on numeric attribute.
*
* @param value the split point
*/
public void setSplitPoint(double value) {
m_Value = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String matchMissingValuesTipText() {
return "Missing values count as a match. This setting is independent of "
+ "the invertSelection option.";
}
/**
* Gets whether missing values are counted as a match.
*
* @return true if missing values are counted as a match.
*/
public boolean getMatchMissingValues() {
return m_MatchMissingValues;
}
/**
* Sets whether missing values are counted as a match.
*
* @param newMatchMissingValues true if missing values are counted as a match.
*/
public void setMatchMissingValues(boolean newMatchMissingValues) {
m_MatchMissingValues = newMatchMissingValues;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Invert matching sense.";
}
/**
* Get whether the supplied columns are to be removed or kept
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return !m_Values.getInvert();
}
/**
* Set whether selected values should be removed or kept. If true the selected
* values are kept and unselected values are deleted.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_Values.setInvert(!invert);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String nominalIndicesTipText() {
return "Range of label indices to be used for selection on nominal attribute. "
+ "First and last are valid indexes.";
}
/**
* Get the set of nominal value indices that will be used for selection
*
* @return rangeList a string representing the list of nominal indices.
*/
public String getNominalIndices() {
return m_Values.getRanges();
}
/**
* Set which nominal labels are to be included in the selection.
*
* @param rangeList a string representing the list of nominal indices. eg:
* first-3,5,6-last
*/
public void setNominalIndices(String rangeList) {
m_Values.setRanges(rangeList);
}
/**
* Set whether to apply the filter to instances that arrive once the first
* (training) batch has been seen. The default is to not apply the filter and
* just return each instance input. This is so that, when used in the
* FilteredClassifier, a test instance does not get "consumed" by the filter
* and a prediction is always generated.
*
* @param b true if the filter should *not* be applied to instances that
* arrive after the first (training) batch has been processed.
*/
public void setDontFilterAfterFirstBatch(boolean b) {
m_dontFilterAfterFirstBatch = b;
}
/**
* Get whether to apply the filter to instances that arrive once the first
* (training) batch has been seen. The default is to not apply the filter and
* just return each instance input. This is so that, when used in the
* FilteredClassifier, a test instance does not get "consumed" by the filter
* and a prediction is always generated.
*
* @return true if the filter should *not* be applied to instances that arrive
* after the first (training) batch has been processed.
*/
public boolean getDontFilterAfterFirstBatch() {
return m_dontFilterAfterFirstBatch;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dontFilterAfterFirstBatchTipText() {
return "Whether to apply the filtering process to instances that "
+ "are input after the first (training) batch. The default "
+ "is false so instances in subsequent batches can potentially "
+ "get 'consumed' by the filter.";
}
/**
* Set which values of a nominal attribute are to be used for selection.
*
* @param values an array containing indexes of values to be used for
* selection
*/
public void setNominalIndicesArr(int[] values) {
String rangeList = "";
for (int i = 0; i < values.length; i++) {
if (i == 0) {
rangeList = "" + (values[i] + 1);
} else {
rangeList += "," + (values[i] + 1);
}
}
setNominalIndices(rangeList);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new RemoveWithValues(), argv);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/filters/unsupervised/instance/Resample.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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* Resample.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.filters.unsupervised.instance;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.core.*;
import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
import weka.gui.ProgrammaticProperty;
/**
* <!-- globalinfo-start --> Produces a random subsample of a dataset using
* either sampling with replacement or without replacement. The original dataset
* must fit entirely in memory. The number of instances in the generated dataset
* may be specified. When used in batch mode, subsequent batches are NOT
* resampled.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -Z <num>
* The size of the output dataset, as a percentage of
* the input dataset (default 100)
* </pre>
*
* <pre>
* -no-replacement
* Disables replacement of instances
* (default: with replacement)
* </pre>
*
* <pre>
* -V
* Inverts the selection - only available with '-no-replacement'.
* </pre>
*
* <!-- options-end -->
*
* @author Len Trigg (len@reeltwo.com)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @author Eibe Frank
* @version $Revision$
*/
public class Resample extends Filter implements UnsupervisedFilter,
OptionHandler, Randomizable, WeightedAttributesHandler {
/** for serialization */
static final long serialVersionUID = 3119607037607101160L;
/** The subsample size, percent of original set, default 100% */
protected double m_SampleSizePercent = 100;
/** The random number generator seed */
protected int m_RandomSeed = 1;
/** Whether to perform sampling with replacement or without */
protected boolean m_NoReplacement = false;
/**
* Whether to invert the selection (only if instances are drawn WITHOUT
* replacement)
*
* @see #m_NoReplacement
*/
protected boolean m_InvertSelection = false;
/**
* Returns a string describing this classifier
*
* @return a description of the classifier suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Produces a random subsample of a dataset using either sampling with "
+ "replacement or without replacement. The original dataset must fit "
+ "entirely in memory. The number of instances in the generated dataset "
+ "may be specified. When used in batch mode, subsequent batches are "
+ "NOT resampled.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tSpecify the random number seed (default 1)", "S", 1, "-S <num>"));
result.addElement(new Option(
"\tThe size of the output dataset, as a percentage of\n"
+ "\tthe input dataset (default 100)", "Z", 1, "-Z <num>"));
result
.addElement(new Option("\tDisables replacement of instances\n"
+ "\t(default: with replacement)", "no-replacement", 0,
"-no-replacement"));
result.addElement(new Option(
"\tInverts the selection - only available with '-no-replacement'.", "V",
0, "-V"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -S <num>
* Specify the random number seed (default 1)
* </pre>
*
* <pre>
* -Z <num>
* The size of the output dataset, as a percentage of
* the input dataset (default 100)
* </pre>
*
* <pre>
* -no-replacement
* Disables replacement of instances
* (default: with replacement)
* </pre>
*
* <pre>
* -V
* Inverts the selection - only available with '-no-replacement'.
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0) {
setRandomSeed(Integer.parseInt(tmpStr));
} else {
setRandomSeed(1);
}
tmpStr = Utils.getOption('Z', options);
if (tmpStr.length() != 0) {
setSampleSizePercent(Double.parseDouble(tmpStr));
} else {
setSampleSizePercent(100);
}
setNoReplacement(Utils.getFlag("no-replacement", options));
if (getNoReplacement()) {
setInvertSelection(Utils.getFlag('V', options));
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-S");
result.add("" + getRandomSeed());
result.add("-Z");
result.add("" + getSampleSizePercent());
if (getNoReplacement()) {
result.add("-no-replacement");
if (getInvertSelection()) {
result.add("-V");
}
}
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String randomSeedTipText() {
return "The seed used for random sampling.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed(int newSeed) {
m_RandomSeed = newSeed;
}
@ProgrammaticProperty
public void setSeed(int seed) {
setRandomSeed(seed);
}
@ProgrammaticProperty
public int getSeed() {
return getRandomSeed();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String sampleSizePercentTipText() {
return "Size of the subsample as a percentage of the original dataset.";
}
/**
* Gets the subsample size as a percentage of the original set.
*
* @return the subsample size
*/
public double getSampleSizePercent() {
return m_SampleSizePercent;
}
/**
* Sets the size of the subsample, as a percentage of the original set.
*
* @param newSampleSizePercent the subsample set size, between 0 and 100.
*/
public void setSampleSizePercent(double newSampleSizePercent) {
m_SampleSizePercent = newSampleSizePercent;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String noReplacementTipText() {
return "Disables the replacement of instances.";
}
/**
* Gets whether instances are drawn with or without replacement.
*
* @return true if the replacement is disabled
*/
public boolean getNoReplacement() {
return m_NoReplacement;
}
/**
* Sets whether instances are drawn with or with out replacement.
*
* @param value if true then the replacement of instances is disabled
*/
public void setNoReplacement(boolean value) {
m_NoReplacement = value;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String invertSelectionTipText() {
return "Inverts the selection (only if instances are drawn WITHOUT replacement).";
}
/**
* Gets whether selection is inverted (only if instances are drawn WIHTOUT
* replacement).
*
* @return true if the replacement is disabled
* @see #m_NoReplacement
*/
public boolean getInvertSelection() {
return m_InvertSelection;
}
/**
* Sets whether the selection is inverted (only if instances are drawn WIHTOUT
* replacement).
*
* @param value if true then selection is inverted
*/
public void setInvertSelection(boolean value) {
m_InvertSelection = value;
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
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
*/
@Override
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
setOutputFormat(instanceInfo);
return true;
}
/**
* Input an instance for filtering. Filter requires all training 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 structure has been defined
*/
@Override
public boolean input(Instance instance) {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (isFirstBatchDone()) {
push(instance);
return true;
} else {
bufferInput(instance);
return false;
}
}
/**
* Signify 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
*/
@Override
public boolean batchFinished() {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (!isFirstBatchDone()) {
// Do the subsample, and clear the input instances.
createSubsample();
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* Creates a subsample of the current set of input instances. The output
* instances are pushed onto the output queue for collection.
*/
protected void createSubsample() {
Instances data = getInputFormat();
int numEligible = data.numInstances();
int sampleSize = (int) (numEligible * m_SampleSizePercent / 100);
Random random = new Random(m_RandomSeed);
if (getNoReplacement()) {
// Set up array of indices
int[] selected = new int[numEligible];
for (int j = 0; j < numEligible; j++) {
selected[j] = j;
}
for (int i = 0; i < sampleSize; i++) {
// Sampling without replacement
int chosenLocation = random.nextInt(numEligible);
int chosen = selected[chosenLocation];
numEligible--;
selected[chosenLocation] = selected[numEligible];
selected[numEligible] = chosen;
}
// Do we need to invert the selection?
if (getInvertSelection()) {
// Take the first numEligible instances
// because they have not been selected
for (int j = 0; j < numEligible; j++) {
push(data.instance(selected[j]), false); // No need to copy instance
}
} else {
// Take the elements that have been selected
for (int j = numEligible; j < data.numInstances(); j++) {
push(data.instance(selected[j]), false); // No need to copy instance
}
}
} else {
// Sampling with replacement
for (int i = 0; i < sampleSize; i++) {
push(data.instance(random.nextInt(numEligible)), false); // No need to copy instance
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String[] argv) {
runFilter(new Resample(), argv);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.