Example usage for weka.classifiers Classifier classifyInstance

List of usage examples for weka.classifiers Classifier classifyInstance

Introduction

In this page you can find the example usage for weka.classifiers Classifier classifyInstance.

Prototype

public double classifyInstance(Instance instance) throws Exception;

Source Link

Document

Classifies the given test instance.

Usage

From source file:anndl.Anndl.java

private void ClassifyInstance(String fileinput) throws Exception {
    System.out.println("Membaca File Model ..");
    Classifier cls = (Classifier) weka.core.SerializationHelper.read(fileinput);

    System.out.println("Masukan Data yang ingin diklasifikasikan, pisahkan dengan spasi :");
    String testset = scanner.nextLine();
    testset = "1 1 0";
    String[] exploded = testset.split(" ");

    Instance newinstance = new Instance(exploded.length);
    for (int i = 0; i < exploded.length; i++) {
        String exploded1 = exploded[i];
        System.out.println(exploded[i] + ";");

        newinstance.setValue(i, Integer.valueOf(exploded[i]));
    }/*w  ww . j  a  v  a 2s.  c o  m*/

    System.out.println("Melakukan klasifikasi ... ");
    double result = cls.classifyInstance(newinstance);
    System.out.println("Data ini:");
    System.out.println(testset);
    System.out.println("memiliki label :");
    System.out.println(newinstance.value(newinstance.classIndex()));
}

From source file:au.edu.usyd.it.yangpy.snp.Ensemble.java

License:Open Source License

public double classify(Classifier c, int cId) throws Exception {

    // train the classifier with training data
    c.buildClassifier(train);/* w  w w.j  av a 2 s. c o  m*/

    // get the predict value and predict distribution from each test instances
    for (int i = 0; i < test.numInstances(); i++) {
        predictDistribution[cId][i] = c.distributionForInstance(test.instance(i));
        predictValue[cId][i] = c.classifyInstance(test.instance(i));
    }

    // of course, get the AUC for each classifier
    Evaluation eval = new Evaluation(train);
    eval.evaluateModel(c, test);
    return eval.areaUnderROC(1) * 100;
}

From source file:bme.mace.logicdomain.Evaluation.java

License:Open Source License

/**
 * Evaluates the classifier on a single instance.
 * //  ww  w.java2  s  . c om
 * @param classifier machine learning classifier
 * @param instance the test instance to be classified
 * @return the prediction made by the clasifier
 * @throws Exception if model could not be evaluated successfully or the data
 *           contains string attributes
 */
public double evaluateModelOnce(Classifier classifier, Instance instance) throws Exception {

    Instance classMissing = (Instance) instance.copy();
    double pred = 0;
    classMissing.setDataset(instance.dataset());
    classMissing.setClassMissing();
    if (m_ClassIsNominal) {
        double[] dist = classifier.distributionForInstance(classMissing);
        pred = Utils.maxIndex(dist);
        if (dist[(int) pred] <= 0) {
            pred = Instance.missingValue();
        }
        updateStatsForClassifier(dist, instance);
    } else {
        pred = classifier.classifyInstance(classMissing);
        updateStatsForPredictor(pred, instance);
    }
    return pred;
}

From source file:bme.mace.logicdomain.Evaluation.java

License:Open Source License

/**
 * store the prediction made by the classifier as a string
 * //from   w  w w . java  2s .  com
 * @param classifier the classifier to use
 * @param inst the instance to generate text from
 * @param instNum the index in the dataset
 * @param attributesToOutput the indices of the attributes to output
 * @param printDistribution prints the complete distribution for nominal
 *          classes, not just the predicted value
 * @return the prediction as a String
 * @throws Exception if something goes wrong
 * @see #printClassifications(Classifier, Instances, String, int, Range,
 *      boolean)
 */
