Example usage for weka.classifiers.functions LinearRegression toString

List of usage examples for weka.classifiers.functions LinearRegression toString

Introduction

In this page you can find the example usage for weka.classifiers.functions LinearRegression toString.

Prototype

@Override
public String toString() 

Source Link

Document

Outputs the linear regression model as a string.

Usage

From source file:task2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww  .j a  v a  2 s  . co 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:controller.MineroControler.java

public String regresionLineal() {
    BufferedReader breader = null;
    Instances datos = null;/*w  w w  .  ja v a 2 s.c  o  m*/
    breader = new BufferedReader(fuente_arff);
    try {
        datos = new Instances(breader);
        datos.setClassIndex(datos.numAttributes() - 1); // clase principal, ltima en atributos
    } catch (IOException ex) {
        System.err.println("Problemas al intentar cargar los datos");
    }

    LinearRegression regresionL = new LinearRegression();
    try {

        regresionL.buildClassifier(datos);

        Instance nuevaCal = datos.lastInstance();
        double calif = regresionL.classifyInstance(nuevaCal);

        setValorCalculado(new Double(calif));

    } catch (Exception ex) {
        System.err.println("Problemas al clasificar instancia");
    }

    return regresionL.toString();
}

From source file:GroupProject.DMChartUI.java

