Spark中关于购物篮的设计,以及优化

本文通过SparkCore实现购物篮分析,详细介绍了程序实现、关键步骤和优化方法,包括频繁项集计算、关联规则挖掘及使用广播变量提高效率。
摘要由CSDN通过智能技术生成

一:介绍

1.购物篮的定义

2.适用场景

3.相关概念

 4.步骤

5.编程实现

6.步骤

二:程序

1.程序

 package com.ibeifeng.senior.mba.association
 
 import org.apache.hadoop.fs.{FileSystem, Path}
 import org.apache.spark.rdd.RDD
 import org.apache.spark.{SparkConf, SparkContext}
 
 import scala.collection.mutable
 
 /**
   * 使用SparkCore实现购物篮分析
   * Created by ibf on 01/12.
   */
 object FindAssociationRulesSparkCore {
   /**
     * 先从缓存中获取数据,如果不存在,直接重新获取
     *
     * @param items
     * @param size
     * @param cache
     * @return
     */
   def findItemSetsByCache(items: List[(String, Int)], size: Int, cache: mutable.Map[Int, List[List[(String, Int)]]]): List[List[(String, Int)]] = {
     cache.get(size).orElse {
       // 获取值
       val result = findItemSets(items, size, cache)
 
       // 更新缓存
       cache += size -> result
 
       // 返回值
       Some(result)
     }.get
   }
 
 
   /**
     * 构建项集基于items商品列表,项集中的商品数量是size指定
     *
     * @param items 商品列表:eg: [A, B, C]
     * @param size  最终项集包含商品的数量
     * @return
     */
   def findItemSets(items: List[(String, Int)], size: Int, cache: mutable.Map[Int, List[List[(String, Int)]]]): List[List[(String, Int)]] = {
     if (size == 1) {
       // items中的每个商品都是一个项集
       items.map(item => item :: Nil)
     } else {
       // 当size不是1的时候
       // 1. 获取项集大小为size-1的项集列表
       val tmpItemSets = findItemSetsByCache(items, size - 1, cache)
       // 2. 给tmpItemSets中添加一个新的不重复的项 ==> 数据的转换
       val itemSets = tmpItemSets.flatMap(itemSets => {
         // 给itemSets项集添加一个新的商品ID,要求不重复
         val newItemSets = items
           // 将包含的商品过滤掉&要求下标必须大于以及存在
           .filter(item => !itemSets.contains(item) && itemSets.forall(_._2 < item._2))
           // 将商品添加到项集中,产生一个新的项集
           // 为了使用distinct做去重操作,进行一个排序操作
           .map(item => (item :: itemSets))
 
         // 返回值
         newItemSets
       })
 
       // 返回项集的值
       itemSets
     }
   }
 
   def main(args: Array[String]): Unit = {
     // 1. 创建SparkContext
     val conf = new SparkConf()
       .setAppName("find-association-rules")
       .setMaster("local[*]")
     val sc = SparkContext.getOrCreat

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值