import weka.classifiers.Evaluation;
import weka.classifiers.functions.LinearRegression;
import weka.core.Instances;
import weka.core.WekaPackageManager;
import weka.core.converters.ConverterUtils.DataSource;
import java.util.Random;


public class linear_regression {
    public static void main(String args[]) throws Exception {

        WekaPackageManager wk = new WekaPackageManager();   //create Package Manager instance
        wk.loadPackages(false);   //load the packages (false = output should not be the loading progress)

        //Import data set
        DataSource src = new DataSource("./house_prices.csv");   //create DataSource pointing to data set
        Instances housing = src.getDataSet();   //load data set into instances

        //Split data set into training and testing data set
        int seed = 42;   //set seed for randomization

        double trainPercentage = 80.0;   //set percentage size of training data

        housing.randomize(new Random(seed));   //randomize data with seed

        int trainSize = (int) Math.round(housing.numInstances() * trainPercentage / 100.0);   //calculate training data size
        int testSize = housing.numInstances() - trainSize;   //calculate testing data size

        Instances trainData = new Instances(housing, 0, trainSize);   //create training data
        Instances testData = new Instances(housing, trainSize, testSize);   //create testing data

        //System.out.println(trainData);   //print out training data
        //System.out.println(testData);   //print out testing data

        //Compute Linear Regression
        LinearRegression lr = new LinearRegression();   //create linear regression instance
        trainData.setClassIndex(trainData.numAttributes() - 1);   //set the dependant variable of the training data (in this case the last column)
        lr.buildClassifier(trainData);   //build the model
        System.out.println(lr);   //print out the result

        //Evaluate Model
        Evaluation eval = new Evaluation(trainData);   //create evaluation instance
        testData.setClassIndex(testData.numAttributes()-1);   //set the dependant variable of the testing data (in this case the last column)
        eval.evaluateModel(lr, testData);   //evaluate the model
        System.out.println(eval.toSummaryString());   //print out a summary of the evaluation
    }
}
