Example usage for weka.core Instance toDoubleArray

List of usage examples for weka.core Instance toDoubleArray

Introduction

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

Prototype

public double[] toDoubleArray();

Source Link

Document

Returns the values of each attribute as an array of doubles.

Usage

From source file:edu.oregonstate.eecs.mcplan.ml.Memorizer.java

License:Open Source License

/**
 * 'instance' must be labeled with the class label in the same position
 * as in the training instances./*  w  w w .j  a va2 s .c o m*/
 * 
 * @see weka.classifiers.Classifier#classifyInstance(weka.core.Instance)
 */
@Override
public double classifyInstance(final Instance instance) throws Exception {
    assert (instance.classIndex() == class_idx_);
    final double[] x = instance.toDoubleArray();
    x[class_idx_] = 0;
    return m_.get(new ArrayHolder(x));
}

From source file:edu.umbc.cs.maple.utils.WekaUtils.java

License:Open Source License

/**
 * Converts an instance to a feature vector excluding the class attribute.
 * @param instance The instance./*from www .  j a  v a  2s. com*/
 * @return A vector representation of the instance excluding the class attribute
 */
public static double[] instanceToDoubleArray(Instance instance) {
    double[] vector = new double[(instance.classIndex() != -1) ? instance.numAttributes() - 1
            : instance.numAttributes()];
    double[] instanceDoubleArray = instance.toDoubleArray();
    int attIdx = 0;
    for (int i = 0; i < vector.length; i++) {
        if (i == instance.classIndex()) {
            attIdx++;
        }
        vector[i] = instanceDoubleArray[attIdx++];
    }
    return vector;
}

From source file:eksploracja.Eksploracja.java

/**
 * @param args the command line arguments
 *//*from w  ww .j a  va2 s. c om*/
public static void main(String[] args) throws Exception {
    // TODO code application logic here
    //sout +tabualcja

    System.out.println("Hello world - tu eksploracja");

    //Pobieranie danych
    String filename = "C:\\Program Files\\Weka-3-8\\data\\weather.numeric.arff";
    DataSource source = new DataSource(filename);
    Instances mojeDane = source.getDataSet();

    //Wywietlanie danych
    System.out.println("Dane: ");
    // System.out.println(mojeDane); //cao danych

    Instance wiersz0 = mojeDane.firstInstance();

    System.out.println("Pocztek " + mojeDane.firstInstance()); //pierwszy wiersz
    System.out.println("Koniec " + mojeDane.lastInstance()); //ostatni wiersz

    System.out.println("\nLiczba danych: " + mojeDane.numInstances());
    System.out.println("\nAtrybuty w liczbie: " + mojeDane.numAttributes());

    for (int i = 0; i < mojeDane.numAttributes(); i++) {
        System.out.println(i + ". " + mojeDane.attribute(i));
        Attribute atr = mojeDane.attribute(i);
        System.out.println(i + " " + atr.name());

        if (atr.isNominal()) {
            System.out.println("Typ danych nominalne");
        } else {
            System.out.println("Typ danych numeryczne");
        }
    }

    //Zapisywanie danych w posataci liczbowej
    System.out.println("Dane - jako liczby: ");
    System.out.println(Arrays.toString(wiersz0.toDoubleArray()));

}

From source file:en_deep.mlprocess.manipulation.featmodif.ReplaceMissing.java

License:Open Source License

/**
 * 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
 *//*from  w  w w  .  ja va2s.  c  om*/
