Example usage for weka.core Instances numAttributes

List of usage examples for weka.core Instances numAttributes

Introduction

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

Prototype


publicint numAttributes() 

Source Link

Document

Returns the number of attributes.

Usage

From source file:REPRandomTree.java

License:Open Source License

/**
 * Builds classifier.//  w ww .j  a va 2s .  c  o  m
 * 
 * @param data the data to train with
 * @throws Exception if building fails
 */
public void buildClassifier(Instances data) throws Exception {

    // can classifier handle the data?
    getCapabilities().testWithFail(data);

    // remove instances with missing class
    data = new Instances(data);
    data.deleteWithMissingClass();

    Random random = new Random(m_Seed);

    m_zeroR = null;
    if (data.numAttributes() == 1) {
        m_zeroR = new ZeroR();
        m_zeroR.buildClassifier(data);
        return;
    }

    // Randomize and stratify
    data.randomize(random);
    if (data.classAttribute().isNominal()) {
        data.stratify(m_NumFolds);
    }

    // Split data into training and pruning set
    Instances train = null;
    Instances prune = null;
    if (!m_NoPruning) {
        train = data.trainCV(m_NumFolds, 0, random);
        prune = data.testCV(m_NumFolds, 0);
    } else {
        train = data;
    }

    // Create array of sorted indices and weights
    int[][][] sortedIndices = new int[1][train.numAttributes()][0];
    double[][][] weights = new double[1][train.numAttributes()][0];
    double[] vals = new double[train.numInstances()];
    for (int j = 0; j < train.numAttributes(); j++) {
        if (j != train.classIndex()) {
            weights[0][j] = new double[train.numInstances()];
            if (train.attribute(j).isNominal()) {

                // Handling nominal attributes. Putting indices of
                // instances with missing values at the end.
                sortedIndices[0][j] = new int[train.numInstances()];
                int count = 0;
                for (int i = 0; i < train.numInstances(); i++) {
                    Instance inst = train.instance(i);
                    if (!inst.isMissing(j)) {
                        sortedIndices[0][j][count] = i;
                        weights[0][j][count] = inst.weight();
                        count++;
                    }
                }
                for (int i = 0; i < train.numInstances(); i++) {
                    Instance inst = train.instance(i);
                    if (inst.isMissing(j)) {
                        sortedIndices[0][j][count] = i;
                        weights[0][j][count] = inst.weight();
                        count++;
                    }
                }
            } else {

                // Sorted indices are computed for numeric attributes
                for (int i = 0; i < train.numInstances(); i++) {
                    Instance inst = train.instance(i);
                    vals[i] = inst.value(j);
                }
                sortedIndices[0][j] = Utils.sort(vals);
                for (int i = 0; i < train.numInstances(); i++) {
                    weights[0][j][i] = train.instance(sortedIndices[0][j][i]).weight();
                }
            }
        }
    }

    // Compute initial class counts
    double[] classProbs = new double[train.numClasses()];
    double totalWeight = 0, totalSumSquared = 0;
    for (int i = 0; i < train.numInstances(); i++) {
        Instance inst = train.instance(i);
        if (data.classAttribute().isNominal()) {
            classProbs[(int) inst.classValue()] += inst.weight();
            totalWeight += inst.weight();
        } else {
            classProbs[0] += inst.classValue() * inst.weight();
            totalSumSquared += inst.classValue() * inst.classValue() * inst.weight();
            totalWeight += inst.weight();
        }
    }
    m_Tree = new Tree();
    double trainVariance = 0;
    if (data.classAttribute().isNumeric()) {
        trainVariance = m_Tree.singleVariance(classProbs[0], totalSumSquared, totalWeight) / totalWeight;
        classProbs[0] /= totalWeight;
    }

    // Build tree
    m_Tree.buildTree(sortedIndices, weights, train, totalWeight, classProbs, new Instances(train, 0), m_MinNum,
            m_MinVarianceProp * trainVariance, 0, m_MaxDepth, m_FeatureFrac, random);

    // Insert pruning data and perform reduced error pruning
    if (!m_NoPruning) {
        m_Tree.insertHoldOutSet(prune);
        m_Tree.reducedErrorPrune();
        m_Tree.backfitHoldOutSet();
    }
}

