Example usage for weka.core Instance numValues

List of usage examples for weka.core Instance numValues

Introduction

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

Prototype

public int numValues();

Source Link

Document

Returns the number of values present in a sparse representation.

Usage

From source file:moa.clusterers.denstream.MicroCluster.java

License:Apache License

public void insert(Instance instance, long timestamp) {
    N++;/*from  www  .j  a v a  2 s .c o  m*/
    super.setWeight(super.getWeight() + 1);
    this.lastEditT = timestamp;

    for (int i = 0; i < instance.numValues(); i++) {
        LS[i] += instance.value(i);
        SS[i] += instance.value(i) * instance.value(i);
    }
}

From source file:moa.clusterers.outliers.MyBaseOutlierDetector.java

License:Apache License

public double[] getInstanceValues(Instance inst) {
    double[] values = new double[inst.numValues() - 1]; // last attribute is the class
    for (int i = 0; i < inst.numValues() - 1; i++) {
        values[i] = inst.value(i);/*  w w  w  .j  a v  a2  s.  co  m*/
    }
    return values;
}

From source file:moa.clusterers.outliers.MyBaseOutlierDetector.java

License:Apache License

public void PrintInstance(Instance inst) {
    Print("instance: [ ");
    for (int i = 0; i < inst.numValues() - 1; i++) { // last value is the class
        Printf("%.2f ", inst.value(i));
    }/*w w w.ja  v  a2s.  co  m*/
    Print("] ");
    Println("");
}

From source file:mulan.classifier.meta.ConstrainedKMeans.java

License:Open Source License

/**
 * Calculates the distance between two instances
 *
 * @param first the first instance//from w  w  w .  j a va 2 s  .  com
 * @param second the second instance
 * @return the distance between the two given instances, between 0 and 1
 */
private double distance(Instance first, Instance second) {
    double distance = 0;
    int firstI, secondI;
    for (int p1 = 0, p2 = 0; p1 < first.numValues() || p2 < second.numValues();) {
        if (p1 >= first.numValues()) {
            firstI = m_ClusterCentroids.numAttributes();
        } else {
            firstI = first.index(p1);
        }
        if (p2 >= second.numValues()) {
            secondI = m_ClusterCentroids.numAttributes();
        } else {
            secondI = second.index(p2);
        }
        /*      if (firstI == m_ClusterCentroids.classIndex()) {
        p1++; continue;
        }
        if (secondI == m_ClusterCentroids.classIndex()) {
        p2++; continue;
        } */
        double diff;
        if (firstI == secondI) {
            diff = difference(firstI, first.valueSparse(p1), second.valueSparse(p2));
            p1++;
            p2++;
        } else if (firstI > secondI) {
            diff = difference(secondI, 0, second.valueSparse(p2));
            p2++;
        } else {
            diff = difference(firstI, first.valueSparse(p1), 0);
            p1++;
        }
        distance += diff * diff;
    }
    //return Math.sqrt(distance / m_ClusterCentroids.numAttributes());
    return distance;
}

From source file:net.paudan.evosvm.LibLINEAR.java

License:Open Source License

/**
* returns an instance into a sparse liblinear array
*
* @param instance the instance to work on
* @return the liblinear array/*from  w w w .ja  v  a 2 s  .  c o  m*/
* @throws Exception if setup of array fails
*/
protected FeatureNode[] instanceToArray(Instance instance) throws Exception {
    // determine number of non-zero attributes
    int count = 0;

    for (int i = 0; i < instance.numValues(); i++) {
        if (instance.index(i) == instance.classIndex())
            continue;
        if (instance.valueSparse(i) != 0)
            count++;
    }

    if (m_Bias >= 0) {
        count++;
    }

    // fill array
    FeatureNode[] nodes = new FeatureNode[count];
    int index = 0;
    for (int i = 0; i < instance.numValues(); i++) {

        int idx = instance.index(i);
        double val = instance.valueSparse(i);

        if (idx == instance.classIndex())
            continue;
        if (val == 0)
            continue;

        nodes[index] = new FeatureNode(idx + 1, val);
        index++;
    }

    // add bias term
    if (m_Bias >= 0) {
        nodes[index] = new FeatureNode(instance.numAttributes() + 1, m_Bias);
    }

    return nodes;
}

From source file:net.sf.jclal.util.distancefunction.CosineDistance.java

License:Open Source License

