Example usage for weka.core Instance numAttributes

List of usage examples for weka.core Instance numAttributes

Introduction

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

Prototype

public int numAttributes();

Source Link

Document

Returns the number of attributes.

Usage

From source file:machinelearning_cw.KNN.java

@Override
public double classifyInstance(Instance instance) throws Exception {
    // Check that classifier has been trained
    if (trainingData == null) {
        throw new Exception("Classifier has not been trained." + " No call to buildClassifier() was made");
    }/*from  w w  w  . j  a v  a 2s .  co m*/

    if (useStandardisedAttributes) {
        if (!isMeanAndStdDevInitialised) {
            // throw exception
        } else {
            /* Standardise test instance */
            for (int i = 0; i < instance.numAttributes() - 1; i++) {
                double value = instance.value(i);
                double standardisedValue = (value - mean[i]) / standardDeviation[i];
                instance.setValue(i, standardisedValue);
            }
        }
    }

    if (!useWeightedVoting) {
        return super.classifyInstance(instance);
    } else {

        if (!useAcceleratedNNSearch) {
            /* Calculate euclidean distances */
            double[] distances = Helpers.findEuclideanDistances(trainingData, instance);

            /* 
             * Create a list of dictionaries where each dictionary contains
             * the keys "distance", "weight" and "id".
             * The distance key stores the euclidean distance for an  
             * instance and the id key stores the hashcode for that 
             * instance object.
             */
            ArrayList<HashMap<String, Object>> table = Helpers.buildDistanceTable(trainingData, distances);

            /* Find the k smallest distances */
            Object[] kClosestRows = new Object[k];
            Object[] kClosestInstances = new Object[k];
            double[] classValues = new double[k];

            for (int i = 1; i <= k; i++) {
                ArrayList<Integer> tieIndices = new ArrayList<Integer>();

                /* Find the positions in the table of the ith closest 
                 * neighbour.
                 */
                int[] closestRowIndices = this.findNthClosestNeighbourByWeights(table, i);

                if (closestRowIndices.length > 0) {
                    /* Keep track of distance ties */
                    for (int j = 0; j < closestRowIndices.length; j++) {
                        tieIndices.add(closestRowIndices[j]);
                    }

                    /* Break ties (by choosing winner at random) */
                    Random rand = new Random();
                    int matchingNeighbourPosition = tieIndices.get(rand.nextInt(tieIndices.size()));
                    HashMap<String, Object> matchingRow = table.get(matchingNeighbourPosition);
                    kClosestRows[i - 1] = matchingRow;
                }
            }

            /* 
             * Find the closestInstances from their rows in the table and 
             * also get their class values.
             */
            for (int i = 0; i < kClosestRows.length; i++) {
                /* Build up closestInstances array */
                for (int j = 0; j < trainingData.numInstances(); j++) {
                    Instance inst = trainingData.get(j);
                    HashMap<String, Object> row = (HashMap<String, Object>) kClosestRows[i];
                    if (Integer.toHexString(inst.hashCode()).equals(row.get("id"))) {
                        kClosestInstances[i] = inst;
                    }
                }
            }

            /* Vote by weights */
            /* Get max class value */
            double[] possibleClassValues = trainingData.attributeToDoubleArray(trainingData.classIndex());
            int maxClassIndex = Utils.maxIndex(possibleClassValues);
            double maxClassValue = possibleClassValues[maxClassIndex];
            ArrayList<Double> weightedVotes = new ArrayList<Double>();

            /* Calculate the sum of votes for each class */
            for (double i = 0; i <= maxClassValue; i++) {
                double weightCount = 0;

                /* Calculate sum */
                for (int j = 0; j < kClosestInstances.length; j++) {
                    Instance candidateInstance = (Instance) kClosestInstances[j];
                    if (candidateInstance.classValue() == i) {
                        // Get weight
                        HashMap<String, Object> row = (HashMap<String, Object>) kClosestRows[(int) j];
                        weightCount += (double) row.get("weight");
                    }
                }

                weightedVotes.add(weightCount);
            }

            /* Select instance with highest vote */
            Double[] votesArray = new Double[weightedVotes.size()];
            weightedVotes.toArray(votesArray);
            double greatestSoFar = votesArray[0];
            int greatestIndex = 0;
            for (int i = 0; i < votesArray.length; i++) {
                if (votesArray[i] > greatestSoFar) {
                    greatestSoFar = votesArray[i];
                    greatestIndex = i;
                }
            }

            /* 
             * Class value will be the index because classes are indexed 
             * from 0 upwards.
             */
            return greatestIndex;

        }
        /* Use Orchards algorithm to accelerate NN search */
        else {
            // find k nearest neighbours
            ArrayList<Instance> nearestNeighbours = new ArrayList<Instance>();
            for (int i = 0; i < k; i++) {
                nearestNeighbours.add(findNthClosestWithOrchards(instance, trainingData, i));
            }

            // Find their class values
            double[] classValues = new double[nearestNeighbours.size()];

            for (int i = 0; i < nearestNeighbours.size(); i++) {
                classValues[i] = nearestNeighbours.get(i).classValue();
            }

            return Helpers.mode(Helpers.arrayToArrayList(classValues));
        }

    }

}