From source file:LabeledItemSet.java

License:Open Source License

/**
 * Splits the class attribute away. Depending on the invert flag, the instances without class attribute or only the class attribute of all instances is returned
 * @param instances the instances//from   ww w .j a  v  a  2  s  .c  o m
 * @param invert flag; if true only the class attribute remains, otherweise the class attribute is the only attribute that is deleted.
 * @throws Exception exception if instances cannot be splitted
 * @return Instances without the class attribute or instances with only the class attribute
 */
public static Instances divide(Instances instances, boolean invert) throws Exception {

    Instances newInstances = new Instances(instances);
    if (instances.classIndex() < 0)
        throw new Exception("For class association rule mining a class attribute has to be specified.");
    if (invert) {
        for (int i = 0; i < newInstances.numAttributes(); i++) {
            if (i != newInstances.classIndex()) {
                newInstances.deleteAttributeAt(i);
                i--;
            }
        }
        return newInstances;
    } else {
        newInstances.setClassIndex(-1);
        newInstances.deleteAttributeAt(instances.classIndex());
        return newInstances;
    }
}

From source file:LabeledItemSet.java

License:Open Source License

/**
 * Converts the header info of the given set of instances into a set
 * of item sets (singletons). The ordering of values in the header file
 * determines the lexicographic order. Each item set knows its class label.
 * @return a set of item sets, each containing a single item
 * @param instancesNoClass instances without the class attribute
 * @param classes the values of the class attribute sorted according to instances
 * @exception Exception if singletons can't be generated successfully
 *///ww  w . j a  v a 2 s  .  c o  m
public static FastVector singletons(Instances instancesNoClass, Instances classes) throws Exception {

    FastVector cSet, setOfItemSets = new FastVector();
    LabeledItemSet current;

    //make singletons
    for (int i = 0; i < instancesNoClass.numAttributes(); i++) {
        if (instancesNoClass.attribute(i).isNumeric())
            throw new Exception("Can't handle numeric attributes!");
        for (int j = 0; j < instancesNoClass.attribute(i).numValues(); j++) {
            for (int k = 0; k < (classes.attribute(0)).numValues(); k++) {
                current = new LabeledItemSet(instancesNoClass.numInstances(), k);
                current.m_items = new int[instancesNoClass.numAttributes()];
                for (int l = 0; l < instancesNoClass.numAttributes(); l++)
                    current.m_items[l] = -1;
                current.m_items[i] = j;
                setOfItemSets.addElement(current);
            }
        }
    }
    return setOfItemSets;
}

From source file:dialog1.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    try {/* w w  w. j a v a  2 s  .  c  o m*/
        CSVLoader loader = new CSVLoader();
        loader.setSource(new File(txtfilename.getText() + "_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("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();*/
        InputStream stream = this.getClass().getResourceAsStream("/" + "Final.model");
        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));
            //txtarea2.append(Utils.arrayToString(newData.classAttribute().value((int) pred)));
            //this.target2.add((i + 1) + " -);
            //this.target.add(newData.classAttribute().value((int) pred));
            //for (String s : this.list) {
            //this.target2 += s + ",";

        }
        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.run("Clear Results");
    IJ.run("Clear Results");
    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");
    }
    IJ.run("Close All", "roiManager");
    IJ.run("Close All", "");
    setVisible(false);
    dispose();// TODO add your handling code here:

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

From source file:CJWeka.java

License:Open Source License

/**
 * This function sets what the m_numeric flag to represent the passed class
 * it also performs the normalization of the attributes if applicable
 * and sets up the info to normalize the class. (note that regardless of
 * the options it will fill an array with the range and base, set to
 * normalize all attributes and the class to be between -1 and 1)
 * @param inst the instances./*w  w  w. java 2 s . c  o  m*/
 * @return The modified instances. This needs to be done. If the attributes
 * are normalized then deep copies will be made of all the instances which
 * will need to be passed back out.
 */
