Example usage for weka.core Instance insertAttributeAt

List of usage examples for weka.core Instance insertAttributeAt

Introduction

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

Prototype

public void insertAttributeAt(int position);

Source Link

Document

Inserts an attribute at the given position (0 to numAttributes()).

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/*ww w .  ja  v  a  2s  . c  o 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  av  a 2  s. c  o  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/*from   w w  w .  j  av  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 w w w  . j a  v a 2 s .  c o  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.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());
    }//  w  ww.ja v  a  2s.  co 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;
    }//  ww  w . j  av  a2 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:org.knime.knip.suise.ops.BuildTrainingData.java

License:Open Source License

/**
 * {@inheritDoc}//w  w w  . ja v  a  2 s.  com
 */
@Override
public Instances compute(RandomAccessibleInterval<LabelingType<L>> lab, Img<T> img, Instances r) {
    Random rand = new Random();

    double[] extent = new double[lab.numDimensions()];
    for (int d = 0; d < m_dimIndices.length; d++) {
        extent[m_dimIndices[d]] = lab.max(m_dimIndices[d]);
    }
    RectangleRegionOfInterest roi = new RectangleRegionOfInterest(new double[lab.numDimensions()], extent);

    Cursor<LabelingType<L>> labCur = roi.getIterableIntervalOverROI(lab).localizingCursor();
    OutOfBounds<T> imgRA = new OutOfBoundsBorder<T>(img);

    LabelRegions<L> regions = new LabelRegions<L>(lab);
    // get the class distributions
    Map<L, Double> classDistr = null;
    if (m_balanceInstancePerClass) {
        long sum = 0;
        long area;
        Collection<L> labels = regions.getExistingLabels();
        classDistr = new HashMap<L, Double>(labels.size());
        for (L label : labels) {
            area = regions.getLabelRegion(label).size();
            sum += area;
            classDistr.put(label, new Double(area));
        }
        // determine the new sampling rate for each class individually
        double instancesPerClass = (double) sum / (double) labels.size();
        for (L label : labels) {
            Double sampleRate = instancesPerClass / classDistr.get(label) * m_samplingRate;
            classDistr.put(label, sampleRate);
        }
    }

    long[] tmpPos = new long[imgRA.numDimensions()];
    while (labCur.hasNext()) {
        labCur.fwd();
        for (int d = 0; d < m_dimIndices.length; d++) {
            imgRA.setPosition(labCur.getLongPosition(m_dimIndices[d]), m_dimIndices[d]);
            if (imgRA.isOutOfBounds()) {
                imgRA.localize(tmpPos);
                NodeLogger.getLogger(getClass()).warn("Labeling reaches beyond the feature image. Position "
                        + Arrays.toString(tmpPos) + " skipped.");
                continue;
            }

        }
        if (!labCur.get().isEmpty()) {

            if (m_balanceInstancePerClass) {
                if (rand.nextDouble() >= classDistr.get(labCur.get().iterator().next())) {
                    continue;
                }
            } else {
                if (rand.nextDouble() >= m_samplingRate) {
                    continue;
                }
            }

            double[] featVec = new double[(int) img.dimension(m_featDim)];
            for (int f = 0; f < img.dimension(m_featDim); f++) {
                imgRA.setPosition(f, m_featDim);
                featVec[f] = imgRA.get().getRealDouble();
            }
            for (L classLabel : labCur.get()) {
                Instance instance = new DenseInstance(1.0, featVec);
                instance.insertAttributeAt(instance.numAttributes());
                instance.setDataset(r);
                instance.setClassValue(classLabel.toString());

                r.add(instance);

            }
        }
    }
    return r;
}