From source file:meka.core.MLUtils.java

License:Open Source License

/**
 * CopyValues - Set x_dest[j+offset] = x_src[i+from].
 */// w w w. j  a  v a 2s .  com
public static final Instance copyValues(Instance x_dest, Instance x_src, int from, int offset) {
    int d = x_src.numAttributes();
    for (int i = from, j = 0; i < d; i++, j++) {
        x_dest.setValue(j + offset, x_src.value(i));
    }
    return x_dest;
}

From source file:meka.experiment.statisticsexporters.WekaFilter.java

License:Open Source License

/**
 * Converts the Instances back into statistics.
 *
 * @param data          the data to convert
 * @return              the generated statistics
 *///from w  w  w . j a v a2 s  .co m
protected List<EvaluationStatistics> fromInstances(Instances data) {
    List<EvaluationStatistics> result;
    EvaluationStatistics stat;
    MultiLabelClassifier cls;
    String rel;
    int i;
    int n;
    Instance inst;

    result = new ArrayList<>();

    if (data.attribute(EvaluationStatistics.KEY_CLASSIFIER) == null) {
        log("Failed to locate attribute: " + EvaluationStatistics.KEY_CLASSIFIER);
        return result;
    }
    if (data.attribute(EvaluationStatistics.KEY_RELATION) == null) {
        log("Failed to locate attribute: " + EvaluationStatistics.KEY_RELATION);
        return result;
    }

    for (i = 0; i < data.numInstances(); i++) {
        inst = data.instance(i);
        try {
            cls = OptionUtils.fromCommandLine(MultiLabelClassifier.class,
                    inst.stringValue(data.attribute(EvaluationStatistics.KEY_CLASSIFIER)));
            rel = inst.stringValue(data.attribute(EvaluationStatistics.KEY_RELATION));
            stat = new EvaluationStatistics(cls, rel, null);
            for (n = 0; n < inst.numAttributes(); n++) {
                if (inst.attribute(n).isNumeric() && !inst.isMissing(n)) {
                    stat.put(inst.attribute(n).name(), inst.value(n));
                }
            }
            result.add(stat);
        } catch (Exception e) {
            handleException("Failed to process instance: " + inst, e);
        }
    }

    return result;
}

From source file:milk.classifiers.MINND.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. co m*/
 * @param second the second instance
 * @return the distance between the two given instances
 */
