Example usage for weka.core Instances setClassIndex

List of usage examples for weka.core Instances setClassIndex

Introduction

In this page you can find the example usage for weka.core Instances setClassIndex.

Prototype

public void setClassIndex(int classIndex) 

Source Link

Document

Sets the class index of the set.

Usage

From source file:GrowTree.java

public static void main(String[] args) throws Exception {
    runClassifier(new GrowTree(), args);
    DataSource source = new DataSource(
            "F:\\backup\\BTH\\#6DV2542 Machine Learning\\WEKA experiments\\UCI\\iris.arff");
    Instances data = source.getDataSet();
    if (data.classIndex() == -1)
        data.setClassIndex(data.numAttributes() - 1);
}

From source file:classifyfromimage1.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    selectWindow(this.name3);
    this.name3 = IJ.getImage().getTitle();
    this.name4 = this.name3.replaceFirst("[.][^.]+$", "");
    RoiManager rm = RoiManager.getInstance();
    IJ.run("Duplicate...", this.name4);
    IJ.run("Set Measurements...", "area perimeter fit shape limit scientific redirect=None decimal=5");
    selectWindow(this.name3);
    IJ.run("Subtract Background...", "rolling=1.5");
    IJ.run("Enhance Contrast...", "saturated=25 equalize");
    IJ.run("Subtract Background...", "rolling=1.5");
    IJ.run("Convolve...",
            "text1=[-1 -3 -4 -3 -1\n-3 0 6 0 -3\n-4 6 50 6 -4\n-3 0 6 0 -3\n-1 -3 -4 -3 -1\n] normalize");
    IJ.run("8-bit", "");
    IJ.run("Restore Selection", "");
    IJ.run("Make Binary", "");
    Prefs.blackBackground = false;//from   w  w  w.j  a  v a2 s . com
    IJ.run("Convert to Mask", "");
    IJ.run("Restore Selection", "");
    this.valor1 = this.interval3.getText();
    this.valor2 = this.interval4.getText();
    this.text = "size=" + this.valor1 + "-" + this.valor2
            + " pixel show=Outlines display include summarize add";
    IJ.saveAs("tif", this.name3 + "_processed");
    String dest_filename1, dest_filename2, full;
    selectWindow("Results");
    //dest_filename1 = this.name2 + "_complete.txt";
    dest_filename2 = this.name3 + "_complete.csv";
    //IJ.saveAs("Results", prova + File.separator + dest_filename1);
    IJ.run("Input/Output...", "jpeg=85 gif=-1 file=.csv copy_row save_column save_row");
    //IJ.saveAs("Results", dir + File.separator + dest_filename2);
    IJ.saveAs("Results", this.name3 + "_complete.csv");
    IJ.run("Restore Selection");
    IJ.run("Clear Results");

    try {
        CSVLoader loader = new CSVLoader();
        loader.setSource(new File(this.name3 + "_complete.csv"));
        Instances data = loader.getDataSet();
        System.out.println(data);

        // save ARFF
        String arffile = this.name3 + ".arff";
        System.out.println(arffile);
        ArffSaver saver = new ArffSaver();
        saver.setInstances(data);
        saver.setFile(new File(arffile));
        saver.writeBatch();
    } catch (IOException ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    Instances data;
    try {
        data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff")));
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels(txtlabel.getText());
        filter.setAttributeName(txtpath2.getText());
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print(newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);

        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(txtpath.getText());
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));
            //txtarea2.append(Utils.arrayToString(dist));
            classif.add(newData.classAttribute().value((int) pred));
        }

        classif.removeAll(Arrays.asList("", null));
        System.out.println(classif);
        String vecstring = "";

        for (Object s : classif) {
            vecstring += s + ",";
            System.out.println("Hola " + vecstring);
        }
        Map<String, Integer> seussCount = new HashMap<String, Integer>();
        for (String t : classif) {
            Integer i = seussCount.get(t);
            if (i == null) {
                i = 0;
            }
            seussCount.put(t, i + 1);
        }
        String s = vecstring;
        int counter = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '$') {
                counter++;
            }
        }
        System.out.println(seussCount);
        System.out.println("hola " + counter++);
        IJ.showMessage("Your file:" + this.name3 + "arff" + "\n is composed by" + seussCount);
        txtpath2.setText("Your file:" + this.name3 + "arff" + "\n is composed by" + seussCount);
        A_MachineLearning nf2 = new A_MachineLearning();
        A_MachineLearning.txtresult2.append(this.txtpath2.getText());
        nf2.setVisible(true);

    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    IJ.run("Close All", "");

    if (WindowManager.getFrame("Results") != null) {
        IJ.selectWindow("Results");
        IJ.run("Close");
    }
    if (WindowManager.getFrame("Summary") != null) {
        IJ.selectWindow("Summary");
        IJ.run("Close");
    }
    if (WindowManager.getFrame("Results") != null) {
        IJ.selectWindow("Results");
        IJ.run("Close");
    }
    if (WindowManager.getFrame("ROI Manager") != null) {
        IJ.selectWindow("ROI Manager");
        IJ.run("Close");
    }

    setVisible(false);
    dispose();// TODO add your handling code here:
    // TODO add your handling code here:
}