/**
* Action for the generate button//from  ww  w  .  j  a  v  a 2 s  .  c  o  m
* It reads the user input from the table and the selected options and performs
* a classifiecation of the user input
* the user can choose linear regression, naive bayes classifier, or j48 trees to classify 
*
*/
private void generateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateButtonActionPerformed
    // TODO add your handling code here:                                              
    // TODO add your handling code here:
    //File file = new File("studentTemp.csv");
    CSVtoArff converter = new CSVtoArff();
    Instances students = null;
    Instances students2 = null;
    try {
        converter.convert("studentTemp.csv", "studentTemp.arff");
    } catch (IOException ex) {
        Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        students = new Instances(new BufferedReader(new FileReader("studentTemp.arff")));
        students2 = new Instances(new BufferedReader(new FileReader("studentTemp.arff")));
    } catch (IOException ex) {
        Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    //get column to predict values for 
    //int target=students.numAttributes()-1; 
    int target = dataSelector.getSelectedIndex() + 1;
    System.out.printf("this is the target: %d\n", target);
    //set target 
    students.setClassIndex(target);
    students2.setClassIndex(target);

    //case on which radio button is selected 
    //Linear Regressions
    if (LRB.isSelected()) {

        LinearRegression model = null;
        if (Lmodel != null) {
            model = Lmodel;
        } else {
            buildLinearModel();
            model = Lmodel;
        }

        System.out.println("im doing linear regression");

        equationDisplayArea.setText(model.toString());

        System.out.println("im going to get the instance");

        Instance prediction2 = getInstance(true);

        Remove remove = new Remove();
        int[] toremove = { 0, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 16, 17 };
        remove.setAttributeIndicesArray(toremove);

        try {
            remove.setInputFormat(students);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        Instances instNew = null;
        try {
            instNew = Filter.useFilter(students, remove);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        prediction2.setDataset(instNew);
        System.err.print("i got the instance");
        double result = 0;
        try {
            result = model.classifyInstance(prediction2);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        System.out.printf("the result : %f \n ", result);
        predictValue.setText(Double.toString(result));
        System.out.println("I'm done with Linear Regression");
    }

    //Naive Bayes
    else if (NBB.isSelected()) {
        Classifier cModel = null;

        if (NBmodel != null) {
            cModel = NBmodel;
        } else {
            buildNBClassifier();
            cModel = NBmodel;
        }

        System.out.println("im doing NB");

        //build test 
        Evaluation eTest = null;
        try {
            eTest = new Evaluation(students);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Using NB");

        try {
            eTest.evaluateModel(cModel, students);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        //display the test results to console 
        String strSummary = eTest.toSummaryString();
        System.out.println(strSummary);

        //build instance to predict 
        System.out.println("im going to get the instance");

        Instance prediction2 = getInstance(false);

        prediction2.setDataset(students);
        System.err.print("i got the instance");

        //replace with loop stating the class names 
        //fit text based on name of categories 
        double pred = 0;
        try {
            pred = cModel.classifyInstance(prediction2);
            prediction2.setClassValue(pred);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        //get the predicted value and set predictValue to it 
        predictValue.setText(prediction2.classAttribute().value((int) pred));

        System.out.println("I'm done with Naive Bayes");

        double[] fDistribution2 = null;
        try {
            fDistribution2 = cModel.distributionForInstance(prediction2);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        double max = 0;
        int maxindex = 0;
        max = fDistribution2[0];
        for (int i = 0; i < fDistribution2.length; i++) {
            if (fDistribution2[i] > max) {
                maxindex = i;
                max = fDistribution2[i];
            }
            System.out.println("the value at " + i + " : " + fDistribution2[i]);
            System.out.println("the label at " + i + prediction2.classAttribute().value(i));
        }
        prediction2.setClassValue(maxindex);
        predictValue.setText(prediction2.classAttribute().value(maxindex));

    }
    //J48 Tree
    else if (JB.isSelected()) {

        System.out.println("im doing j48 ");

        Classifier jModel = null;
        if (Jmodel != null) {
            jModel = Jmodel;
        } else {
            buildJClassifier();
            jModel = Jmodel;
        }
        //test model 
        Evaluation eTest2 = null;
        try {
            eTest2 = new Evaluation(students);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Using J48 test");
        try {
            eTest2.evaluateModel(jModel, students);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        String strSummary2 = eTest2.toSummaryString();
        System.out.println(strSummary2);

        System.out.println("im going to get the instance");

        Instance prediction2 = getInstance(false);

        prediction2.setDataset(students);
        System.err.print("i got the instance\n");

        double pred = 0;
        try {
            pred = jModel.classifyInstance(prediction2);
            prediction2.setClassValue(pred);
            System.out.println("i did a prediction");
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        //get the predicted value and set predictValue to it 
        System.out.println("this was pred:" + pred);
        predictValue.setText(prediction2.classAttribute().value((int) pred));

        System.out.println("I'm done with J48");
        //replace with loop stating the class names 
        //fit text based on name of categories 

        double[] fDistribution2 = null;
        try {
            fDistribution2 = jModel.distributionForInstance(prediction2);
        } catch (Exception ex) {
            Logger.getLogger(DMChartUI.class.getName()).log(Level.SEVERE, null, ex);
        }

        double max = 0;
        int maxindex = 0;
        max = fDistribution2[0];
        for (int i = 0; i < fDistribution2.length; i++) {
            if (fDistribution2[i] > max) {
                maxindex = i;
                max = fDistribution2[i];
            }
            System.out.println("the value at " + i + " : " + fDistribution2[i]);
            System.out.println("the label at " + i + " " + prediction2.classAttribute().value(i));
        }
        prediction2.setClassValue(maxindex);
        predictValue.setText(prediction2.classAttribute().value(maxindex));

    }

}

From source file:wekimini.learning.LinearRegressionModelBuilder.java

@Override
public LinearRegressionModel build(String name) throws Exception {
    if (trainingData == null) {
        throw new IllegalStateException("Must set training examples (to not null) before building model");
    }/*from  ww w .  j  a  v a2 s  .  c o m*/
    LinearRegression m;
    LinearRegressionAttributeTransformer t = null;
    if (exponent == 1) {
        m = (LinearRegression) WekaModelBuilderHelper.build(classifier, trainingData);
    } else {
        t = new LinearRegressionAttributeTransformer(trainingData.numAttributes() - 1, exponent);
        Instances i = t.transformedData(trainingData);
        System.out.println("New instances:\n" + i.toString());
        m = (LinearRegression) WekaModelBuilderHelper.build(classifier, i);
    }
    //Remove: for testing:
    logger.log(Level.WARNING, m.toString());
    return new LinearRegressionModel(name, m, t);
}