/**
 * Calculates the distance between two instances. Offers speed up (if the
 * distance function class in use supports it) in nearest neighbour search
 * by taking into account the cutOff or maximum distance. Depending on the
 * distance function class, post processing of the distances by
 * postProcessDistances(double []) may be required if this function is used.
 *
 * @param first the first instance/*from   w  w  w.  j a v a  2 s.  co  m*/
 * @param second the second instance
 * @param cutOffValue If the distance being calculated becomes larger than
 * cutOffValue then the rest of the calculation is discarded.
 * @param stats the performance stats object
 * @return the distance between the two given instances or
 * Double.POSITIVE_INFINITY if the distance being calculated becomes larger
 * than cutOffValue.
 */
@Override
public double distance(Instance first, Instance second, double cutOffValue, PerformanceStats stats) {
    double distance = 0;
    int firstI, secondI;
    int firstNumValues = first.numValues();
    int secondNumValues = second.numValues();
    int numAttributes = m_Data.numAttributes();
    int classIndex = m_Data.classIndex();

    double norm2First = 0, norm2Second = 0;

    validate();

    for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
        if (p1 >= firstNumValues) {
            firstI = numAttributes;
        } else {
            firstI = first.index(p1);
        }

        if (p2 >= secondNumValues) {
            secondI = numAttributes;
        } else {
            secondI = second.index(p2);
        }

        if (firstI == classIndex) {
            p1++;
            continue;
        }
        if ((firstI < numAttributes) && !m_ActiveIndices[firstI]) {
            p1++;
            continue;
        }

        if (secondI == classIndex) {
            p2++;
            continue;
        }
        if ((secondI < numAttributes) && !m_ActiveIndices[secondI]) {
            p2++;
            continue;
        }

        double diff;

        if (firstI == secondI) {
            diff = localSimilarity(firstI, first.valueSparse(p1), second.valueSparse(p2));

            norm2First += localSimilarity(firstI, first.valueSparse(p1), first.valueSparse(p1));
            norm2Second += localSimilarity(secondI, second.valueSparse(p2), second.valueSparse(p2));

            p1++;
            p2++;
        } else if (firstI > secondI) {

            diff = localSimilarity(secondI, 0, second.valueSparse(p2));

            norm2Second += localSimilarity(secondI, second.valueSparse(p2), second.valueSparse(p2));

            p2++;
        } else {

            diff = localSimilarity(firstI, first.valueSparse(p1), 0);

            norm2First += localSimilarity(firstI, first.valueSparse(p1), first.valueSparse(p1));

            p1++;
        }
        if (stats != null) {
            stats.incrCoordCount();
        }

        distance = updateDistance(distance, diff);
        if (distance > cutOffValue) {
            return Double.POSITIVE_INFINITY;
        }
    }

    return distance / (Math.sqrt(norm2First * norm2Second));
}

From source file:org.esa.nest.gpf.SGD.java

/**
 * Updates the classifier with the given instance.
 *
 * @param instance the new training instance to include in the model
 * @exception Exception if the instance could not be incorporated in the
 * model.// ww w . ja  v a  2 s.  c  o m
 */
@Override
public void updateClassifier(Instance instance) throws Exception {

    if (!instance.classIsMissing()) {

        double wx = dotProd(instance, m_weights, instance.classIndex());

        double y;
        double z;
        if (instance.classAttribute().isNominal()) {
            y = (instance.classValue() == 0) ? -1 : 1;
            z = y * (wx + m_weights[m_weights.length - 1]);
        } else {
            y = instance.classValue();
            z = y - (wx + m_weights[m_weights.length - 1]);
            y = 1;
        }

        // Compute multiplier for weight decay
        double multiplier = 1.0;
        if (m_numInstances == 0) {
            multiplier = 1.0 - (m_learningRate * m_lambda) / m_t;
        } else {
            multiplier = 1.0 - (m_learningRate * m_lambda) / m_numInstances;
        }
        for (int i = 0; i < m_weights.length - 1; i++) {
            m_weights[i] *= multiplier;
        }

        // Only need to do the following if the loss is non-zero
        if (m_loss != HINGE || (z < 1)) {

            // Compute Factor for updates
            double factor = m_learningRate * y * dloss(z);

            // Update coefficients for attributes
            int n1 = instance.numValues();
            for (int p1 = 0; p1 < n1; p1++) {
                int indS = instance.index(p1);
                if (indS != instance.classIndex() && !instance.isMissingSparse(p1)) {
                    m_weights[indS] += factor * instance.valueSparse(p1);
                }
            }

            // update the bias
            m_weights[m_weights.length - 1] += factor;
        }
        m_t++;
    }
}