private void convertInstance(Instance instance) {

    // create a copy of the input instance
    Instance inst = null;

    if (instance instanceof SparseInstance) {
        inst = new SparseInstance(instance.weight(), instance.toDoubleArray());
    } else {
        inst = new DenseInstance(instance.weight(), instance.toDoubleArray());
    }

    // copy the string values from this instance as well (only the existing ones)
    inst.setDataset(getOutputFormat());
    copyValues(inst, false, instance.dataset(), getOutputFormat()); // beware of weird behavior of this function (see source)!!
    inst.setDataset(getOutputFormat());

    // find the missing values to be filled + the double values for the new "missing" label and store it
    double[] vals = instance.toDoubleArray();

    for (int j = 0; j < getInputFormat().numAttributes(); j++) {

        Attribute att = instance.attribute(j);

        if (m_Columns.isInRange(j) && instance.isMissing(j)) {
            // find the "missing" value in the output nominal attribute
            if (att.isNominal()) {
                vals[j] = inst.dataset().attribute(j).indexOfValue(m_ReplVal);
            }
            // add a string value for the new "missing" label
            else if (att.isString()) {
                vals[j] = inst.dataset().attribute(j).addStringValue(m_ReplVal);
            }
        }
    }

    // fill in the missing values found
    inst.replaceMissingValues(vals);

    push(inst);
}

From source file:lascer.WekaClassifier.java

License:Open Source License

/**
 * Generates the classifier.//from  w  w w .ja v a  2 s .  c om
 *
 * @param data  the data to be used.
 *
 * @exception Exception  if the classifier can't built successfully.
 */
public void buildClassifier(Instances data) throws Exception {
    weka.coreExtended.Instances extendedInstances;
    weka.coreExtended.BasicInstance extInst;
    weka.coreExtended.BasicAttribute classAttribut;
    de.unistuttgart.commandline.Option formelnArtOption;
    de.unistuttgart.commandline.Option formelnKlasseOption;
    de.unistuttgart.commandline.Option loggingSwitch;
    Instance readInst;
    Beispieldaten invDatensatz;
    StringReader stringReader;
    Enumeration instEnum;
    Enumeration attribEnum;
    PraedErzParameter praedErzParameter = null;
    KonzErzParameter konzErzParameter = null;
    Pruning pruning;
    String formelArt;
    String formelKlasse;
    String optionWert;
    float posPruneAnt, negPruneAnt;
    int instNumber;
    boolean unbekannteWertBsp;

    Steuerung.parseArguments(parser);

    formelArt = Konstanten.WEKA_FORMEL_ART;
    formelnArtOption = parser.getOption("formelArt");
    if (parser.isEnabled(formelnArtOption)) {
        optionWert = parser.getParameter(formelnArtOption);
        if (!optionWert.equals("dis") && !optionWert.equals("kon") && !optionWert.equals("beste")) {

            System.err.println("Wert der Option formelArt unzulssig");
            System.err.println("Zulssig: " + formelnArtOption.toString());
            throw (new RuntimeException("Wert von Option unzulssig."));
        }
        formelArt = optionWert;
    }

    formelKlasse = Konstanten.WEKA_FORMEL_KLASSE;
    formelnKlasseOption = parser.getOption("formelKlasse");
    if (parser.isEnabled(formelnKlasseOption)) {
        optionWert = parser.getParameter(formelnKlasseOption);
        if (!optionWert.equals("pos") && !optionWert.equals("neg") && !optionWert.equals("beste")
                && !optionWert.equals("beide")) {

            System.err.println("Wert der Option formelKlasse unzulssig");
            System.err.println("Zulssig: " + formelnKlasseOption.toString());
            throw (new RuntimeException("Wert von Option unzulssig."));
        }
        formelKlasse = optionWert;
    }

    loggingSwitch = parser.getOption("logging");
    if (debugMode || parser.isEnabled(loggingSwitch)) {
        Steuerung.setLogLevel(Konstanten.LOGGING_LEVEL);
    }

    // Ermittlung der Parameter.
    unbekannteWertBsp = Steuerung.unbekannteWertBeispiele(parser);
    posPruneAnt = Steuerung.posPruneAnteil(parser);
    negPruneAnt = Steuerung.negPruneAnteil(parser);
    praedErzParameter = Steuerung.praedErzParameter(parser);
    konzErzParameter = Steuerung.konzErzParameter(parser);

    // Einlesen der Daten und Erzeugung des Instanzen-Objekts.
    instNumber = data.numInstances();
    stringReader = new StringReader(data.toString());
    extendedInstances = new weka.coreExtended.Instances(stringReader, instNumber);
    instEnum = data.enumerateInstances();
    while (instEnum.hasMoreElements()) {
        readInst = (Instance) instEnum.nextElement();
        extInst = new weka.coreExtended.BasicInstance(readInst.weight(), readInst.toDoubleArray());
        extendedInstances.addBasicInstance(extInst);
    }

    // Erzeugung der Datenstze.
    posDatensatz = ArffDateiEinlesen.beispieldaten(extendedInstances, unbekannteWertBsp);
    negDatensatz = posDatensatz.kopie(true);

    // Erzeugung der Liste der Attribute.
    attributListe = new LinkedList();
    attribEnum = extendedInstances.enumerateBasicAttributes();
    while (attribEnum.hasMoreElements()) {
        attributListe.add(attribEnum.nextElement());
    }

    // Ermittlung der Werte der Klassifikation.
    classAttribut = extendedInstances.basicClassAttribute();
    wekaClassTrue = classAttribut.indexOfValue("true");
    wekaClassFalse = classAttribut.indexOfValue("false");

    // Die Formel zur Klasse der positiven Beispiele erzeugen.
    if (formelKlasse.equals("pos") || formelKlasse.equals("beste") || formelKlasse.equals("beide")) {

        posFormel = generatedFormula(posDatensatz, praedErzParameter, konzErzParameter, formelArt);
    }

    // Die Formel zur Klasse der negativen Beispiele erzeugen.
    if (formelKlasse.equals("neg") || formelKlasse.equals("beste") || formelKlasse.equals("beide")) {

        negFormel = generatedFormula(negDatensatz, praedErzParameter, konzErzParameter, formelArt);
    }

    if (formelKlasse.equals("beste")) {
        // Die schlechtere Formel lschen.
        if (negFormel.istBesser(posFormel)) {
            posFormel = null;
        } else {
            negFormel = null;
        }
    }

    if ((posPruneAnt > 0) || (negPruneAnt > 0)) {
        pruning = new Pruning();

        if (posFormel != null) {
            posDatensatz = pruning.reduzierteDaten(posDatensatz, posFormel, posPruneAnt, negPruneAnt);
            posFormel = generatedFormula(posDatensatz, praedErzParameter, konzErzParameter, formelArt);
        }

        if (negFormel != null) {
            negDatensatz = pruning.reduzierteDaten(negDatensatz, negFormel, negPruneAnt, posPruneAnt);
            negFormel = generatedFormula(negDatensatz, praedErzParameter, konzErzParameter, formelArt);
        }
    }
}

