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 // $example on$
0020 import org.apache.spark.ml.clustering.LDA;
0021 import org.apache.spark.ml.clustering.LDAModel;
0022 import org.apache.spark.sql.Dataset;
0023 import org.apache.spark.sql.Row;
0024 import org.apache.spark.sql.SparkSession;
0025 // $example off$
0026 
0027 /**
0028  * An example demonstrating LDA.
0029  * Run with
0030  * <pre>
0031  * bin/run-example ml.JavaLDAExample
0032  * </pre>
0033  */
0034 public class JavaLDAExample {
0035 
0036   public static void main(String[] args) {
0037     // Creates a SparkSession
0038     SparkSession spark = SparkSession
0039       .builder()
0040       .appName("JavaLDAExample")
0041       .getOrCreate();
0042 
0043     // $example on$
0044     // Loads data.
0045     Dataset<Row> dataset = spark.read().format("libsvm")
0046       .load("data/mllib/sample_lda_libsvm_data.txt");
0047 
0048     // Trains a LDA model.
0049     LDA lda = new LDA().setK(10).setMaxIter(10);
0050     LDAModel model = lda.fit(dataset);
0051 
0052     double ll = model.logLikelihood(dataset);
0053     double lp = model.logPerplexity(dataset);
0054     System.out.println("The lower bound on the log likelihood of the entire corpus: " + ll);
0055     System.out.println("The upper bound on perplexity: " + lp);
0056 
0057     // Describe topics.
0058     Dataset<Row> topics = model.describeTopics(3);
0059     System.out.println("The topics described by their top-weighted terms:");
0060     topics.show(false);
0061 
0062     // Shows the result.
0063     Dataset<Row> transformed = model.transform(dataset);
0064     transformed.show(false);
0065     // $example off$
0066 
0067     spark.stop();
0068   }
0069 }