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.Pipeline;
0022 import org.apache.spark.ml.PipelineModel;
0023 import org.apache.spark.ml.PipelineStage;
0024 import org.apache.spark.ml.classification.FMClassificationModel;
0025 import org.apache.spark.ml.classification.FMClassifier;
0026 import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
0027 import org.apache.spark.ml.feature.*;
0028 import org.apache.spark.sql.Dataset;
0029 import org.apache.spark.sql.Row;
0030 import org.apache.spark.sql.SparkSession;
0031 // $example off$
0032 
0033 public class JavaFMClassifierExample {
0034   public static void main(String[] args) {
0035     SparkSession spark = SparkSession
0036         .builder()
0037         .appName("JavaFMClassifierExample")
0038         .getOrCreate();
0039 
0040     // $example on$
0041     // Load and parse the data file, converting it to a DataFrame.
0042     Dataset<Row> data = spark
0043         .read()
0044         .format("libsvm")
0045         .load("data/mllib/sample_libsvm_data.txt");
0046 
0047     // Index labels, adding metadata to the label column.
0048     // Fit on whole dataset to include all labels in index.
0049     StringIndexerModel labelIndexer = new StringIndexer()
0050         .setInputCol("label")
0051         .setOutputCol("indexedLabel")
0052         .fit(data);
0053     // Scale features.
0054     MinMaxScalerModel featureScaler = new MinMaxScaler()
0055         .setInputCol("features")
0056         .setOutputCol("scaledFeatures")
0057         .fit(data);
0058 
0059     // Split the data into training and test sets (30% held out for testing)
0060     Dataset<Row>[] splits = data.randomSplit(new double[] {0.7, 0.3});
0061     Dataset<Row> trainingData = splits[0];
0062     Dataset<Row> testData = splits[1];
0063 
0064     // Train a FM model.
0065     FMClassifier fm = new FMClassifier()
0066         .setLabelCol("indexedLabel")
0067         .setFeaturesCol("scaledFeatures")
0068         .setStepSize(0.001);
0069 
0070     // Convert indexed labels back to original labels.
0071     IndexToString labelConverter = new IndexToString()
0072         .setInputCol("prediction")
0073         .setOutputCol("predictedLabel")
0074         .setLabels(labelIndexer.labelsArray()[0]);
0075 
0076     // Create a Pipeline.
0077     Pipeline pipeline = new Pipeline()
0078         .setStages(new PipelineStage[] {labelIndexer, featureScaler, fm, labelConverter});
0079 
0080     // Train model.
0081     PipelineModel model = pipeline.fit(trainingData);
0082 
0083     // Make predictions.
0084     Dataset<Row> predictions = model.transform(testData);
0085 
0086     // Select example rows to display.
0087     predictions.select("predictedLabel", "label", "features").show(5);
0088 
0089     // Select (prediction, true label) and compute test accuracy.
0090     MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
0091         .setLabelCol("indexedLabel")
0092         .setPredictionCol("prediction")
0093         .setMetricName("accuracy");
0094     double accuracy = evaluator.evaluate(predictions);
0095     System.out.println("Test Accuracy = " + accuracy);
0096 
0097     FMClassificationModel fmModel = (FMClassificationModel)(model.stages()[2]);
0098     System.out.println("Factors: " + fmModel.factors());
0099     System.out.println("Linear: " + fmModel.linear());
0100     System.out.println("Intercept: " + fmModel.intercept());
0101     // $example off$
0102 
0103     spark.stop();
0104   }
0105 }