From source file:lascer.WekaClassifier.java

License:Open Source License

/**
 * Classifies a given instance./*from w w w.  ja v a2 s .  c om*/
 *
 * @param inst  the instance to be classified.
 *
 * @return  the classification of the instance.
 */
public double classifyInstance(Instance inst) {
    weka.coreExtended.Instance extendedInstance;
    de.unistuttgart.commandline.Option lokalGrenzwertOption;
    AttributSammlung attributSammlung;
    PraedErzParameter praedErzParameter = null;
    KonzErzParameter konzErzParameter = null;
    Konzept posFormelTrue, posFormelFalse;
    Konzept negFormelTrue, negFormelFalse;
    Konzept posKonzeptTrue, posKonzeptFalse;
    Konzept negKonzeptTrue, negKonzeptFalse;
    Beispiel testbeispiel;
    float fehlAnzPosTrue, fehlAnzPosFalse, fehlAnzPosDiff;
    float fehlAnzNegTrue, fehlAnzNegFalse, fehlAnzNegDiff;
    float komplexPosTrue, komplexPosFalse, komplexPosDiff;
    float komplexNegTrue, komplexNegFalse, komplexNegDiff;
    float bewertPosTrue, bewertPosFalse, bewertPosDiff;
    float bewertNegTrue, bewertNegFalse, bewertNegDiff;
    float lokalGrenzwert;

    extendedInstance = new weka.coreExtended.BasicInstance(inst.weight(), inst.toDoubleArray());
    attributSammlung = posDatensatz.attributSammlung();
    testbeispiel = ArffDateiEinlesen.instanzBeispiel(extendedInstance, attributListe, attributSammlung);

    lokalGrenzwert = Konstanten.LOKAL_GRENZWERT;
    lokalGrenzwertOption = parser.getOption("lokalGrenzwert");
    if (parser.isEnabled(lokalGrenzwertOption)) {
        lokalGrenzwert = parser.getParameterAsFloat(lokalGrenzwertOption);
    }

    if ((posFormel != null) && (negFormel != null) || (lokalGrenzwert > 0)) {
        // Ermittlung der Parameter.
        praedErzParameter = Steuerung.praedErzParameter(parser);
        konzErzParameter = Steuerung.konzErzParameter(parser);
    }

    if ((posFormel == null) && (negFormel == null)) {

        throw (new RuntimeException("Keine Formel vorhanden."));

    } else if (negFormel == null) {
        // Es ist nur eine Formel fr die positiven Beispiele vorhanden.

        if (lokalGrenzwert == 0) {
            // Die Klassifikation erfolgt nur mittels der vorhandenen
            // Formel.
            if (posFormel.trifftZu(testbeispiel)) {
                return wekaClassTrue;
            } else {
                return wekaClassFalse;
            }
        } else {
            // Die Klassifikation erfolgt nach Erzeugung von Formeln und
            // gegebenenfalls Konzepten nach Hinzunahme des Testbeispiels
            // zum Datensatz.
            return relativeCassification(posDatensatz, praedErzParameter, konzErzParameter, posFormel,
                    testbeispiel, lokalGrenzwert, wekaClassTrue, wekaClassFalse);
        }

    } else if (posFormel == null) {
        // Es ist nur eine Formel fr die negativen Beispiele vorhanden.

        if (lokalGrenzwert == 0) {
            // Die Klassifikation erfolgt nur mittels der vorhandenen
            // Formel.
            if (negFormel.trifftZu(testbeispiel)) {
                return wekaClassFalse;
            } else {
                return wekaClassTrue;
            }
        } else {
            // Die Klassifikation erfolgt nach Erzeugung von Formeln und
            // gegebenenfalls Konzepten nach Hinzunahme des Testbeispiels
            // zum Datensatz.
            return relativeCassification(negDatensatz, praedErzParameter, konzErzParameter, negFormel,
                    testbeispiel, lokalGrenzwert, wekaClassFalse, wekaClassTrue);
        }

    } else {
        // Es ist sowohl eine Formel fr die positiven wie fr negativen
        // Beispiele vorhanden. Es findet daher eine Klassifikation
        // entsprechend der relativen Vernderung der Komplexitt der
        // Formeln bei Bercksichtigung des zu klassifizierenden Beispiels
        // statt.

        // Eine Formel fr die positiven Beispiele inklusive des
        // Testbeispiels erzeugen.
        if (posFormel.trifftZu(testbeispiel)) {
            posFormelTrue = posFormel;
            posFormelFalse = generatedAddFormula(posDatensatz, praedErzParameter, konzErzParameter, posFormel,
                    testbeispiel, false);
        } else {
            posFormelFalse = posFormel;
            posFormelTrue = generatedAddFormula(posDatensatz, praedErzParameter, konzErzParameter, posFormel,
                    testbeispiel, true);
        }

        // Eine Formel fr die negativen Beispiele inklusive des
        // Testbeispiels erzeugen.
        if (negFormel.trifftZu(testbeispiel)) {
            negFormelTrue = negFormel;
            negFormelFalse = generatedAddFormula(negDatensatz, praedErzParameter, konzErzParameter, negFormel,
                    testbeispiel, false);
        } else {
            negFormelFalse = negFormel;
            negFormelTrue = generatedAddFormula(negDatensatz, praedErzParameter, konzErzParameter, negFormel,
                    testbeispiel, true);
        }

        // Die Fehleranzahl der Formeln ermitteln.
        fehlAnzPosTrue = (posFormelTrue.posFalschAnz() + posFormelTrue.negFalschAnz());
        fehlAnzPosFalse = (posFormelFalse.posFalschAnz() + posFormelFalse.negFalschAnz());
        fehlAnzNegTrue = (negFormelTrue.posFalschAnz() + negFormelTrue.negFalschAnz());
        fehlAnzNegFalse = (negFormelFalse.posFalschAnz() + negFormelFalse.negFalschAnz());
        fehlAnzPosDiff = fehlAnzPosTrue - fehlAnzPosFalse;
        fehlAnzNegDiff = fehlAnzNegTrue - fehlAnzNegFalse;

        // Die Komplexitt der Formeln ermitteln.
        komplexPosTrue = posFormelTrue.komplexitaet();
        komplexPosFalse = posFormelFalse.komplexitaet();
        komplexNegTrue = negFormelTrue.komplexitaet();
        komplexNegFalse = negFormelFalse.komplexitaet();
        komplexPosDiff = komplexPosTrue - komplexPosFalse;
        komplexNegDiff = komplexNegTrue - komplexNegFalse;

        // Vergleich der Vernderungen der Formeln.
        if ((fehlAnzPosDiff < 0) && (fehlAnzNegDiff > 0)) {

            return wekaClassTrue;

        } else if ((fehlAnzPosDiff > 0) && (fehlAnzNegDiff < 0)) {

            return wekaClassFalse;

        } else if (Math.abs(fehlAnzPosDiff) > Math.abs(fehlAnzNegDiff)) {

            // fehlAnzPosDiff ist nicht Null.
            if (fehlAnzPosDiff < 0) {
                return wekaClassTrue;
            } else {
                return wekaClassFalse;
            }

        } else if (Math.abs(fehlAnzPosDiff) < Math.abs(fehlAnzNegDiff)) {

            // fehlAnzNegDiff ist nicht Null.
            if (fehlAnzNegDiff > 0) {
                return wekaClassTrue;
            } else {
                return wekaClassFalse;
            }

        } else {
            // Die Vernderung der Fehleranzahl bezglich der Klassse des
            // Testbeispiels ist fr beide Formeln aller Beispiel der
            // jeweiligen Klasse gleich.

            if ((Math.abs(komplexPosDiff - komplexNegDiff) >= 2 * lokalGrenzwert)
                    && (komplexPosDiff != komplexNegDiff)) {

                // Klassifikation nach den Komplexitten.
                if (Math.abs(komplexPosDiff) > Math.abs(komplexNegDiff)) {

                    // komplexPosDiff ist nicht Null.
                    if (komplexPosDiff < 0) {
                        return wekaClassTrue;
                    } else {
                        return wekaClassFalse;
                    }

                } else {

                    // komplexNegDiff ist betragsmig grer als
                    // komplexPosDiff und nicht Null.
                    if (komplexNegDiff > 0) {
                        return wekaClassTrue;
                    } else {
                        return wekaClassFalse;
                    }

                }

            } else if (lokalGrenzwert > 0) {
                // Eine lokale Klassifikation vornehmen.

                // Erzeugung der effizientesten Konzepte nach Hinzunahme
                // des Testbeispiels.
                posKonzeptTrue = generatedAddConcept(posDatensatz, praedErzParameter, konzErzParameter,
                        posFormel, testbeispiel, true);
                posKonzeptFalse = generatedAddConcept(posDatensatz, praedErzParameter, konzErzParameter,
                        posFormel, testbeispiel, false);
                negKonzeptTrue = generatedAddConcept(negDatensatz, praedErzParameter, konzErzParameter,
                        negFormel, testbeispiel, true);
                negKonzeptFalse = generatedAddConcept(negDatensatz, praedErzParameter, konzErzParameter,
                        negFormel, testbeispiel, false);

                // Die Bewertungen der Konzepte ermitteln.
                bewertPosTrue = KonzeptErzeugungFacade.konzeptEffizienz(posKonzeptTrue);
                bewertPosFalse = KonzeptErzeugungFacade.konzeptEffizienz(posKonzeptFalse);
                bewertNegTrue = KonzeptErzeugungFacade.konzeptEffizienz(negKonzeptTrue);
                bewertNegFalse = KonzeptErzeugungFacade.konzeptEffizienz(negKonzeptFalse);
                bewertPosDiff = bewertPosTrue - bewertPosFalse;
                bewertNegDiff = bewertNegTrue - bewertNegFalse;

                if (Math.abs(bewertPosDiff) >= Math.abs(bewertNegDiff)) {
                    if (bewertPosDiff >= 0) {
                        return wekaClassTrue;
                    } else {
                        return wekaClassFalse;
                    }
                } else {
                    if (bewertNegDiff < 0) {
                        return wekaClassTrue;
                    } else {
                        return wekaClassFalse;
                    }
                }

            } else {
                // Die Vernderung der Komplexitt bezglich der Klassse
                // des Testbeispiels ist fr beide Formeln aller Beispiel
                // der jeweiligen Klasse gleich und eine lokale
                // Klassifikation soll nicht erfolgen. Daher nach der
                // Anzahl der Beispiele der Klassen klassifizieren.

                if (posDatensatz.posBspAnz() >= posDatensatz.negBspAnz()) {
                    return wekaClassTrue;
                } else {
                    return wekaClassFalse;
                }
            }
        }
    }
}