protected static String predictionText(Classifier classifier, Instance inst, int instNum,
        Range attributesToOutput, boolean printDistribution)

        throws Exception {

    StringBuffer result = new StringBuffer();
    int width = 10;
    int prec = 3;

    Instance withMissing = (Instance) inst.copy();
    withMissing.setDataset(inst.dataset());
    withMissing.setMissing(withMissing.classIndex());
    double predValue = classifier.classifyInstance(withMissing);

    // index
    result.append(Utils.padLeft("" + (instNum + 1), 6));

    if (inst.dataset().classAttribute().isNumeric()) {
        // actual
        if (inst.classIsMissing()) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(inst.classValue(), width, prec));
        }
        // predicted
        if (Instance.isMissingValue(predValue)) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(predValue, width, prec));
        }
        // error
        if (Instance.isMissingValue(predValue) || inst.classIsMissing()) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.doubleToString(predValue - inst.classValue(), width, prec));
        }
    } else {
        // actual
        result.append(" "
                + Utils.padLeft(((int) inst.classValue() + 1) + ":" + inst.toString(inst.classIndex()), width));
        // predicted
        if (Instance.isMissingValue(predValue)) {
            result.append(" " + Utils.padLeft("?", width));
        } else {
            result.append(" " + Utils.padLeft(
                    ((int) predValue + 1) + ":" + inst.dataset().classAttribute().value((int) predValue),
                    width));
        }
        // error?
        if (!Instance.isMissingValue(predValue) && !inst.classIsMissing()
                && ((int) predValue + 1 != (int) inst.classValue() + 1)) {
            result.append(" " + "  +  ");
        } else {
            result.append(" " + "     ");
        }
        // prediction/distribution
        if (printDistribution) {
            if (Instance.isMissingValue(predValue)) {
                result.append(" " + "?");
            } else {
                result.append(" ");
                double[] dist = classifier.distributionForInstance(withMissing);
                for (int n = 0; n < dist.length; n++) {
                    if (n > 0) {
                        result.append(",");
                    }
                    if (n == (int) predValue) {
                        result.append("*");
                    }
                    result.append(Utils.doubleToString(dist[n], prec));
                }
            }
        } else {
            if (Instance.isMissingValue(predValue)) {
                result.append(" " + "?");
            } else {
                result.append(" " + Utils.doubleToString(
                        classifier.distributionForInstance(withMissing)[(int) predValue], prec));
            }
        }
    }

    // attributes
    result.append(" " + attributeValuesString(withMissing, attributesToOutput) + "\n");

    return result.toString();
}

From source file:boa.functions.BoaIntrinsics.java

License:Apache License

/**
 * Classify instances for given ML model
 *
 * @param Take Model Type/*w w w  .ja  v a 2 s . c  om*/
 * @return Predicted value for a instance
 */
@FunctionSpec(name = "classify", returnType = "float", formalParameters = { "Model", "array of float" })
public static double classify(final Object model, final double[] vector) throws Exception {
    List<Attribute> attribute = new ArrayList<Attribute>();
    int size = vector.length;
    int NumOfAttributes = size + 1;

    FastVector fvAttributes = new FastVector(NumOfAttributes);
    for (int i = 0; i < NumOfAttributes; i++) {
        attribute.add(new Attribute("Attribute" + i));
        fvAttributes.addElement(attribute.get(i));
    }

    Instances testingSet = new Instances("Classifier", fvAttributes, 1);
    testingSet.setClassIndex(NumOfAttributes - 1);

    Instance instance = new Instance(NumOfAttributes);
    for (int i = 0; i < size; i++) {
        instance.setValue((Attribute) fvAttributes.elementAt(i), vector[i]);
    }

    Classifier classifier = (Classifier) model;
    double predval = classifier.classifyInstance(instance);

    return predval;
}

From source file:br.puc_rio.ele.lvc.interimage.datamining.udf.BayesClassifier.java

License:Apache License

