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 java.util.Arrays;
0022 import java.util.List;
0023 
0024 import org.apache.spark.ml.fpm.FPGrowth;
0025 import org.apache.spark.ml.fpm.FPGrowthModel;
0026 import org.apache.spark.sql.Dataset;
0027 import org.apache.spark.sql.Row;
0028 import org.apache.spark.sql.RowFactory;
0029 import org.apache.spark.sql.SparkSession;
0030 import org.apache.spark.sql.types.*;
0031 // $example off$
0032 
0033 /**
0034  * An example demonstrating FPGrowth.
0035  * Run with
0036  * <pre>
0037  * bin/run-example ml.JavaFPGrowthExample
0038  * </pre>
0039  */
0040 public class JavaFPGrowthExample {
0041   public static void main(String[] args) {
0042     SparkSession spark = SparkSession
0043       .builder()
0044       .appName("JavaFPGrowthExample")
0045       .getOrCreate();
0046 
0047     // $example on$
0048     List<Row> data = Arrays.asList(
0049       RowFactory.create(Arrays.asList("1 2 5".split(" "))),
0050       RowFactory.create(Arrays.asList("1 2 3 5".split(" "))),
0051       RowFactory.create(Arrays.asList("1 2".split(" ")))
0052     );
0053     StructType schema = new StructType(new StructField[]{ new StructField(
0054       "items", new ArrayType(DataTypes.StringType, true), false, Metadata.empty())
0055     });
0056     Dataset<Row> itemsDF = spark.createDataFrame(data, schema);
0057 
0058     FPGrowthModel model = new FPGrowth()
0059       .setItemsCol("items")
0060       .setMinSupport(0.5)
0061       .setMinConfidence(0.6)
0062       .fit(itemsDF);
0063 
0064     // Display frequent itemsets.
0065     model.freqItemsets().show();
0066 
0067     // Display generated association rules.
0068     model.associationRules().show();
0069 
0070     // transform examines the input items against all the association rules and summarize the
0071     // consequents as prediction
0072     model.transform(itemsDF).show();
0073     // $example off$
0074 
0075     spark.stop();
0076   }
0077 }