private double distance(Instance first, double[] mean, double[] var, int pos) {

    double diff, distance = 0;
    int j = 0;
    for (int i = 0; i < first.numAttributes(); i++) {
        // Skipp nominal attributes (incl. class & ID)
        if ((i == m_ClassIndex) || (i == m_IdIndex))
            continue;

        // If attribute is numeric
        if (first.attribute(i).isNumeric()) {
            if (!first.isMissing(i)) {
                diff = first.value(i) - mean[j];
                if (Utils.gr(var[j], m_ZERO))
                    distance += m_Change[pos][j] * var[j] * diff * diff;
                else
                    distance += m_Change[pos][j] * diff * diff;
            } else {
                if (Utils.gr(var[j], m_ZERO))
                    distance += m_Change[pos][j] * var[j];
                else
                    distance += m_Change[pos][j] * 1.0;
            }
        }
        j++;
    }

    return distance;
}

From source file:minorpro.BitsUtility.java

public static String convertToBits(Instance ins) {
    String bits = "";
    for (int i = 0; i < ins.numAttributes() - 1; i++) {
        double d = 0, a = ins.value(i);
        switch (i) {
        case 0://from ww  w  . j a  v a 2s.c o  m
            d = (a + 7) / 2;
            break;
        case 1:
            d = a - 4;
            break;
        case 2:
        case 3:
            d = a;
            break;
        }

        bits = bits + intToBits(d);
    }
    return bits;
}

From source file:ml.ann.BackPropagation.java

License:Open Source License

private void initInputAndTarget(Instance instance) {
    int classAttributeIdx = neuronTopology.instances.classIndex();
    if (neuronTopology.instances.classAttribute().isNumeric()) {
        neuronTopology.target = new double[1];
        neuronTopology.target[0] = instance.value(classAttributeIdx);
    } else if (neuronTopology.instances.classAttribute().isNominal()) {
        neuronTopology.target = new double[instance.numClasses()];
        for (int i = 0; i < instance.numClasses(); i++) {
            neuronTopology.target[i] = 0;
        }/*  w  ww . j a v  a 2 s  .  c  o  m*/
        int idxClassValue = (int) instance.classValue();
        neuronTopology.target[idxClassValue] = 1;
    }
    for (int i = 0; i < instance.numAttributes(); i++) {
        if (i == 0) {
            neuronTopology.input[i] = 1;
            neuronTopology.output[0][i] = 1;
        } else {
            neuronTopology.input[i] = instance.value(i - 1);
            neuronTopology.output[0][i] = instance.value(i - 1);
        }
    }
    //        System.out.println(neuronTopology.originInstances.instance(instancesIdx).toString());
}

From source file:ml.ann.BackPropagation.java

License:Open Source License

@Override
public double[] distributionForInstance(Instance instance) throws Exception {

    Instance currentInstance;
    // default model?
    if (useDefaultModel) {
        return zeroR.distributionForInstance(instance);
    }/*from   w w  w.ja  v a2 s . com*/

    // Make a copy of the instance so that it isn't modified
    currentInstance = (Instance) instance.copy();

    for (int noa = 0; noa < currentInstance.numAttributes(); noa++) {
        if (noa != neuronTopology.instances.classIndex()) {
            if (attributeRanges[noa] != 0) {
                currentInstance.setValue(noa,
                        (currentInstance.value(noa) - attributeBases[noa]) / attributeRanges[noa]);
            } else {
                currentInstance.setValue(noa, currentInstance.value(noa) - attributeBases[noa]);
            }
        }
    }
    //        resetNetwork();

    //        initInputAndTarget(currentInstance);

    int lastLayerIdx = neuronTopology.numLayers - 1;
    for (int layers = 0; layers < neuronTopology.numLayers; layers++) {
        for (int neu = 0; neu < neuronTopology.numNeuronEachLayer[layers]; neu++) {
            neuronTopology.output[layers][neu] = sigmoidFunction(layers, neu);
        }
    }

    double[] jancuk = new double[neuronTopology.numNeuronEachLayer[lastLayerIdx]];

    for (int i = 0; i < neuronTopology.numNeuronEachLayer[lastLayerIdx]; i++) {
        jancuk[i] = neuronTopology.output[lastLayerIdx][i];
    }

    // now normalize the array
    double count = 0;
    for (int noa = 0; noa < neuronTopology.numClasses; noa++) {
        count += jancuk[noa];
    }
    if (count <= 0) {
        //            return zeroR.distributionForInstance(i);
    }
    for (int noa = 0; noa < neuronTopology.numClasses; noa++) {
        jancuk[noa] /= count;
    }
    return jancuk;
}