@Override
public String exec(Tuple input) throws IOException {
    if (input == null)
        return null;

    if (_trainData == null) {

        //Reads train data
        try {/*from w w w  .j  a  va  2 s .  com*/

            if (!_trainUrl.isEmpty()) {

                URL url = new URL(_trainUrl);
                URLConnection urlConn = url.openConnection();
                urlConn.connect();
                InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
                BufferedReader buff = new BufferedReader(inStream);

                _trainData = _dataParser.parseData(buff);

            }
        } catch (Exception e) {
            throw new IOException("Caught exception reading training data file ", e);
        }

    }

    try {
        Integer numFeatures = input.size();

        double[] testData;
        testData = new double[numFeatures];

        for (int i = 0; i < numFeatures; i++)
            testData[i] = DataType.toDouble(input.get(i));

        Classifier csfr = null;
        csfr = (Classifier) Class.forName("weka.classifiers.bayes.NaiveBayes").newInstance();
        csfr.buildClassifier(_trainData);
        double classification = 0;

        Instance myinstance = _trainData.instance(0);
        for (int i = 0; i < numFeatures; i++)
            myinstance.setValue(i, testData[i]);
        classification = csfr.classifyInstance(myinstance);

        return myinstance.attribute(_trainData.classIndex()).value((int) classification);

    } catch (Exception e) {
        throw new IOException("Caught exception processing input row ", e);
    }
}

From source file:ca.uqac.florentinth.speakerauthentication.Learning.Learning.java

License:Apache License

public Map<String, String> makePrediction(String username, FileInputStream trainingModel,
        FileReader testingDataset) throws Exception {
    Map<String, String> predictions = new HashMap<>();

    ObjectInputStream inputStream = new ObjectInputStream(trainingModel);
    weka.classifiers.Classifier classifier = (weka.classifiers.Classifier) inputStream.readObject();
    inputStream.close();//from w w  w. j a v a 2 s. co m

    Instances instances = new Instances(new BufferedReader(testingDataset));

    if (instances.classIndex() == -1) {
        instances.setClassIndex(instances.numAttributes() - 1);
    }

    int last = instances.numInstances() - 1;

    if (instances.instance(last).stringValue(instances.classIndex()).equals(username)) {
        double label = classifier.classifyInstance(instances.instance(last));
        instances.instance(last).setClassValue(label);
        predictions.put(username, instances.instance(last).stringValue(instances.classIndex()));
    }

    return predictions;
}

From source file:cish.CISH.java

/**
 * Returns the (only) centromer points (cep), (only) gene points and the points which are classified as 
 * centromer and gene (whenever the gene is too close to the centromer).
 * @param ip The image as image processor on which points are classified.
 * @param circles The points which are classified into the three classes cep, gene and both.
 * @param r A radius r for feature extraction around each point.
 * @param classifier A trained classifier used for classification.
 * @param dataset A dataset used for classification (technically necessary).
 * @return Three lists are returned: ceps, a n x 5 list for n centromer points, each with x coord, y coord, R G and B color value;
 * genes, a m x 5 list for m gene points, each with x coord, y coord, R G and B color value;
 * both, a k x 5 list for k "both" points, each with x coord, y coord, R G and B color value;
 *///from  w w w  .  j  av a2s.co  m
