Example usage for weka.core Instance setDataset

List of usage examples for weka.core Instance setDataset

Introduction

In this page you can find the example usage for weka.core Instance setDataset.

Prototype

public void setDataset(Instances instances);

Source Link

Document

Sets the reference to the dataset.

Usage

From source file:mulan.transformations.multiclass.Copy.java

License:Open Source License

/**
 * Transforms a multi-label instance to a list of single-label instances,
 * one for each of the labels that annotate the instance, by copying the
 * feature vector//w  w  w. j ava2 s .co  m
 *
 * @param instance a multi-label instance
 * @return a list with the transformed single-label instances
 */
List<Instance> transformInstance(Instance instance) {
    List<Instance> result = new ArrayList<Instance>();
    for (int counter = 0; counter < numOfLabels; counter++) {
        if (instance.attribute(labelIndices[counter]).value((int) instance.value(labelIndices[counter]))
                .equals("1")) {
            Instance transformed = null;
            try {
                transformed = RemoveAllLabels.transformInstance(instance, labelIndices);
                transformed.setDataset(null);
                transformed.insertAttributeAt(transformed.numAttributes());
                transformed.setValue(transformed.numAttributes() - 1, counter);
            } catch (Exception ex) {
                Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, ex);
            }
            result.add(transformed);
        }
    }
    return result;
}

From source file:mulan.transformations.multiclass.Ignore.java

License:Open Source License

/**
 * Transforms a multi-label example with a single annotation to a
 * single-label example and ignores multi-label example with more
 * annotations/*from   w  w w .  j a  va  2  s .  co m*/
 *
 * @param instance a multi-label example
 * @return a list that is either empty or contains the transformed
 * single-label example
 */
