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.classification.NaiveBayes;
0022 import org.apache.spark.ml.classification.NaiveBayesModel;
0023 import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
0024 import org.apache.spark.sql.Dataset;
0025 import org.apache.spark.sql.Row;
0026 import org.apache.spark.sql.SparkSession;
0027 // $example off$
0028 
0029 /**
0030  * An example for Naive Bayes Classification.
0031  */
0032 public class JavaNaiveBayesExample {
0033 
0034   public static void main(String[] args) {
0035     SparkSession spark = SparkSession
0036       .builder()
0037       .appName("JavaNaiveBayesExample")
0038       .getOrCreate();
0039 
0040     // $example on$
0041     // Load training data
0042     Dataset<Row> dataFrame =
0043       spark.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
0044     // Split the data into train and test
0045     Dataset<Row>[] splits = dataFrame.randomSplit(new double[]{0.6, 0.4}, 1234L);
0046     Dataset<Row> train = splits[0];
0047     Dataset<Row> test = splits[1];
0048 
0049     // create the trainer and set its parameters
0050     NaiveBayes nb = new NaiveBayes();
0051 
0052     // train the model
0053     NaiveBayesModel model = nb.fit(train);
0054 
0055     // Select example rows to display.
0056     Dataset<Row> predictions = model.transform(test);
0057     predictions.show();
0058 
0059     // compute accuracy on the test set
0060     MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
0061       .setLabelCol("label")
0062       .setPredictionCol("prediction")
0063       .setMetricName("accuracy");
0064     double accuracy = evaluator.evaluate(predictions);
0065     System.out.println("Test set accuracy = " + accuracy);
0066     // $example off$
0067 
0068     spark.stop();
0069   }
0070 }