From source file:RunBestFirstSearch.java

License:Open Source License

public static void main(String[] arg) throws Exception {
    // Load data.
    ///*from  www.j ava2 s  . c o  m*/
    System.out.println("\nLoading sample file...");
    DataSource source = new DataSource(arg[0]);
    Instances data = source.getDataSet();

    if (data.classIndex() == -1)
        data.setClassIndex(data.numAttributes() - 1);

    int n = Integer.parseInt(arg[1]);

    System.out.println("Instance with " + n + " features!");
    System.out.println("\nRunning BFS algorithm with CFS cost function...");

    // Run feature selection algorithm BFS using CFS cost function.
    //
    runAttributeSelection(data, n);
}

From source file:MachinLearningInterface.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    Instances data;/*from   ww  w  .  j  a  va 2 s . c  om*/
    try {
        data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff")));
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels("rods,punctua,networks");
        filter.setAttributeName("target");
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print(newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);
        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        URL urlToModel = this.getClass().getResource("/" + "Final.model");
        InputStream stream = urlToModel.openStream();

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(stream);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));

        }
        int p = 0, n = 0, r = 0;

        //txtarea2.append(Utils.arrayToString(this.target));
        for (Object vec1 : vec) {
            if ("rods".equals(vec1.toString())) {
                r = r + 1;
            }
            if ("punctua".equals(vec1.toString())) {
                p = p + 1;
            }
            if ("networks".equals(vec1.toString())) {
                n = n + 1;
            }

            PrintWriter out = null;
            try {

                out = new PrintWriter(this.name3 + "_morphology.txt");
                out.println(vec);
                out.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //System.out.println(vec.get(i));
        }
        System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n);
        IJ.showMessage(
                "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: "
                        + p + ", rods: " + r + ", networks: " + n);

    } catch (IOException ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    IJ.showMessage("analysing complete ");
}

From source file:MachinLearningInterface.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    Instances data;//from   ww  w .java 2 s .  c  o  m
    try {
        data = new Instances(new BufferedReader(new FileReader(this.name3 + ".arff")));
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels(this.liststring);
        filter.setAttributeName("target");
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print(newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);

        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));
            //txtarea2.append(Utils.arrayToString(dist));

        }
        URL urlToModel = this.getClass().getResource("/" + "Final.model");
        InputStream stream = urlToModel.openStream();

        Classifier cls2 = (Classifier) weka.core.SerializationHelper.read(stream);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls2.classifyInstance(newData.instance(i));
            double[] dist = cls2.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));

        }
        int p = 0, n = 0, r = 0;

        //txtarea2.append(Utils.arrayToString(this.target));
        for (Object vec1 : vec) {
            if ("rods".equals(vec1.toString())) {
                r = r + 1;
            }
            if ("punctua".equals(vec1.toString())) {
                p = p + 1;
            }
            if ("networks".equals(vec1.toString())) {
                n = n + 1;
            }

            PrintWriter out = null;
            try {

                out = new PrintWriter(this.name3 + "_morphology.txt");
                out.println(vec);
                out.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //System.out.println(vec.get(i));
        }
        System.out.println("VECTOR-> punctua: " + p + ", rods: " + r + ", networks: " + n);
        IJ.showMessage(
                "Your file:" + this.name3 + "arff" + "\nhas been analysed, and it is composed by-> punctua: "
                        + p + ", rods: " + r + ", networks: " + n);
        //txtarea2.setText("Your file:" + this.name3 + ".arff"
        //+ "\nhas been analysed, and it is composed by-> punctua: " + p + ", rods: " + r + ", networks: " + n
        //+ "\n"
        //+ "\nAnalyse complete");
        //txtarea.setText("Analyse complete");

    } catch (IOException ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    IJ.showMessage("analysing complete "); // TODO add your handling code here:         // TODO add your handling code here:
}