From source file:lu.lippmann.cdb.lab.beta.util.WekaUtil2.java

License:Open Source License

/**
 * Generate the centroid coordinates based 
 * on it's  members (objects assigned to the cluster of the centroid) and the distance 
 * function being used./*from w  w  w .  ja  va 2  s  .c om*/
 * @return the centroid
 */
public static MixedCentroid computeMixedCentroid(final boolean preserveOrder,
        final NormalizableDistance distanceFunction, final Instances numericInstances,
        final Instances originalInstances, final int clusterIndex) {
    final int numInstances = numericInstances.numInstances();
    final int numAttributes = numericInstances.numAttributes();

    final Map<TupleSI, Integer> addedAttr = new HashMap<TupleSI, Integer>();

    if (numInstances == 1) {
        Instance uniqueNumInstance = numericInstances.firstInstance();
        Instance uniqueMixInstance = originalInstances.firstInstance();
        double[] centroid = uniqueNumInstance.toDoubleArray();
        for (int i = 0; i < uniqueMixInstance.numAttributes(); i++) {
            if (!uniqueMixInstance.attribute(i).isNumeric()) {
                final String catVal = uniqueMixInstance.attribute(i).value((int) uniqueMixInstance.value(i));
                addedAttr.put(new TupleSI(catVal, i), 1);
            }
        }
        return new MixedCentroid(clusterIndex, centroid, addedAttr);
    }

    final double[] vals = new double[numAttributes];

    //used only for Manhattan Distance
    Instances sortedMembers = null;
    int middle = 0;
    boolean dataIsEven = false;

    final boolean isManhattanDist = (distanceFunction instanceof ManhattanDistance);
    final boolean isEuclideanDist = (distanceFunction instanceof EuclideanDistance);

    if (isManhattanDist) {
        middle = (numInstances - 1) / 2;
        dataIsEven = ((numInstances % 2) == 0);
        if (preserveOrder) {
            sortedMembers = numericInstances;
        } else {
            sortedMembers = new Instances(numericInstances);
        }
    }

    for (int j = 0; j < numAttributes; j++) {
        //in case of Euclidian distance the centroid is the mean point
        //in case of Manhattan distance the centroid is the median point
        //in both cases, if the attribute is nominal, the centroid is the mode            
        if (isEuclideanDist) {
            vals[j] = numericInstances.meanOrMode(j);

            for (int i = 0; i < numInstances; i++) {
                if (!originalInstances.attribute(j).isNumeric()) {
                    final Instance instance = originalInstances.instance(i);
                    final String catVal = instance.attribute(j).value((int) instance.value(j));
                    //Initialize map
                    final TupleSI key = new TupleSI(catVal, j);
                    if (!addedAttr.containsKey(key))
                        addedAttr.put(key, 0);
                    addedAttr.put(key, addedAttr.get(key) + 1);
                }
            }
        } else if (isManhattanDist) {
            sortedMembers.kthSmallestValue(j, middle + 1);
            vals[j] = sortedMembers.instance(middle).value(j);
            if (dataIsEven) {
                sortedMembers.kthSmallestValue(j, middle + 2);
                vals[j] = (vals[j] + sortedMembers.instance(middle + 1).value(j)) / 2;
            }
        } else {
            throw new IllegalStateException("Not handled distance ...");
        }
    }

    return new MixedCentroid(clusterIndex, vals, addedAttr);
}