List<Instance> transformInstance(Instance instance) {
    List<Instance> result = new ArrayList<Instance>();
    int indexOfSingleLabel = -1;
    int counter = 0;
    for (int labelCounter = 0; labelCounter < numOfLabels; labelCounter++) {
        int index = labelIndices[labelCounter];
        if (instance.attribute(index).value((int) instance.value(index)).equals("1")) {
            counter++;
            indexOfSingleLabel = labelCounter;
        }
        if (counter > 1) {
            break;
        }
    }
    if (counter > 1 || counter == 0) {
        return result;
    }

    Instance transformedInstance;
    try {
        transformedInstance = RemoveAllLabels.transformInstance(instance, labelIndices);
        transformedInstance.setDataset(null);
        transformedInstance.insertAttributeAt(transformedInstance.numAttributes());
        transformedInstance.setValue(transformedInstance.numAttributes() - 1, indexOfSingleLabel);
        result.add(transformedInstance);
    } catch (Exception ex) {
        Logger.getLogger(Ignore.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:mulan.transformations.multiclass.SelectBasedOnFrequency.java

License:Open Source License

/**
 * Transforms a multi-label example to a list containing a single-label
 * multi-class example by selecting the most/least frequent label in the 
 * training set/*  w w  w  .  jav a2  s.c o  m*/
 *
 * @param instance
 * @return
 */
List<Instance> transformInstance(Instance instance) {
    int value = labelOccurance[0];
    int labelSelected = 0;
    for (int counter = 1; counter < numOfLabels; counter++) {
        if (instance.attribute(labelIndices[counter]).value((int) instance.value(labelIndices[counter]))
                .equals("1")) {
            boolean test = false;
            switch (type) {
            case MIN:
                test = labelOccurance[counter] < value ? true : false;
                break;
            case MAX:
                test = labelOccurance[counter] > value ? true : false;
                break;
            }

            if (test) {
                value = labelOccurance[counter];
                labelSelected = counter;
            }
        }
    }

    Instance transformed = null;
    try {
        transformed = RemoveAllLabels.transformInstance(instance, labelIndices);
        transformed.setDataset(null);
        transformed.insertAttributeAt(transformed.numAttributes());
        transformed.setValue(transformed.numAttributes() - 1, labelSelected);
    } catch (Exception ex) {
        Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Instance> result = new ArrayList<Instance>();
    result.add(transformed);
    return result;
}

From source file:mulan.transformations.multiclass.SelectRandom.java

License:Open Source License

/**
 * Transforms a multi-label example to a list containing a single-label
 * multi-class example by randomly selecting one of the labels
 * //from  ww w  . ja va  2s  .  co m
 * @param instance the multi-label example
 * @return the list with the single-label multi-class example
 */
List<Instance> transformInstance(Instance instance) {
    ArrayList<Integer> labels = new ArrayList<Integer>();
    for (int counter = 0; counter < numOfLabels; counter++) {
        if (instance.attribute(labelIndices[counter]).value((int) instance.value(labelIndices[counter]))
                .equals("1")) {
            labels.add(counter);
        }
    }

    int randomLabel = labels.get((int) (Math.random() * labels.size()));

    Instance transformed = null;
    try {
        transformed = RemoveAllLabels.transformInstance(instance, labelIndices);
        transformed.setDataset(null);
        transformed.insertAttributeAt(transformed.numAttributes());
        transformed.setValue(transformed.numAttributes() - 1, randomLabel);
    } catch (Exception ex) {
        Logger.getLogger(Copy.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Instance> result = new ArrayList<Instance>();
    result.add(transformed);
    return result;
}

From source file:mulan.transformations.PairwiseTransformation.java

License:Open Source License

/**
 * Keeps the predictors and adds one binary attrinute
 *
 * @param instance the instance to be transformed
 * @return transformed Instance/*from  ww  w. j a va  2 s  .  com*/
 */
public Instance transformInstance(Instance instance) {
    Instance transformedInstance;
    remove.input(instance);
    transformedInstance = remove.output();
    add.input(transformedInstance);
    transformedInstance = add.output();
    transformedInstance.setDataset(shell);
    return transformedInstance;
}

From source file:mulan.transformations.PairwiseTransformation.java

License:Open Source License

/**
 * Prepares the training data for two labels. 
 *
 * @param label1 first label/*from  w w w .j ava  2  s .  c om*/
 * @param label2 second label
 * @return transformed Instances object
 */
public Instances transformInstances(int label1, int label2) {
    Instances transformed = new Instances(shell, 0);
    int[] labelIndices = data.getLabelIndices();

    int indexOfTrueLabel1;
    if (data.getDataSet().attribute(labelIndices[label1]).value(0).equals("1")) {
        indexOfTrueLabel1 = 0;
    } else {
        indexOfTrueLabel1 = 1;
    }
    int indexOfTrueLabel2;
    if (data.getDataSet().attribute(labelIndices[label2]).value(0).equals("1")) {
        indexOfTrueLabel2 = 0;
    } else {
        indexOfTrueLabel2 = 1;
    }

    for (int j = 0; j < shell.numInstances(); j++) {
        boolean value1 = ((int) data.getDataSet().instance(j).value(labelIndices[label1]) == indexOfTrueLabel1);
        boolean value2 = ((int) data.getDataSet().instance(j).value(labelIndices[label2]) == indexOfTrueLabel2);
        if (value1 != value2) {
            Instance tempInstance;
            if (shell.instance(j) instanceof SparseInstance) {
                tempInstance = new SparseInstance(shell.instance(j));
            } else {
                tempInstance = new DenseInstance(shell.instance(j));
            }
            tempInstance.setDataset(transformed);
            if (value1 == true) {
                tempInstance.setClassValue(1);
            } else {
                tempInstance.setClassValue(0);
            }
            transformed.add(tempInstance);
        }
    }
    return transformed;
}

From source file:mulan.transformations.PT6Transformation.java

License:Open Source License

public Instances transformInstances(MultiLabelInstances mlData) throws Exception {
    int numLabels = mlData.getNumLabels();
    labelIndices = mlData.getLabelIndices();

    // remove all labels
    Instances transformed = RemoveAllLabels.transformInstances(mlData);

    // add at the end an attribute with values the label names
    ArrayList<String> labelNames = new ArrayList<String>(numLabels);
    for (int counter = 0; counter < numLabels; counter++) {
        labelNames.add(mlData.getDataSet().attribute(labelIndices[counter]).name());
    }//from  w ww  .  ja va 2 s  .c o m
    Attribute attrLabel = new Attribute("Label", labelNames);
    transformed.insertAttributeAt(attrLabel, transformed.numAttributes());

    // and at the end a binary attribute
    ArrayList<String> binaryValues = new ArrayList<String>(2);
    binaryValues.add("0");
    binaryValues.add("1");
    Attribute classAttr = new Attribute("Class", binaryValues);
    transformed.insertAttributeAt(classAttr, transformed.numAttributes());

    // add instances
    transformed = new Instances(transformed, 0);
    transformed.setClassIndex(transformed.numAttributes() - 1);
    Instances data = mlData.getDataSet();
    for (int instanceIndex = 0; instanceIndex < data.numInstances(); instanceIndex++) {
        for (int labelCounter = 0; labelCounter < numLabels; labelCounter++) {
            Instance temp;
            temp = RemoveAllLabels.transformInstance(data.instance(instanceIndex), labelIndices);
            temp.setDataset(null);
            temp.insertAttributeAt(temp.numAttributes());
            temp.insertAttributeAt(temp.numAttributes());
            temp.setDataset(transformed);
            temp.setValue(temp.numAttributes() - 2, (String) labelNames.get(labelCounter));
            if (data.attribute(labelIndices[labelCounter])
                    .value((int) data.instance(instanceIndex).value(labelIndices[labelCounter])).equals("1")) {
                temp.setValue(temp.numAttributes() - 1, "1");
            } else {
                temp.setValue(temp.numAttributes() - 1, "0");
            }
            transformed.add(temp);
        }
    }

    return transformed;
}

From source file:mulan.transformations.PT6Transformation.java

License:Open Source License

public Instance transformInstance(Instance instance) throws Exception {
    if (labelIndices == null) {
        System.out.println("Label Indices not set!!");
        return null;
    }//from ww  w .jav  a  2 s .  c o  m
    Instance transformedInstance = RemoveAllLabels.transformInstance(instance, labelIndices);
    transformedInstance.setDataset(null);
    transformedInstance.insertAttributeAt(transformedInstance.numAttributes());
    transformedInstance.insertAttributeAt(transformedInstance.numAttributes());
    return transformedInstance;
}

From source file:mulan.transformations.regression.SingleTargetTransformation.java

License:Open Source License

/**
 * Remove all target attributes except labelToKeep
 * //from www .ja v  a  2s.  com
 * @param instance the instance to be transformed
 * @param targetToKeep the target to keep
 * @return transformed Instance
 */
public Instance transformInstance(Instance instance, int targetToKeep) {
    Instance transformedInstance;
    remove.input(instance);
    transformedInstance = remove.output();
    add.input(transformedInstance);
    transformedInstance = add.output();
    transformedInstance.setDataset(shell);

    int[] targetIndices = data.getLabelIndices();
    transformedInstance.setValue(shell.numAttributes() - 1, instance.value(targetIndices[targetToKeep]));

    return transformedInstance;
}

From source file:mx.itesm.arch.mvc.MvcAnalyzer.java

License:Open Source License

/**
 * Classify each class in the specified List into one of the layers of the
 * MVC pattern./*from   ww  w.java 2 s  . c  o m*/
 * 
 * @param dependencies
 *            List containing the dependencies for each class to classify.
 * @param internalPackages
 *            Project's internal packages.
 * @return Map containing the classification layer for each class.
 * @throws Exception
 *             If an Exception occurs during classification.
 */
private static Map<String, Layer> classifyClasses(final List<ClassDependencies> dependencies,
        final Map<String, Set<String>> internalPackages) throws Exception {
    int viewCount;
    int modelCount;
    int instanceLayer;
    Instance instance;
    boolean valueFound;
    int controllerCount;
    Instances instances;
    String instanceType;
    String[] typeValues;
    Layer componentLayer;
    String[] suffixValues;
    Layer dependencyLayer;
    FastVector attributes;
    String[] externalApiValues;
    Map<String, Layer> returnValue;
    Set<String> currentPackageContent;
    Map<String, Layer> packagesClassification;
    Map<String, String[]> externalApiPackages;

    // Model variables
    attributes = new FastVector();
    for (Variable variable : Variable.values()) {
        attributes.addElement(variable.getAttribute());
    }

    // Layer variable
    attributes.addElement(Layer.attribute);

    // Set the test instances, the Layer variable is unknown
    instances = new Instances("mvc", attributes, 0);
    instances.setClassIndex(Variable.values().length);

    // Valid suffixes to look for in the class names
    suffixValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Suffix.getVariableName());

    // Valid file types to look for in the component names
    typeValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.Type.getVariableName());

    // Valid external api packages to look for in the classes dependencies
    externalApiValues = MvcAnalyzer.getPropertyValues(MvcAnalyzer.Variable.ExternalAPI.getVariableName());
    externalApiPackages = new HashMap<String, String[]>(externalApiValues.length);
    for (int i = 0; i < externalApiValues.length; i++) {
        if (!externalApiValues[i].equals("none")) {
            externalApiPackages.put(externalApiValues[i],
                    MvcAnalyzer.getPropertyValues("externalApi." + externalApiValues[i] + ".packages"));
        }
    }

    returnValue = new HashMap<String, Layer>(dependencies.size());
    for (ClassDependencies classDependencies : dependencies) {
        // Variables + Layer
        instance = new Instance(Variable.values().length + 1);

        // Type
        instanceType = "java";
        for (String validType : typeValues) {
            if (classDependencies.getClassName().endsWith("." + validType)) {
                instanceType = validType;
                break;
            }
        }
        instance.setValue(Variable.Type.getAttribute(), instanceType);

        // ExternalAPI
        valueFound = false;
        externalApi: for (String externalApi : externalApiValues) {
            if (externalApi.equals("none")) {
                continue;
            }

            // Check if any of the class' external dependencies match with
            // one of the key external dependencies
            if (classDependencies.getExternalDependencies() != null) {
                for (String externalDependency : classDependencies.getExternalDependencies()) {
                    for (String externalPackage : externalApiPackages.get(externalApi)) {
                        if (externalDependency.toLowerCase().startsWith(externalPackage)) {
                            valueFound = true;
                            instance.setValue(Variable.ExternalAPI.getAttribute(), externalApi);
                            break externalApi;
                        }
                    }
                }
            }
        }

        // No key external dependency found
        if (!valueFound) {
            instance.setValue(Variable.ExternalAPI.getAttribute(), "none");
        }

        // Suffix
        valueFound = false;
        for (String suffix : suffixValues) {
            if (classDependencies.getClassName().toLowerCase().endsWith(suffix)) {
                valueFound = true;
                instance.setValue(Variable.Suffix.getAttribute(), suffix);
                break;
            }
        }

        // No key suffix found
        if (!valueFound) {
            instance.setValue(Variable.Suffix.getAttribute(), "none");
        }

        // Layer, the unknown variable
        instance.setMissing(Layer.attribute);
        instances.add(instance);
        instance.setDataset(instances);

        try {
            instanceLayer = (int) MvcAnalyzer.classifier.classifyInstance(instance);
        } catch (Exception e) {
            // Default value
            instanceLayer = 0;
            logger.severe("Unable to classify: " + instance);
        }

        returnValue.put(classDependencies.getClassName(), Layer.values()[instanceLayer]);
        logger.info(
                classDependencies.getClassName() + " : " + returnValue.get(classDependencies.getClassName()));
    }

    // Check for any invalid relation
    packagesClassification = new HashMap<String, Layer>(internalPackages.size());
    for (String currentPackage : internalPackages.keySet()) {
        modelCount = viewCount = controllerCount = 0;
        currentPackageContent = internalPackages.get(currentPackage);

        for (String component : currentPackageContent) {
            componentLayer = returnValue.get(component);
            if (componentLayer == Layer.Model) {
                modelCount++;
            } else if (componentLayer == Layer.View) {
                viewCount++;
            } else if (componentLayer == Layer.Controller) {
                controllerCount++;
            }
        }

        if ((modelCount > viewCount) && (modelCount > controllerCount)) {
            packagesClassification.put(currentPackage, Layer.Model);
        } else if ((viewCount > modelCount) && (viewCount > controllerCount)) {
            packagesClassification.put(currentPackage, Layer.View);
        } else if ((controllerCount > viewCount) && (controllerCount > modelCount)) {
            packagesClassification.put(currentPackage, Layer.Controller);
        } else {
            packagesClassification.put(currentPackage, null);
        }
    }

    for (ClassDependencies classDependencies : dependencies) {
        // Code relations
        valueFound = false;
        componentLayer = returnValue.get(classDependencies.getClassName());
        if (classDependencies.getInternalDependencies() != null) {
            for (String internalDependency : classDependencies.getInternalDependencies()) {
                dependencyLayer = returnValue.get(internalDependency);

                if (!componentLayer.isValidRelation(dependencyLayer)) {
                    valueFound = true;
                    returnValue.put(classDependencies.getClassName(),
                            Layer.valueOf("Invalid" + componentLayer));
                    logger.info("Invalid relation detected between: " + classDependencies.getClassName()
                            + " and " + internalDependency);
                }
            }
        }

        // Package relations
        if (!valueFound) {
            dependencyLayer = packagesClassification.get(classDependencies.getPackageName());

            if ((dependencyLayer != null) && (componentLayer != dependencyLayer)) {
                returnValue.put(classDependencies.getClassName(), Layer.valueOf("Invalid" + componentLayer));
            }
        }
    }

    return returnValue;
}