static List<List> getPoints(ImageProcessor ip, Point[] circles, int r, Classifier classifier,
        Instances dataset) {
    List<int[]> ceps = new ArrayList<>();
    List<int[]> genes = new ArrayList<>();
    List<int[]> both = new ArrayList<>();

    int x, y;
    Instance inst;
    double c;
    for (Point p : circles) {
        try {
            x = p.x;
            y = p.y;

            double[] attValues = new double[(2 * r + 1) * (2 * r + 1) * 3 + 1];
            int k = 0;
            int[] rgb = new int[3];
            for (int n = 0; n < 3; n++) {
                for (int i = x - r; i <= x + r; i++) {
                    for (int j = y - r; j <= y + r; j++) {
                        ip.getPixel(i, j, rgb);
                        attValues[k] = rgb[n] / 255.0;
                        k++;
                    }
                }
            }
            inst = new Instance(1, attValues);
            inst.setDataset(dataset);
            c = classifier.classifyInstance(inst);
            int[] entry = Misc.concat(new int[] { x, y }, COLORS[(int) c]);
            switch ((int) c) {
            case 0:
                ceps.add(entry);
                break;
            case 1:
                genes.add(entry);
                break;
            case 4:
                both.add(entry);
                break;
            default:
                break;
            }
        } catch (Exception ex) {
            //Logger.getLogger(CISH.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    List<List> out = new ArrayList<>();
    out.add(ceps);
    out.add(genes);
    out.add(both);
    return out;
}

From source file:clasificacion.Clasificacion.java

public String clasificar(String[] testCases) throws Exception {
    String ruta = "nursery_model.model";

    InputStream classModelStream;
    classModelStream = getClass().getResourceAsStream(ruta);
    //classModel = (Classifier)SerializationHelper.read(classModelStream);
    Classifier clasify = (Classifier) SerializationHelper.read(classModelStream);

    FastVector parents = new FastVector();
    parents.addElement("usual");
    parents.addElement("pretentious");
    parents.addElement("great_pret");
    Attribute _parent = new Attribute("parents", parents);

    FastVector nurs = new FastVector();
    nurs.addElement("proper");
    nurs.addElement("less_proper");
    nurs.addElement("improper");
    nurs.addElement("critical");
    nurs.addElement("very_crit");
    Attribute _has_nurs = new Attribute("has_nurs", nurs);

    FastVector form = new FastVector();
    form.addElement("complete");
    form.addElement("completed");
    form.addElement("incomplete");
    form.addElement("foster");
    Attribute _form = new Attribute("form", form);

    FastVector children = new FastVector();
    children.addElement("1");
    children.addElement("2");
    children.addElement("3");
    children.addElement("more");
    Attribute _children = new Attribute("children", children);

    FastVector housing = new FastVector();
    housing.addElement("convenient");
    housing.addElement("less_conv");
    housing.addElement("critical");
    Attribute _housing = new Attribute("housing", housing);

    FastVector finance = new FastVector();
    finance.addElement("convenient");
    finance.addElement("inconv");
    Attribute _finance = new Attribute("finance", finance);

    FastVector social = new FastVector();
    social.addElement("nonprob");
    social.addElement("slightly_prob");
    social.addElement("problematic");
    Attribute _social = new Attribute("social", social);

    FastVector health = new FastVector();
    health.addElement("recommended");
    health.addElement("priority");
    health.addElement("not_recom");
    Attribute _health = new Attribute("health", health);

    FastVector Class = new FastVector();
    Class.addElement("not_recom");
    Class.addElement("recommend");
    Class.addElement("very_recom");
    Class.addElement("priority");
    Class.addElement("spec_prior");
    Attribute _Class = new Attribute("class", Class);

    FastVector atributos = new FastVector(9);
    atributos.addElement(_parent);//from ww  w.  j a  v a2 s  . c  o  m
    atributos.addElement(_has_nurs);
    atributos.addElement(_form);
    atributos.addElement(_children);
    atributos.addElement(_housing);
    atributos.addElement(_finance);
    atributos.addElement(_social);
    atributos.addElement(_health);
    atributos.addElement(_Class);

    ArrayList<Attribute> atributs = new ArrayList<>();
    atributs.add(_parent);
    atributs.add(_has_nurs);
    atributs.add(_form);
    atributs.add(_children);
    atributs.add(_housing);
    atributs.add(_finance);
    atributs.add(_social);
    atributs.add(_health);
    atributs.add(_Class);

    //Aqu se crea la instacia, que tiene todos los atributos del modelo
    Instances dataTest = new Instances("TestCases", atributos, 1);
    dataTest.setClassIndex(8);

    Instance setPrueba = new Instance(9);

    int index = -1;
    for (int i = 0; i < 8; i++) {
        index = atributs.get(i).indexOfValue(testCases[i]);
        //System.out.println(i + " " + atributs.get(i)  + " " + index + " " + testCases[i]);
        setPrueba.setValue(atributs.get(i), index);
    }

    //Agregando el set que se desea evaluar.
    dataTest.add(setPrueba);

    //Realizando la Prediccin
    //La instancia es la 0 debido a que es la unica que se encuentra.
    double valorP = clasify.classifyInstance(dataTest.instance(0));
    //get the name of the class value
    String prediccion = dataTest.classAttribute().value((int) valorP);

    return prediccion;
}

From source file:com.gamerecommendation.Weatherconditions.Clasificacion.java

public String clasificar(String[] testCases) throws Exception {
    String ruta = "model.model";

    InputStream classModelStream;
    classModelStream = getClass().getResourceAsStream(ruta);
    Classifier clasify = (Classifier) SerializationHelper.read(classModelStream);
    FastVector condition = new FastVector();
    condition.addElement("Cloudy");
    condition.addElement("Clear");
    condition.addElement("Sunny");
    condition.addElement("Fair");
    condition.addElement("Partly_Cloudy");
    condition.addElement("Mostly_Cloudy");
    condition.addElement("Showers");
    condition.addElement("Haze");
    condition.addElement("Dust");
    condition.addElement("Other");
    Attribute _condition = new Attribute("contition", condition);

    FastVector temperature = new FastVector();
    temperature.addElement("Hot");
    temperature.addElement("Mild");
    temperature.addElement("Cool");
    Attribute _temperature = new Attribute("temperature", temperature);

    FastVector chill = new FastVector();
    chill.addElement("Regrettable");
    chill.addElement("Mint");
    Attribute _chill = new Attribute("chill", chill);

    FastVector direction = new FastVector();
    direction.addElement("Mint");
    direction.addElement("Fair");
    direction.addElement("Regular");
    Attribute _direction = new Attribute("direction", direction);

    FastVector speed = new FastVector();
    speed.addElement("Mint");
    speed.addElement("Fair");
    speed.addElement("Regular");
    Attribute _speed = new Attribute("speed", speed);

    FastVector humidity = new FastVector();
    humidity.addElement("High");
    humidity.addElement("Normal");
    humidity.addElement("Low");
    Attribute _humidity = new Attribute("humidity", humidity);

    FastVector visibility = new FastVector();
    visibility.addElement("Recommended");
    visibility.addElement("Not_Recommended");
    Attribute _visibility = new Attribute("visibility", visibility);

    FastVector preassure = new FastVector();
    preassure.addElement("Fair");
    preassure.addElement("Mint");
    Attribute _preassure = new Attribute("preassure", preassure);

    FastVector Class = new FastVector();
    Class.addElement("Recommended");
    Class.addElement("Not_Recommended");
    Attribute _Class = new Attribute("class", Class);

    FastVector atributos = new FastVector(9);
    atributos.addElement(_condition);/*from w w w . ja  v  a 2 s .  c o m*/
    atributos.addElement(_temperature);
    atributos.addElement(_chill);
    atributos.addElement(_direction);
    atributos.addElement(_speed);
    atributos.addElement(_humidity);
    atributos.addElement(_visibility);
    atributos.addElement(_preassure);
    atributos.addElement(_Class);

    ArrayList<Attribute> atributs = new ArrayList<>();
    atributs.add(_condition);
    atributs.add(_temperature);
    atributs.add(_chill);
    atributs.add(_direction);
    atributs.add(_speed);
    atributs.add(_humidity);
    atributs.add(_visibility);
    atributs.add(_preassure);
    atributs.add(_Class);

    //Aqu se crea la instacia, que tiene todos los atributos del modelo
    Instances dataTest = new Instances("TestCases", atributos, 1);
    dataTest.setClassIndex(8);

    Instance setPrueba = new Instance(9);

    int index = -1;
    for (int i = 0; i < 8; i++) {
        index = atributs.get(i).indexOfValue(testCases[i]);
        //System.out.println(i + " " + atributs.get(i)  + " " + index + " " + testCases[i]);
        setPrueba.setValue(atributs.get(i), index);
    }

    //Agregando el set que se desea evaluar.
    dataTest.add(setPrueba);

    //Realizando la Prediccin
    //La instancia es la 0 debido a que es la unica que se encuentra.
    double valorP = clasify.classifyInstance(dataTest.instance(0));
    //get the name of the class value
    String prediccion = dataTest.classAttribute().value((int) valorP);

    return prediccion;
}