From source file:ml.ann.MultiClassPTR.java

@Override
public void buildClassifier(Instances instances) throws Exception {
    initAttributes(instances);//  w  w  w .j a  v a  2s. c o  m

    // REMEMBER: only works if class index is in the last position
    for (int instanceIdx = 0; instanceIdx < instances.numInstances(); instanceIdx++) {
        Instance instance = instances.get(instanceIdx);
        double[] inputInstance = inputInstances[instanceIdx];
        inputInstance[0] = 1.0; // initialize bias value
        for (int attrIdx = 0; attrIdx < instance.numAttributes() - 1; attrIdx++) {
            inputInstance[attrIdx + 1] = instance.value(attrIdx); // the first index of input instance is for bias
        }
    }

    // Initialize target values
    if (instances.classAttribute().isNominal()) {
        for (int instanceIdx = 0; instanceIdx < instances.numInstances(); instanceIdx++) {
            Instance instance = instances.instance(instanceIdx);
            for (int classIdx = 0; classIdx < instances.numClasses(); classIdx++) {
                targetInstances[instanceIdx][classIdx] = 0.0;
            }
            targetInstances[instanceIdx][(int) instance.classValue()] = 1.0;
        }
    } else {
        for (int instanceIdx = 0; instanceIdx < instances.numInstances(); instanceIdx++) {
            Instance instance = instances.instance(instanceIdx);
            targetInstances[instanceIdx][0] = instance.classValue();
        }
    }

    if (algo == 1) {
        setActFunction();
        buildClassifier();
    } else if (algo == 2) {
        buildClassifier();
    } else if (algo == 3) {
        buildClassifierBatch();
    }
}

From source file:ml.ann.MultiClassPTR.java

@Override
public double[] distributionForInstance(Instance instance) throws Exception {
    double[] input = new double[numInput]; // remember the first index use for bias input
    input[0] = 1.0;/*from  ww w .j  a  v a  2s  .c  o  m*/
    for (int attrIdx = 0; attrIdx < instance.numAttributes() - 1; attrIdx++) { // we ignore the class value
        input[attrIdx + 1] = instance.value(attrIdx);
    }

    double[] output = new double[numOutput];
    double totalVal = 0.0;
    System.out.println("=========================");
    for (int outputIdx = 0; outputIdx < numOutput; outputIdx++) {
        output[outputIdx] = 0.0;
        for (int inputIdx = 0; inputIdx < numInput; inputIdx++) {
            output[outputIdx] += input[inputIdx] * weight[inputIdx][outputIdx];
        }
        output[outputIdx] = actFunction(output[outputIdx]);
        System.out.print(output[outputIdx] + " ");
        totalVal += Math.exp(output[outputIdx]);
    }
    for (int out = 0; out < numOutput; out++) {
        output[out] = Math.exp(output[out]) / totalVal;
    }
    return output;
}

From source file:moa.classifiers.bayes.NaiveBayes.java

License:Open Source License

@Override
public void trainOnInstanceImpl(Instance inst) {
    this.observedClassDistribution.addToValue((int) inst.classValue(), inst.weight());
    for (int i = 0; i < inst.numAttributes() - 1; i++) {
        int instAttIndex = modelAttIndexToInstanceAttIndex(i, inst);
        AttributeClassObserver obs = this.attributeObservers.get(i);
        if (obs == null) {
            obs = inst.attribute(instAttIndex).isNominal() ? newNominalClassObserver()
                    : newNumericClassObserver();
            this.attributeObservers.set(i, obs);
        }//from  www.j av  a2s .c o m
        obs.observeAttributeClass(inst.value(instAttIndex), (int) inst.classValue(), inst.weight());
    }
}