From source file:lu.lippmann.cdb.lab.kmeans.KmeansImproved.java

License:Open Source License

/**
 * //from  w  w  w. ja v  a  2s .c  o m
 * @param instances
 * @param k
 * @param clusters_sizes
 * @param clusters_centroids
 * @return
 */
private double R2(SimpleKMeans kMeans) {
    //int k, int[] clusters_sizes, Instances clusters_centroids){
    final int k = kMeans.getNumClusters();
    final int[] clusters_sizes = kMeans.getClusterSizes();
    final Instances clusters_centroids = kMeans.getClusterCentroids();
    double inter, total;
    double[] weights = new double[k];
    double[] centroid = new double[instances.numAttributes()];
    final int N = instances.numInstances();
    final double instance_weight = 1.0;
    inter = total = 0;

    //Computing the centroid of the entire set
    for (int i = 0; i < N; i++) {
        final Instance instance = instances.get(i);
        double[] temp = instance.toDoubleArray();
        for (int j = 0; j < temp.length; j++)
            centroid[j] += temp[j];
    }
    for (int j = 0; j < centroid.length; j++) {
        centroid[j] = centroid[j] / N;
    }

    for (int i = 0; i < k; i++) {
        weights[i] = (0.0 + clusters_sizes[i]) / N;
    }

    final Instance centroid_G = new DenseInstance(instance_weight, centroid);
    for (int i = 0; i < N; i++) {
        total += Math.pow(distance.distance(instances.instance(i), centroid_G), 2);
    }
    total = total / N;

    for (int i = 0; i < k; i++) {
        inter += weights[i] * Math.pow(distance.distance(clusters_centroids.get(i), centroid_G), 2);
    }

    return (inter / total);
}

From source file:meka.core.MLUtils.java

License:Open Source License

/**
 * GetxfromInstances - Extract attributes as a double x[] from an Instance.
 *///from  ww  w .j  a  va2  s.  c  o m
public static double[] getxfromInstance(Instance xy) {
    int L = xy.classIndex();
    double xy_[] = xy.toDoubleArray();
    return Arrays.copyOfRange(xy_, L, xy_.length);
}

From source file:moa.classifiers.featureselection.OFSL.java

License:Open Source License

@Override
public double[] getVotesForInstance(Instance inst) {

    if (this.weights == null)
        return (inst.classAttribute().isNominal()) ? new double[2] : new double[1];

    double[] result = (inst.classAttribute().isNominal()) ? new double[2] : new double[1];
    double f_t = dot(inst.toDoubleArray(), this.weights);
    f_t += this.bias;

    if (inst.classAttribute().isNumeric()) {
        result[0] = f_t;//  w  ww . ja  va  2  s.c o m
        return result;
    }
    if (f_t <= 0) {
        result[0] = 1;
    } else {
        result[1] = 1;
    }

    return result;
}