private Instances setClassType(Instances inst) throws Exception {
    if (inst != null) {
        // x bounds
        double min = Double.POSITIVE_INFINITY;
        double max = Double.NEGATIVE_INFINITY;
        double value;
        m_attributeRanges = new double[inst.numAttributes()];
        m_attributeBases = new double[inst.numAttributes()];
        for (int noa = 0; noa < inst.numAttributes(); noa++) {
            min = Double.POSITIVE_INFINITY;
            max = Double.NEGATIVE_INFINITY;
            for (int i = 0; i < inst.numInstances(); i++) {
                if (!inst.instance(i).isMissing(noa)) {
                    value = inst.instance(i).value(noa);
                    if (value < min) {
                        min = value;
                    }
                    if (value > max) {
                        max = value;
                    }
                }
            }

            m_attributeRanges[noa] = (max - min) / 2;
            m_attributeBases[noa] = (max + min) / 2;
            if (noa != inst.classIndex() && m_normalizeAttributes) {
                for (int i = 0; i < inst.numInstances(); i++) {
                    if (m_attributeRanges[noa] != 0) {
                        inst.instance(i).setValue(noa,
                                (inst.instance(i).value(noa) - m_attributeBases[noa]) / m_attributeRanges[noa]);
                    } else {
                        inst.instance(i).setValue(noa, inst.instance(i).value(noa) - m_attributeBases[noa]);
                    }
                }
            }
        }
        if (inst.classAttribute().isNumeric()) {
            m_numeric = true;
        } else {
            m_numeric = false;
        }
    }
    return inst;
}

From source file:CJWeka.java

License:Open Source License

public void buildClassifier(Instances i) throws Exception {

    // can classifier handle the data?
    getCapabilities().testWithFail(i);/* ww  w  .j  a  va2s . c o  m*/

    // remove instances with missing class
    i = new Instances(i);
    i.deleteWithMissingClass();

    // only class? -> build ZeroR model
    if (i.numAttributes() == 1) {
        System.err.println(
                "Cannot build model (only class attribute present in data!), " + "using ZeroR model instead!");
        m_ZeroR = new weka.classifiers.rules.ZeroR();
        m_ZeroR.buildClassifier(i);
        return;
    } else {
        m_ZeroR = null;
    }

    m_instances = null;
    m_currentInstance = null;

    m_outputs = new NeuralEnd[0];
    m_inputs = new NeuralEnd[0];
    m_numAttributes = 0;
    m_numClasses = 0;
    m_neuralNodes = new NeuralConnection[0];

    m_nextId = 0;
    m_instances = new Instances(i);
    m_random = new Random(m_randomSeed);

    if (m_useNomToBin) {
        m_nominalToBinaryFilter = new NominalToBinary();
        m_nominalToBinaryFilter.setInputFormat(m_instances);
        m_instances = Filter.useFilter(m_instances, m_nominalToBinaryFilter);
    }
    m_numAttributes = m_instances.numAttributes() - 1;
    m_numClasses = m_instances.numClasses();

    setClassType(m_instances);

    setupInputs();
    setupOutputs();
    setupHiddenLayer();

    //For silly situations in which the network gets accepted before training
    //commenses
    if (m_numeric) {
        setEndsToLinear();
    }

    //connections done.
    double right = 0;
    double tempRate;
    double totalWeight = 0;

    m_hiddenValues = new double[m_hiddenLayers];
    resetNetwork();
    saveValues();
    for (int noa = 1; noa < m_numEpochs + 1; noa++) {
        //            System.out.println(noa);
        resetNetwork();
        totalWeight = 0;
        right = 0;
        for (int nob = 0; nob < m_instances.numInstances(); nob++) {
            m_currentInstance = m_instances.instance(nob);
            if (!m_currentInstance.classIsMissing()) {
                totalWeight += m_currentInstance.weight();

                //this is where the network updating (and training occurs, for the
                //training set
                resetNetwork();
                calculateOutputs();
                tempRate = m_learningRate * m_currentInstance.weight();
                if (m_decay) {
                    tempRate /= noa;
                }

                right += (calculateErrors() / m_instances.numClasses()) * m_currentInstance.weight();
                updateNetworkWeights(tempRate, m_momentum);
                saveValues();
            }
        }
        right /= totalWeight;
        if (Double.isInfinite(right) || Double.isNaN(right)) {
            m_instances = null;
            throw new Exception("Network cannot train. Try restarting with a" + " smaller learning rate.");
        }
        //            System.out.println(noa+ ": " +right);
    }
    resetNetwork();
    if (m_resetAfterTraining) {
        // in that point it saves Double.NaN
        saveValues();
    }

}