From source file:MPCKMeans.java

License:Open Source License

public static void runFromCommandLine(String[] args) {
    MPCKMeans mpckmeans = new MPCKMeans();
    Instances data = null, clusterData = null;
    ArrayList labeledPairs = null;

    try {//from w  w w .  ja va 2s  . c  om
        String optionString = Utils.getOption('D', args);
        if (optionString.length() != 0) {
            FileReader reader = new FileReader(optionString);
            data = new Instances(reader);
            System.out.println("Reading dataset: " + data.relationName());
        }

        int classIndex = data.numAttributes() - 1;
        optionString = Utils.getOption('K', args);
        if (optionString.length() != 0) {
            classIndex = Integer.parseInt(optionString);
            if (classIndex >= 0) {
                data.setClassIndex(classIndex); // starts with 0
                // Remove the class labels before clustering
                clusterData = new Instances(data);
                mpckmeans.setNumClusters(clusterData.numClasses());
                clusterData.deleteClassAttribute();
                System.out.println("Setting classIndex: " + classIndex);
            } else {
                clusterData = new Instances(data);
            }
        } else {
            data.setClassIndex(classIndex); // starts with 0
            // Remove the class labels before clustering
            clusterData = new Instances(data);
            mpckmeans.setNumClusters(clusterData.numClasses());
            clusterData.deleteClassAttribute();
            System.out.println("Setting classIndex: " + classIndex);
        }

        optionString = Utils.getOption('C', args);
        if (optionString.length() != 0) {
            labeledPairs = mpckmeans.readConstraints(optionString);
            System.out.println("Reading constraints from: " + optionString);
        } else {
            labeledPairs = new ArrayList(0);
        }

        mpckmeans.setTotalTrainWithLabels(data);
        mpckmeans.setOptions(args);
        System.out.println();
        mpckmeans.buildClusterer(labeledPairs, clusterData, data, mpckmeans.getNumClusters(),
                data.numInstances());
        mpckmeans.printClusterAssignments();

        if (mpckmeans.m_TotalTrainWithLabels.classIndex() > -1) {
            double nCorrect = 0;
            for (int i = 0; i < mpckmeans.m_TotalTrainWithLabels.numInstances(); i++) {
                for (int j = i + 1; j < mpckmeans.m_TotalTrainWithLabels.numInstances(); j++) {
                    int cluster_i = mpckmeans.m_ClusterAssignments[i];
                    int cluster_j = mpckmeans.m_ClusterAssignments[j];
                    double class_i = (mpckmeans.m_TotalTrainWithLabels.instance(i)).classValue();
                    double class_j = (mpckmeans.m_TotalTrainWithLabels.instance(j)).classValue();
                    //         System.out.println(cluster_i + "," + cluster_j + ":" + class_i + "," + class_j);
                    if (cluster_i == cluster_j && class_i == class_j
                            || cluster_i != cluster_j && class_i != class_j) {
                        nCorrect++;
                        //        System.out.println("nCorrect:" + nCorrect);
                    }
                }
            }
            int numInstances = mpckmeans.m_TotalTrainWithLabels.numInstances();
            double RandIndex = 100 * nCorrect / (numInstances * (numInstances - 1) / 2);
            System.err.println("Acc\t" + RandIndex);
        }

        //      if (mpckmeans.getTotalTrainWithLabels().classIndex() >= 0) {
        //    SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
        //                             mpckmeans.m_TotalTrainWithLabels.numClasses(),
        //                             mpckmeans.m_TotalTrainWithLabels.numClasses());
        //    eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
        //    eval.mutualInformation();
        //    eval.pairwiseFMeasure();
        //      }
    } catch (Exception e) {
        System.out.println("Option not specified");
        e.printStackTrace();
    }
}

From source file:MPCKMeans.java

License:Open Source License

