Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 
0018 package org.apache.spark.examples.ml;
0019 
0020 // $example on$
0021 import org.apache.spark.ml.regression.LinearRegression;
0022 import org.apache.spark.ml.regression.LinearRegressionModel;
0023 import org.apache.spark.ml.regression.LinearRegressionTrainingSummary;
0024 import org.apache.spark.ml.linalg.Vectors;
0025 import org.apache.spark.sql.Dataset;
0026 import org.apache.spark.sql.Row;
0027 import org.apache.spark.sql.SparkSession;
0028 // $example off$
0029 
0030 public class JavaLinearRegressionWithElasticNetExample {
0031   public static void main(String[] args) {
0032     SparkSession spark = SparkSession
0033       .builder()
0034       .appName("JavaLinearRegressionWithElasticNetExample")
0035       .getOrCreate();
0036 
0037     // $example on$
0038     // Load training data.
0039     Dataset<Row> training = spark.read().format("libsvm")
0040       .load("data/mllib/sample_linear_regression_data.txt");
0041 
0042     LinearRegression lr = new LinearRegression()
0043       .setMaxIter(10)
0044       .setRegParam(0.3)
0045       .setElasticNetParam(0.8);
0046 
0047     // Fit the model.
0048     LinearRegressionModel lrModel = lr.fit(training);
0049 
0050     // Print the coefficients and intercept for linear regression.
0051     System.out.println("Coefficients: "
0052       + lrModel.coefficients() + " Intercept: " + lrModel.intercept());
0053 
0054     // Summarize the model over the training set and print out some metrics.
0055     LinearRegressionTrainingSummary trainingSummary = lrModel.summary();
0056     System.out.println("numIterations: " + trainingSummary.totalIterations());
0057     System.out.println("objectiveHistory: " + Vectors.dense(trainingSummary.objectiveHistory()));
0058     trainingSummary.residuals().show();
0059     System.out.println("RMSE: " + trainingSummary.rootMeanSquaredError());
0060     System.out.println("r2: " + trainingSummary.r2());
0061     // $example off$
0062 
0063     spark.stop();
0064   }
0065 }