From source file:org.mcennis.graphrat.property.database.InstanceDB.java

License:Open Source License

public int put(Instance object) {
    int ret = -1;
    ResultSet rs = null;/*from   w  w  w .  jav  a 2  s .c o m*/
    try {
        put.clearParameters();
        getID.clearParameters();
        put.setDouble(1, object.weight());
        getID.setDouble(1, object.weight());
        put.executeUpdate();
        rs = getID.executeQuery();
        if (rs.next()) {
            ret = rs.getInt("id");
            for (int i = 0; i < object.numValues(); ++i) {
                putValue.clearParameters();
                putValue.setInt(1, ret);
                putValue.setInt(2, i);
                putValue.setDouble(3, object.value(i));
                putValue.executeUpdate();
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(URLDB.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
            }
            rs = null;
        }
    }
    return ret;
}

From source file:org.sr.recognition.paleo.paleoNN.PaleoTrainer.java

License:BSD License

/**
 * Converts ARFF instances into a format readable by LibSVM and outputs it
 * to file//from  ww  w . ja v  a2  s .  c o m
 * 
 * @param filename
 *            output file name
 * @param data
 *            ARFF instances (the data)
 * @throws IOException
 *             if output fails
 */
public static void libSVMToFile(String filename, Instances data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
    for (int i = 0; i < data.numInstances(); i++) {
        Instance inst = data.instance(i);
        double label = inst.value(inst.numValues() - 1);
        writer.write(label + "\t");
        for (int a = 0; a < inst.numValues() - 1; a++) {
            double value = inst.value(a);
            if (Double.isInfinite(value) || Double.isNaN(value))
                value = mean(data.attributeToDoubleArray(a));
            writer.write((a + 1) + ":" + value);
            if (a < inst.numValues() - 2)
                writer.write(" ");
        }
        writer.newLine();
    }
}

From source file:org.stream_gpu.float_knn.float_search.NormalizableDistance.java

License:Open Source License

/**
 * Calculates the distance between two instances. Offers speed up (if the 
 * distance function class in use supports it) in nearest neighbour search by 
 * taking into account the cutOff or maximum distance. Depending on the 
 * distance function class, post processing of the distances by 
 * postProcessDistances(float []) may be required if this function is used.
 *
 * @param first    the first instance/*ww  w  .j  a v  a  2 s  . com*/
 * @param second    the second instance
 * @param cutOffValue If the distance being calculated becomes larger than 
 *                    cutOffValue then the rest of the calculation is 
 *                    discarded.
 * @param stats    the performance stats object
 * @return       the distance between the two given instances or 
 *          float.POSITIVE_INFINITY if the distance being 
 *          calculated becomes larger than cutOffValue. 
 */
public float distance(Instance first, Instance second, float cutOffValue, PerformanceStats stats) {
    float distance = 0;
    int firstI, secondI;
    int firstNumValues = first.numValues();
    int secondNumValues = second.numValues();
    int numAttributes = m_Data.numAttributes();
    int classIndex = m_Data.classIndex();

    validate();

    for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
        if (p1 >= firstNumValues)
            firstI = numAttributes;
        else
            firstI = first.index(p1);

        if (p2 >= secondNumValues)
            secondI = numAttributes;
        else
            secondI = second.index(p2);

        if (firstI == classIndex) {
            p1++;
            continue;
        }
        if ((firstI < numAttributes) && !m_ActiveIndices[firstI]) {
            p1++;
            continue;
        }

        if (secondI == classIndex) {
            p2++;
            continue;
        }
        if ((secondI < numAttributes) && !m_ActiveIndices[secondI]) {
            p2++;
            continue;
        }

        float diff;

        if (firstI == secondI) {
            diff = difference(firstI, (float) first.valueSparse(p1), (float) second.valueSparse(p2));
            p1++;
            p2++;
        } else if (firstI > secondI) {
            diff = difference(secondI, 0, (float) second.valueSparse(p2));
            p2++;
        } else {
            diff = difference(firstI, (float) first.valueSparse(p1), 0);
            p1++;
        }
        if (stats != null)
            stats.incrCoordCount();

        distance = updateDistance(distance, diff);
        if (distance > cutOffValue)
            return Float.POSITIVE_INFINITY;
    }

    return distance;
}