public static void testCase() {
    try {//from   www .  ja v  a 2 s  .c  o  m
        String dataset = new String("lowd");
        //String dataset = new String("highd");
        if (dataset.equals("lowd")) {
            //////// Low-D data

            //   String datafile = "/u/ml/data/bio/arffFromPhylo/ecoli_K12-100.arff";
            //   String datafile = "/u/sugato/weka/data/digits-0.1-389.arff";
            String datafile = "/u/sugato/weka/data/iris.arff";
            int numPairs = 200, num = 0;

            // set up the data
            FileReader reader = new FileReader(datafile);
            Instances data = new Instances(reader);

            // Make the last attribute be the class 
            int classIndex = data.numAttributes() - 1;
            data.setClassIndex(classIndex); // starts with 0
            System.out.println("ClassIndex is: " + classIndex);

            // Remove the class labels before clustering
            Instances clusterData = new Instances(data);
            clusterData.deleteClassAttribute();

            // create the pairs
            ArrayList labeledPair = InstancePair.getPairs(data, numPairs);

            System.out.println("Finished initializing constraint matrix");

            MPCKMeans mpckmeans = new MPCKMeans();
            mpckmeans.setUseMultipleMetrics(false);
            System.out.println("\nClustering the data using MPCKmeans...\n");

            WeightedEuclidean metric = new WeightedEuclidean();
            WEuclideanLearner metricLearner = new WEuclideanLearner();

            //     LearnableMetric metric = new WeightedDotP();
            //     MPCKMeansMetricLearner metricLearner = new DotPGDLearner();

            //     KL metric = new KL();
            //     KLGDLearner metricLearner = new KLGDLearner();
            //   ((KL)metric).setUseIDivergence(true);

            //   BarHillelMetric metric = new BarHillelMetric();
            //   BarHillelMetricMatlab metric = new BarHillelMetricMatlab();
            //     XingMetric metric = new XingMetric();
            //   WeightedMahalanobis metric = new WeightedMahalanobis(); 

            mpckmeans.setMetric(metric);
            mpckmeans.setMetricLearner(metricLearner);
            mpckmeans.setVerbose(false);
            mpckmeans.setRegularize(false);
            mpckmeans.setTrainable(new SelectedTag(TRAINING_INTERNAL, TAGS_TRAINING));
            mpckmeans.setSeedable(true);
            mpckmeans.buildClusterer(labeledPair, clusterData, data, data.numClasses(), data.numInstances());
            mpckmeans.getIndexClusters();
            mpckmeans.printIndexClusters();

            SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
                    mpckmeans.m_TotalTrainWithLabels.numClasses(),
                    mpckmeans.m_TotalTrainWithLabels.numClasses());
            eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
            System.out.println("MI=" + eval.mutualInformation());
            System.out.print("FM=" + eval.pairwiseFMeasure());
            System.out.print("\tP=" + eval.pairwisePrecision());
            System.out.print("\tR=" + eval.pairwiseRecall());
        } else if (dataset.equals("highd")) {
            //////// Newsgroup data
            String datafile = "/u/ml/users/sugato/groupcode/weka335/data/arffFromCCS/sanitized/different-1000_sanitized.arff";
            //String datafile = "/u/ml/users/sugato/groupcode/weka335/data/20newsgroups/small-newsgroup_fromCCS.arff";
            //String datafile = "/u/ml/users/sugato/groupcode/weka335/data/20newsgroups/same-100_fromCCS.arff";

            // set up the data
            FileReader reader = new FileReader(datafile);
            Instances data = new Instances(reader);

            // Make the last attribute be the class 
            int classIndex = data.numAttributes() - 1;
            data.setClassIndex(classIndex); // starts with 0
            System.out.println("ClassIndex is: " + classIndex);

            // Remove the class labels before clustering
            Instances clusterData = new Instances(data);
            clusterData.deleteClassAttribute();

            // create the pairs
            int numPairs = 0, num = 0;
            ArrayList labeledPair = new ArrayList(numPairs);
            Random rand = new Random(42);
            System.out.println("Initializing constraint matrix:");
            while (num < numPairs) {
                int i = (int) (data.numInstances() * rand.nextFloat());
                int j = (int) (data.numInstances() * rand.nextFloat());
                int first = (i < j) ? i : j;
                int second = (i >= j) ? i : j;
                int linkType = (data.instance(first).classValue() == data.instance(second).classValue())
                        ? InstancePair.MUST_LINK
                        : InstancePair.CANNOT_LINK;
                InstancePair pair = new InstancePair(first, second, linkType);
                if (first != second && !labeledPair.contains(pair)) {
                    labeledPair.add(pair);
                    //System.out.println(num + "th entry is: " + pair);
                    num++;
                }
            }
            System.out.println("Finished initializing constraint matrix");

            MPCKMeans mpckmeans = new MPCKMeans();
            mpckmeans.setUseMultipleMetrics(false);
            System.out.println("\nClustering the highd data using MPCKmeans...\n");

            LearnableMetric metric = new WeightedDotP();
            MPCKMeansMetricLearner metricLearner = new DotPGDLearner();

            //     KL metric = new KL();
            //     KLGDLearner metricLearner = new KLGDLearner();

            mpckmeans.setMetric(metric);
            mpckmeans.setMetricLearner(metricLearner);
            mpckmeans.setVerbose(false);
            mpckmeans.setRegularize(true);
            mpckmeans.setTrainable(new SelectedTag(TRAINING_INTERNAL, TAGS_TRAINING));
            mpckmeans.setSeedable(true);
            mpckmeans.buildClusterer(labeledPair, clusterData, data, data.numClasses(), data.numInstances());
            mpckmeans.getIndexClusters();

            SemiSupClustererEvaluation eval = new SemiSupClustererEvaluation(mpckmeans.m_TotalTrainWithLabels,
                    mpckmeans.m_TotalTrainWithLabels.numClasses(),
                    mpckmeans.m_TotalTrainWithLabels.numClasses());

            mpckmeans.getMetric().resetMetric(); // Vital: to reset m_attrWeights to 1 for proper normalization
            eval.evaluateModel(mpckmeans, mpckmeans.m_TotalTrainWithLabels, mpckmeans.m_Instances);
            System.out.println("MI=" + eval.mutualInformation());
            System.out.print("FM=" + eval.pairwiseFMeasure());
            System.out.print("\tP=" + eval.pairwisePrecision());
            System.out.print("\tR=" + eval.pairwiseRecall());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:A_AdvanceMachineLearning.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
    UIManager.put("OptionPane.yesButtonText", "Confirm");
    UIManager.put("OptionPane.noButtonText", "Cancel");
    int dialogButton = JOptionPane.YES_NO_OPTION;
    int dialogResult = JOptionPane.showConfirmDialog(this, "The labels must be the same used in the weka model",
            "Advance Machine learning", dialogButton, JOptionPane.WARNING_MESSAGE);
    if (dialogResult == 0) {
        this.list.clear();
        //txtcodigo1.setText("hola");
        this.valor = txtcodigo1.getText();
        this.valor1 = txtcodigo2.getText();
        this.valor2 = txtcodigo3.getText();
        this.valor3 = txtcodigo4.getText();
        this.valor4 = txtcodigo5.getText();
        this.valor5 = txtcodigo6.getText();
        //IJ.showMessage("your label 1 is = "+valor+", "+valor1+", "+valor2+", "+valor3+", "+valor4);
        // Array list
        this.list.add(this.valor);
        this.list.add(this.valor1);
        this.list.add(this.valor2);
        this.list.add(this.valor3);
        this.list.add(this.valor4);
        this.list.add(this.valor5);
        this.list.removeAll(Arrays.asList("", null));
        System.out.println(this.list);
        this.liststring = "";

        for (String s : this.list) {
            this.liststring += s + ",";
        }/* www.java  2  s  . c  om*/
        txtlabel.setText(this.liststring);

        System.out.println(this.liststring);
        txtarea.setText("Your labels are = " + this.list + "\nThe labels had been saved");
        //txtarea.setText("The labels had been saved");

        System.out.println(label);

    } else {
        System.out.println("No Option");

    }
    Instances data;
    try {
        System.out.println(this.file2 + "arff");
        FileReader reader = new FileReader(this.file2 + ".arff");
        BufferedReader br = new BufferedReader(reader);

        data = new Instances(br);
        System.out.println(data);
        Instances newData = null;
        Add filter;
        newData = new Instances(data);
        filter = new Add();
        filter.setAttributeIndex("last");
        filter.setNominalLabels(this.liststring);
        filter.setAttributeName(txtcodigo7.getText());
        filter.setInputFormat(newData);
        newData = Filter.useFilter(newData, filter);
        System.out.print("hola" + newData);
        Vector vec = new Vector();
        newData.setClassIndex(newData.numAttributes() - 1);
        if (!newData.equalHeaders(newData)) {
            throw new IllegalArgumentException("Train and test are not compatible!");
        }

        Classifier cls = (Classifier) weka.core.SerializationHelper.read(this.model);
        System.out.println("PROVANT MODEL.classifyInstance");
        for (int i = 0; i < newData.numInstances(); i++) {
            double pred = cls.classifyInstance(newData.instance(i));
            double[] dist = cls.distributionForInstance(newData.instance(i));
            System.out.print((i + 1) + " - ");
            System.out.print(newData.classAttribute().value((int) pred) + " - ");
            //txtarea2.setText(Utils.arrayToString(dist));

            System.out.println(Utils.arrayToString(dist));

            vec.add(newData.classAttribute().value((int) pred));

            classif.add(newData.classAttribute().value((int) pred));
        }

        classif.removeAll(Arrays.asList("", null));
        System.out.println(classif);
        String vecstring = "";

        for (Object s : classif) {
            vecstring += s + ",";

        }
        Map<String, Integer> seussCount = new HashMap<String, Integer>();
        for (String t : classif) {
            Integer i = seussCount.get(t);
            if (i == null) {
                i = 0;
            }
            seussCount.put(t, i + 1);
        }
        String s = vecstring;
        String in = vecstring;
        int i = 0;
        Pattern p = Pattern.compile(this.valor1);
        Matcher m = p.matcher(in);
        while (m.find()) {
            i++;
        }

        System.out.println("hola " + i); // Prints 2

        System.out.println(seussCount);
        txtarea2.append("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
        IJ.showMessage("Your file:" + this.file2 + "arff" + "\n is composed by" + seussCount);
    } catch (Exception ex) {
        Logger.getLogger(MachinLearningInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    //IJ.showMessage("analysing complete ");// TODO add your handling code here:
}

From source file:MeansClassifier.java

public static void main(String[] args) throws Exception {
    Instances read = null;
    String str = "\\\\ueahome4\\stusci4\\ysj13kxu\\data\\Documents\\Sheet2_Train.arff";
    FileReader r;//  ww  w. ja  v a 2s.  c  om
    try {
        r = new FileReader(str);
        read = new Instances(r);
        read.setClassIndex(read.numAttributes() - 1);
    } catch (Exception e) {
        System.out.println(" Exception caught =" + e);
    }
    MeansClassifier m = new MeansClassifier();
    m.buildClassifier(read);
}

From source file:ab.demo.AIAssignment2.java

License:Open Source License

public GameState solve() {

    // capture Image
    BufferedImage screenshot = ActionRobot.doScreenShot();

    // process image
    Vision vision = new Vision(screenshot);

    // find the slingshot
    Rectangle sling = vision.findSlingshotMBR();

    // confirm the slingshot
    while (sling == null && aRobot.getState() == GameState.PLAYING) {
        System.out.println("No slingshot detected. Please remove pop up or zoom out");
        ActionRobot.fullyZoomOut();//from  w  w  w  . j  av  a  2s  .c o m
        screenshot = ActionRobot.doScreenShot();
        vision = new Vision(screenshot);
        sling = vision.findSlingshotMBR();
    }

    // get all the pigs
    List<ABObject> pigs = vision.findPigsMBR();
    List<ABObject> blocks = vision.findBlocksMBR();

    GameState state = aRobot.getState();

    // if there is a sling, then play, otherwise just skip.
    if (sling != null) {

        if (!pigs.isEmpty()) { //if there are pigs in the level

            Point releasePoint = null;
            Shot shot = new Shot();
            int dx, dy;
            {
                //random pick up a pig
                ABObject pig = pigs.get(randomGenerator.nextInt(pigs.size()));
                Point _tpt = pig.getCenter();

                // estimate the trajectory
                ArrayList<Point> pts = tp.estimateLaunchPoint(sling, _tpt);

                //define all of the wood, ice and stone in the stage
                ArrayList<ABObject> wood = new ArrayList<ABObject>();
                ArrayList<ABObject> stone = new ArrayList<ABObject>();
                ArrayList<ABObject> ice = new ArrayList<ABObject>();
                ArrayList<ABObject> tnt = new ArrayList<ABObject>();

                //initialise counters to store how many times the trajectory intersects blocks of these types
                int woodCount = 0;
                int stoneCount = 0;
                int iceCount = 0;
                int pigsCount = 0;
                int tntCount = 0;

                //populate the wood, stone and ice ArrayLists with the correct materials
                for (int i = 0; i < blocks.size(); i++) {
                    if (blocks.get(i).type == ABType.Wood)
                        wood.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Stone)
                        stone.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.Ice)
                        ice.add(blocks.get(i));
                    if (blocks.get(i).type == ABType.TNT)
                        tnt.add(blocks.get(i));
                }

                //check whether the trajectory intersects any wood blocks
                for (int i = 0; i < wood.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (wood.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some wood");
                            woodCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for wood on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any ice blocks
                for (int i = 0; i < ice.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (ice.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some ice");
                            iceCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for ice on the trajectory (escape for loop)
                    }
                }

                //check whether the trajectory intersects any stone blocks            
                for (int i = 0; i < stone.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (stone.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some stone");
                            stoneCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for stone on the trajectory (escape for loop)
                    }
                }

                //how many pigs the trajectory intersects (this should always be at least 1)         
                for (int i = 0; i < pigs.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (pigs.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects a pig");
                            pigsCount++;
                        }
                    }
                }

                //how many tnt blocks the trajectory intersects            
                for (int i = 0; i < tnt.size(); i++) {
                    for (int j = 0; j < pts.size(); j++) {
                        if (tnt.get(i).contains(pts.get(j))) {
                            System.out.println("Trajectory intersects some tnt");
                            tntCount++;
                        }
                        if (pig.contains(pts.get(j))) //if we find the pig on this point
                            j = pts.size() - 1; //stop looking for tnt on the trajectory
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.append(pigsCount + "," + woodCount + "," + iceCount + "," + stoneCount + "," + tntCount
                        + ",?");
                String dataEntry = sb.toString();
                try (PrintWriter out = new PrintWriter(
                        new BufferedWriter(new FileWriter("dataset/birds.level.arff", true)))) {
                    out.println(dataEntry);
                } catch (IOException e) {
                    System.out.println("Error - dataset/birds.level.arff file not found or in use!");
                }

                //indicator of if the agent should continue this shot or not (used in the bayes classifier)
                ArrayList<Boolean> takeShot = new ArrayList<Boolean>();

                try {
                    DataSource source = new DataSource("dataset/birds.data.arff"); //initialise the learning set for the agent
                    Instances data = source.getDataSet();

                    // setting class attribute if the data format does not provide this information
                    // For example, the XRFF format saves the class attribute information as well
                    if (data.classIndex() == -1)
                        data.setClassIndex(data.numAttributes() - 1);

                    DataSource thisLevel = new DataSource("dataset/birds.level.arff"); //initialise the data retrieved from the current level for the agent
                    Instances thisLevelData = thisLevel.getDataSet();
                    if (thisLevelData.classIndex() == -1)
                        thisLevelData.setClassIndex(data.numAttributes() - 1);

                    //build a new NaiveBayes classifier
                    NaiveBayes bayes = new NaiveBayes();
                    bayes.buildClassifier(data);

                    for (int i = 0; i < thisLevelData.numInstances(); i++) { //for all instances in the current level
                        double label = bayes.classifyInstance(thisLevelData.instance(i)); //generate an outcome/classify an instance in the current level
                        thisLevelData.instance(i).setClassValue(label); //store this outcome
                        System.out.println(thisLevelData.instance(i).stringValue(5)); //print it
                        if (thisLevelData.instance(i).stringValue(5) != "?") { //if there is a decisive choice as to whether a shot should be taken
                            data.add(thisLevelData.instance(i)); //store it
                            if (thisLevelData.instance(i).stringValue(5) == "yes") {//if the classifier classifies a good shot, store it
                                takeShot.add(true);
                            } else { //if no, store this too
                                takeShot.add(false);
                            }
                        }
                    }

                    //add all non ? entries to the learning set
                    BufferedWriter writer = new BufferedWriter(new FileWriter("dataset/birds.data.arff"));
                    writer.write(data.toString());
                    writer.flush();
                    writer.close();

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("Exception caught - file handle error");
                }

                //TODO: roll a random number to determine whether we take a shot or not.
                //populated using the bayesian classification above.
                //if we roll true, continue with the random pig shot as usual.
                //if not, take a new random pig and try again.
                //TODO: implement a failsafe so the agent does not get stuck randomly choosing pigs which the bayesian classification does not allow.
                Random rng = new Random(takeShot.size());
                if (takeShot.get(rng.nextInt()))
                    System.out.println("Taking this shot.");
                else {
                    System.out.println("Not taking this shot. Finding another random pig.");
                    return state;
                }

                // if the target is very close to before, randomly choose a
                // point near it
                if (prevTarget != null && distance(prevTarget, _tpt) < 10) {
                    double _angle = randomGenerator.nextDouble() * Math.PI * 2;
                    _tpt.x = _tpt.x + (int) (Math.cos(_angle) * 10);
                    _tpt.y = _tpt.y + (int) (Math.sin(_angle) * 10);
                    System.out.println("Randomly changing to " + _tpt);
                }

                prevTarget = new Point(_tpt.x, _tpt.y);

                // do a high shot when entering a level to find an accurate velocity
                if (firstShot && pts.size() > 1) {
                    releasePoint = pts.get(1);
                } else if (pts.size() == 1)
                    releasePoint = pts.get(0);
                else if (pts.size() == 2) {
                    // randomly choose between the trajectories, with a 1 in
                    // 6 chance of choosing the high one
                    if (randomGenerator.nextInt(6) == 0)
                        releasePoint = pts.get(1);
                    else
                        releasePoint = pts.get(0);
                } else if (pts.isEmpty()) {
                    System.out.println("No release point found for the target");
                    System.out.println("Try a shot with 45 degree");
                    releasePoint = tp.findReleasePoint(sling, Math.PI / 4);
                }

                // Get the reference point
                Point refPoint = tp.getReferencePoint(sling);

                //Calculate the tapping time according the bird type 
                if (releasePoint != null) {
                    double releaseAngle = tp.getReleaseAngle(sling, releasePoint);
                    System.out.println("Release Point: " + releasePoint);
                    System.out.println("Release Angle: " + Math.toDegrees(releaseAngle));
                    int tapInterval = 0;
                    switch (aRobot.getBirdTypeOnSling()) {

                    case RedBird:
                        tapInterval = 0;
                        break; // start of trajectory
                    case YellowBird:
                        tapInterval = 65 + randomGenerator.nextInt(25);
                        break; // 65-90% of the way
                    case WhiteBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlackBird:
                        tapInterval = 70 + randomGenerator.nextInt(20);
                        break; // 70-90% of the way
                    case BlueBird:
                        tapInterval = 65 + randomGenerator.nextInt(20);
                        break; // 65-85% of the way
                    default:
                        tapInterval = 60;
                    }

                    int tapTime = tp.getTapTime(sling, releasePoint, _tpt, tapInterval);
                    dx = (int) releasePoint.getX() - refPoint.x;
                    dy = (int) releasePoint.getY() - refPoint.y;
                    shot = new Shot(refPoint.x, refPoint.y, dx, dy, 0, tapTime);
                } else {
                    System.err.println("No Release Point Found");
                    return state;
                }
            }

            // check whether the slingshot is changed. the change of the slingshot indicates a change in the scale.
            {
                ActionRobot.fullyZoomOut();
                screenshot = ActionRobot.doScreenShot();
                vision = new Vision(screenshot);
                Rectangle _sling = vision.findSlingshotMBR();
                if (_sling != null) {
                    double scale_diff = Math.pow((sling.width - _sling.width), 2)
                            + Math.pow((sling.height - _sling.height), 2);
                    if (scale_diff < 25) {
                        if (dx < 0) {
                            aRobot.cshoot(shot);
                            state = aRobot.getState();
                            if (state == GameState.PLAYING) {
                                screenshot = ActionRobot.doScreenShot();
                                vision = new Vision(screenshot);
                                List<Point> traj = vision.findTrajPoints();
                                tp.adjustTrajectory(traj, sling, releasePoint);
                                firstShot = false;
                            }
                        }
                    } else
                        System.out.println(
                                "Scale is changed, can not execute the shot, will re-segement the image");
                } else
                    System.out
                            .println("no sling detected, can not execute the shot, will re-segement the image");
            }

        }

    }
    return state;
}