From source file:MainFrame.java

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
    double[][] food_sources = new double[0][0];
    Classifier classifier;//from  www . j a v a  2  s . c o  m
    Evaluation eval;
    int N;
    PreparingSteps pr = new PreparingSteps();
    int iterationnumber = Integer.parseInt(iterationnumber_cb.getSelectedItem().toString());
    double modificationRate = Double.parseDouble(modificationrate_cb.getSelectedItem().toString());
    int foldnumber = Integer.parseInt(crossvalfold_cb.getSelectedItem().toString());
    //statuslabel.setText("Calculating...");
    try {
        N = pr.getReadFileData(path).numAttributes();
        Instances data = pr.getReadFileData(path);

        food_sources = pr.createFoodSources(data.numAttributes(), food_sources); // food sources olusturuluyor

        //////////////////////////////////////////////////////// + 

        Debug.Random rand = new Debug.Random(1);

        classifier = new IBk(); // snflandrc olusturuldu
        eval = new Evaluation(data);

        for (int i = 0; i < N - 1; i++) {
            food_source = new double[N];

            for (int j = 0; j < N; j++) {
                food_source[j] = food_sources[i][j];
            }
            Instances data1 = pr.getReadFileData(path);
            food_sources[i][N - 1] = pr.getSourceFitnessValue(foldnumber, N, rand, data1, food_source, eval,
                    classifier);

        }

        ////////////////// +++++

        BeesProcesses bees = new BeesProcesses();
        double[] neighbor;
        int e = 0;

        while (e < iterationnumber) {
            System.out.println("iter:" + e);
            for (int i = 0; i < N - 1; i++) {
                neighbor = new double[N];
                food_source = new double[N];

                for (int j = 0; j < N; j++)
                    food_source[j] = food_sources[i][j];

                Instances data2 = pr.getReadFileData(path);
                neighbor = bees.employedBeeProcess(food_source, modificationRate, i); // komsu olusturuldu
                neighbor[N - 1] = pr.getSourceFitnessValue(foldnumber, N, rand, data2, neighbor, eval,
                        classifier); // komsunun fitness degeri bulunuyor
                double a = food_source[N - 1];
                double b = neighbor[N - 1];
                if (b > a) {
                    for (int j = 0; j < N; j++) {
                        food_sources[i][j] = neighbor[j];
                    }
                }

            }

            e++;
        } // while sonu

        double[][] onlooker_foodsources = new double[N - 1][N];
        onlooker_foodsources = bees.onlookerBeeProcess(N, 0.5);
        for (int i = 0; i < N - 1; i++) {
            double[] onlooker_food_source = new double[N];

            for (int j = 0; j < N; j++) {
                onlooker_food_source[j] = onlooker_foodsources[i][j];
            }

            Instances data3 = pr.getReadFileData(path);
            onlooker_foodsources[i][N - 1] = pr.getSourceFitnessValue(foldnumber, N, rand, data3,
                    onlooker_food_source, eval, classifier);

        }

        int m = 0;
        while (m < 20) {
            double[][] onlooker_foodsources2 = new double[N - 1][N];
            onlooker_foodsources2 = bees.onlookerBeeProcess(N, 0.5);

            for (int i = 0; i < N - 1; i++) {
                double[] onlooker_food_source = new double[N];

                for (int j = 0; j < N; j++) {
                    onlooker_food_source[j] = onlooker_foodsources2[i][j];
                }

                Instances data4 = pr.getReadFileData(path);
                onlooker_food_source[N - 1] = pr.getSourceFitnessValue(foldnumber, N, rand, data4,
                        onlooker_food_source, eval, classifier);

                for (int j = 0; j < N - 1; j++) {
                    if (onlooker_foodsources[j][N - 1] < onlooker_foodsources2[j][N - 1]) {
                        for (int k = 0; k < N; k++) {
                            onlooker_foodsources[j][k] = onlooker_foodsources[j][k];
                        }
                    }
                }
            }
            m++;
        }

        /////// feature selection
        double[] selected_features = new double[N];

        double max_fit = 0.0;
        for (int i = 0; i < N - 1; i++) {
            if (food_sources[i][N - 1] > max_fit) {
                max_fit = food_sources[i][N - 1];
                for (int j = 0; j < N; j++) {
                    selected_features[j] = food_sources[i][j];
                }
            }

        }

        for (int i = 0; i < N - 1; i++) {
            if (onlooker_foodsources[i][N - 1] > max_fit) {
                max_fit = food_sources[i][N - 1];
                for (int j = 0; j < N; j++) {
                    selected_features[j] = onlooker_foodsources[i][j];
                }
            }

        }

        ////////////
        System.out.println(" ");

        String sf_wfmeasure = "";
        for (int i = 0; i < N; i++) {
            System.out.print(selected_features[i] + " ");
            if (i == N - 1) {
                sf_wfmeasure = Double.toString(selected_features[i]);
            } else {
                if (selected_features[i] == 1.0)
                    sf_indexes = sf_indexes + Integer.toString(i) + ",";
            }
        }

        selectedfeaturesindexes_tf.setText(sf_indexes);
        //weightedfmeasure_tf.setText(sf_wfmeasure);
        //statuslabel.setText("Finished.");

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

From source file:task2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w  w.  j av a2 s .c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet selection</title>");
        out.println("</head>");
        out.println("<body>");
        CSVLoader loader = new CSVLoader();
        loader.setSource(new File("C:/Users//Raguvinoth/Desktop/5339.csv"));
        Instances data = loader.getDataSet();

        //Save ARFF
        ArffSaver saver = new ArffSaver();
        saver.setInstances(data);
        saver.setFile(new File("\"C:/Users/Raguvinoth/Desktop/5339_converted.arff"));
        saver.writeBatch();

        BufferedReader reader = new BufferedReader(
                new FileReader("C://Users//Raguvinoth//Desktop//weka1//5339_nominal.arff"));
        Instances data1 = new Instances(reader);

        if (data1.classIndex() == -1)
            data1.setClassIndex(data1.numAttributes() - 14);
        // 1. meta-classifier
        // useClassifier(data);

        // 2. AttributeSelector
        try {
            AttributeSelection attsel = new AttributeSelection();
            GreedyStepwise search = new GreedyStepwise();
            CfsSubsetEval eval = new CfsSubsetEval();
            attsel.setEvaluator(eval);
            attsel.setSearch(search);
            attsel.SelectAttributes(data);
            int[] indices = attsel.selectedAttributes();

            System.out.println("selected attribute indices:\n" + Utils.arrayToString(indices));
            System.out.println("\n 4. Linear-Regression on above selected attributes");
            long time1 = System.currentTimeMillis();
            long sec1 = time1 / 1000;
            BufferedReader reader1 = new BufferedReader(
                    new FileReader("C://Users//Raguvinoth//Desktop//weka1//5339_linear2.arff"));
            Instances data2 = new Instances(reader1);
            data2.setClassIndex(0);
            LinearRegression lr = new LinearRegression();
            lr.buildClassifier(data2);

            System.out.println(lr.toString());
            long time2 = System.currentTimeMillis();
            long sec2 = time2 / 1000;
            long timeTaken = sec2 - sec1;
            System.out.println("Total time taken for building the model: " + timeTaken + " seconds");

            for (int i = 0; i < 5; i++) {
                out.println("<p>" + "selected attribute indices:\n" + Utils.arrayToString(indices[i]) + "</p>");
            }
            out.println("<p>" + "\n 4. Linear-Regression on above selected attributes" + "</p>");
            out.println("<p>" + lr.toString() + "</p>");
            out.println("<p>" + "Total time taken for building the model: " + timeTaken + " seconds" + "</p>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

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   ww  w.  j  av  a  2s .c o  m
    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:
}