代码解析:
spark.udf.register("changeDate", (x: Int)=>simpleDateFormat.format(new Date(x * 1000L)).toInt)
在recommender下新建子项目StatisticsRecommender,pom.xml文件中只需引入spark、scala和mongodb的相关依赖:
在resources文件夹下引入log4j.properties,然后在src/main/scala下新建scala 单例对象com.atguigu.statistics.StatisticsRecommender。
同样,我们应该先建好样例类,在main()方法中定义配置、创建SparkSession并加载数据,最后关闭spark。
历史热门商品统计:根据所有历史评分数据,计算历史评分次数最多的商品
最近热门商品统计:根据评分,按月为单位计算最近时间的月份里面评分数最多的商品集合
商品平均得分统计:根据历史数据中所有用户对商品的评分,周期性的计算每个商品的平均得分
主体代码(src/main/scala/com.atguigu.statistics/StatisticsRecommender.scala):
package com.atguigu.statistics
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkConf
import org.apache.spark.sql.{DataFrame, SparkSession}
case class Rating( userId: Int, productId: Int, score: Double, timestamp: Int )
case class MongoConfig( uri: String, db: String )
object StatisticsRecommender {
// 定义mongodb中存储的表名
val MONGODB_RATING_COLLECTION = "Rating"
val RATE_MORE_PRODUCTS = "RateMoreProducts"
val RATE_MORE_RECENTLY_PRODUCTS = "RateMoreRecentlyProducts"
val AVERAGE_PRODUCTS = "AverageProducts"
def main(args: Array[String]): Unit = {
val config = Map(
"spark.cores" -> "local[1]",
"mongo.uri" -> "mongodb://localhost:27017/recommender",
"mongo.db" -> "recommender"
)
// 创建一个spark config
val sparkConf = new SparkConf().setMaster(config("spark.cores")).setAppName("StatisticsRecommender")
// 创建spark session
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
import spark.implicits._
implicit val mongoConfig = MongoConfig( config("mongo.uri"), config("mongo.db") )
// 加载数据
val ratingDF = spark.read
.option("uri", mongoConfig.uri)
.option("collection", MONGODB_RATING_COLLECTION)
.format("com.mongodb.spark.sql")
.load()
.as[Rating]
.toDF()
// 创建一张叫ratings的临时表
ratingDF.createOrReplaceTempView("ratings")
// TODO: 【 用spark sql去做不同的统计推荐 】
// todo: (1)历史热门商品,按照评分个数统计,productId,count
val rateMoreProductsDF = spark.sql("select productId, count(productId) as count from ratings group by productId order by count desc")
storeDFInMongoDB( rateMoreProductsDF, RATE_MORE_PRODUCTS )
// todo: (2)近期热门商品,把时间戳转换成yyyyMM格式进行评分个数统计,最终得到productId, count, yearmonth
// 创建一个日期格式化工具
val simpleDateFormat = new SimpleDateFormat("yyyyMM")
// 注册UDF,将timestamp转化为年月格式yyyyMM
spark.udf.register("changeDate", (x: Int)=>simpleDateFormat.format(new Date(x * 1000L)).toInt)
// 把原始rating数据转换成想要的结构productId, score, yearmonth
val ratingOfYearMonthDF = spark.sql("select productId, score, changeDate(timestamp) as yearmonth from ratings")
ratingOfYearMonthDF.createOrReplaceTempView("ratingOfMonth")
val rateMoreRecentlyProductsDF = spark.sql("select productId, count(productId) as count, yearmonth from ratingOfMonth group by yearmonth, productId order by yearmonth desc, count desc")
// 把df保存到mongodb
storeDFInMongoDB( rateMoreRecentlyProductsDF, RATE_MORE_RECENTLY_PRODUCTS )
// todo: (3)优质商品统计,商品的平均评分,productId,avg
val averageProductsDF = spark.sql("select productId, avg(score) as avg from ratings group by productId order by avg desc")
storeDFInMongoDB( averageProductsDF, AVERAGE_PRODUCTS )
spark.stop()
}
// TODO: 【 保存到MongoDB数据库 】
def storeDFInMongoDB(df: DataFrame, collection_name: String)(implicit mongoConfig: MongoConfig): Unit ={
df.write
.option("uri", mongoConfig.uri)
.option("collection", collection_name)
.mode("overwrite")
.format("com.mongodb.spark.sql")
.save()
}
}
通过ALS训练出来的Model来计算所有当前用户商品的推荐列表,主要思路如下:
最后生成的数据结构如下:将数据保存到MongoDB的UserRecs表中
新建recommender的子项目OfflineRecommender,引入spark、scala、mongo和jblas的依赖:
同样经过前期的构建样例类、声明配置、创建SparkSession等步骤,可以加载数据开始计算模型了。
通过ALS计算商品相似度矩阵,该矩阵用于查询当前商品的相似商品并为实时推荐系统服务。
离线计算的ALS 算法,算法最终会为用户、商品分别生成最终的特征矩阵,分别是表示用户特征矩阵的U(m x k)矩阵,每个用户由 k个特征描述;表示物品特征矩阵的V(n x k)矩阵,每个物品也由 k 个特征描述。
V(n x k)表示物品特征矩阵,每一行是一个 k 维向量,虽然我们并不知道每一个维度的特征意义是什么,但是k 个维度的数学向量表示了该行对应商品的特征。
所以,每个商品用V(n x k)每一行的
数据集中任意两个商品间相似度都可以由公式计算得到,商品与商品之间的相似度在一段时间内基本是固定值。最后生成的数据保存到MongoDB的ProductRecs表中。
在上述模型训练的过程中,我们直接给定了隐语义模型的rank,iterations,lambda三个参数。
对于我们的模型,这并不一定是最优的参数选取,所以我们需要对模型进行评估。
通常的做法是计算均方根误差(RMSE),考察预测评分与实际评分之间的误差。
有了RMSE,我们可以就可以通过多次调整参数值,来选取RMSE最小的一组作为我们模型的优化选择。
其中adjustALSParams方法是模型评估的核心,输入一组训练数据和测试数据,输出计算得到最小RMSE的那组参数。
代码实现如下:
计算RMSE的函数getRMSE代码实现如下:
运行代码得到目前数据的最优模型参数
代码主体:
package com.atguigu.offline
import org.apache.spark.SparkConf
import org.apache.spark.mllib.recommendation.{ALS, Rating}
import org.apache.spark.sql.SparkSession
import org.jblas.DoubleMatrix
case class ProductRating( userId: Int, productId: Int, score: Double, timestamp: Int )
case class MongoConfig( uri: String, db: String )
// 定义标准推荐对象
case class Recommendation( productId: Int, score: Double )
// 定义用户的推荐列表
case class UserRecs( userId: Int, recs: Seq[Recommendation] )
// 定义商品相似度列表
case class ProductRecs( productId: Int, recs: Seq[Recommendation] )
object OfflineRecommender {
// 定义mongodb中存储的表名
val MONGODB_RATING_COLLECTION = "Rating"
val USER_RECS = "UserRecs"
val PRODUCT_RECS = "ProductRecs"
val USER_MAX_RECOMMENDATION = 20
def main(args: Array[String]): Unit = {
val config = Map(
"spark.cores" -> "local[*]",
"mongo.uri" -> "mongodb://localhost:27017/recommender",
"mongo.db" -> "recommender"
)
// 创建一个spark config
val sparkConf = new SparkConf().setMaster(config("spark.cores")).setAppName("OfflineRecommender")
// 创建spark session
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
import spark.implicits._
implicit val mongoConfig = MongoConfig( config("mongo.uri"), config("mongo.db") )
// 加载数据
val ratingRDD = spark.read
.option("uri", mongoConfig.uri)
.option("collection", MONGODB_RATING_COLLECTION)
.format("com.mongodb.spark.sql")
.load()
.as[ProductRating]
.rdd
.map(
rating => (rating.userId, rating.productId, rating.score)
).cache()
// 提取出所有用户和商品的数据集
val userRDD = ratingRDD.map(_._1).distinct()
val productRDD = ratingRDD.map(_._2).distinct()
// 核心计算过程
// 1. 训练隐语义模型
val trainData = ratingRDD.map(x=>Rating(x._1,x._2,x._3))
// 定义模型训练的参数,rank隐特征个数,iterations迭代词数,lambda正则化系数
val ( rank, iterations, lambda ) = ( 5, 10, 0.01 )
val model = ALS.train( trainData, rank, iterations, lambda )
// 2. 获得预测评分矩阵,得到用户的推荐列表
// 用userRDD和productRDD做一个笛卡尔积,得到空的userProductsRDD表示的评分矩阵
val userProducts = userRDD.cartesian(productRDD)
val preRating = model.predict(userProducts)
// 从预测评分矩阵中提取得到用户推荐列表
val userRecs = preRating.filter(_.rating>0)
.map(
rating => ( rating.user, ( rating.product, rating.rating ) )
)
.groupByKey()
.map{
case (userId, recs) =>
UserRecs( userId, recs.toList.sortWith(_._2>_._2).take(USER_MAX_RECOMMENDATION).map(x=>Recommendation(x._1,x._2)) )
}
.toDF()
userRecs.write
.option("uri", mongoConfig.uri)
.option("collection", USER_RECS)
.mode("overwrite")
.format("com.mongodb.spark.sql")
.save()
// 3. 利用商品的特征向量,计算商品的相似度列表
val productFeatures = model.productFeatures.map{
case (productId, features) => ( productId, new DoubleMatrix(features) )
}
// 两两配对商品,计算余弦相似度
val productRecs = productFeatures.cartesian(productFeatures)
.filter{
case (a, b) => a._1 != b._1
}
// 计算余弦相似度
.map{
case (a, b) =>
val simScore = consinSim( a._2, b._2 )
( a._1, ( b._1, simScore ) )
}
.filter(_._2._2 > 0.4)
.groupByKey()
.map{
case (productId, recs) =>
ProductRecs( productId, recs.toList.sortWith(_._2>_._2).map(x=>Recommendation(x._1,x._2)) )
}
.toDF()
productRecs.write
.option("uri", mongoConfig.uri)
.option("collection", PRODUCT_RECS)
.mode("overwrite")
.format("com.mongodb.spark.sql")
.save()
spark.stop()
}
def consinSim(product1: DoubleMatrix, product2: DoubleMatrix): Double ={
product1.dot(product2)/ ( product1.norm2() * product2.norm2() )
}
}
在recommender下新建子项目StreamingRecommender,引入spark、scala、mongo、redis和kafka的依赖:
代码中首先定义样例类和一个连接助手对象(用于建立redis和mongo连接),并在StreamingRecommender中定义一些常量
实时推荐主体代码如下:
def main(args: Array[String]): Unit = {
val config = Map(
"spark.cores" -> "local[*]",
"mongo.uri" -> "mongodb://localhost:27017/recommender",
"mongo.db" -> "recommender",
"kafka.topic" -> "recommender"
)
//创建一个SparkConf配置
val sparkConf = new SparkConf().setAppName("StreamingRecommender").setMaster(config("spark.cores"))
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
val sc = spark.sparkContext
val ssc = new StreamingContext(sc,Seconds(2))
implicit val mongConfig = MongConfig(config("mongo.uri"),config("mongo.db"))
import spark.implicits._
// 广播商品相似度矩阵
//装换成为 Map[Int, Map[Int,Double]]
val simProductsMatrix = spark
.read
.option("uri",config("mongo.uri"))
.option("collection",MONGODB_PRODUCT_RECS_COLLECTION)
.format("com.mongodb.spark.sql")
.load()
.as[ProductRecs]
.rdd
.map{recs =>
(recs.productId,recs.recs.map(x=> (x.productId,x.score)).toMap)
}.collectAsMap()
val simProductsMatrixBroadCast = sc.broadcast(simProductsMatrix)
//创建到Kafka的连接
val kafkaPara = Map(
"bootstrap.servers" -> "localhost:9092",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "recommender",
"auto.offset.reset" -> "latest"
)
val kafkaStream = KafkaUtils.createDirectStream[String,String](ssc,LocationStrategies.PreferConsistent,ConsumerStrategies.Subscribe[String,String](Array(config("kafka.topic")),kafkaPara))
// UID|MID|SCORE|TIMESTAMP
// 产生评分流
val ratingStream = kafkaStream.map{case msg=>
var attr = msg.value().split("\\|")
(attr(0).toInt,attr(1).toInt,attr(2).toDouble,attr(3).toInt)
}
// 核心实时推荐算法
ratingStream.foreachRDD{rdd =>
rdd.map{case (userId,productId,score,timestamp) =>
println(">>>>>>>>>>>>>>>>")
//获取当前最近的M次商品评分
val userRecentlyRatings = getUserRecentlyRating(MAX_USER_RATINGS_NUM,userId,ConnHelper.jedis)
//获取商品P最相似的K个商品
val simProducts = getTopSimProducts(MAX_SIM_PRODUCTS_NUM,productId,userId,simProductsMatrixBroadCast.value)
//计算待选商品的推荐优先级
val streamRecs = computeProductScores(simProductsMatrixBroadCast.value,userRecentlyRatings,simProducts)
//将数据保存到MongoDB
saveRecsToMongoDB(userId,streamRecs)
}.count()
}
//启动Streaming程序
ssc.start()
ssc.awaitTermination()
}
在离线算法中,已经预先将商品的相似度矩阵进行了计算,所以每个商品productId 的最相似的K 个商品很容易获取:从MongoDB中读取ProductRecs数据,从productId 在simHash 对应的子哈希表中获取相似度前K 大的那些商品。输出是数据类型为Array[Int]的数组,表示与productId 最相似的商品集合,并命名为candidateProducts 以作为候选商品集合。
对于候选商品集合simiHash和userId 的最近K 个评分recentRatings,算法代码内容如下:
其中,getProductSimScore是取候选商品和已评分商品的相似度,代码如下:
而log是对数运算,这里实现为取10的对数(常用对数):
代码主体:
package com.atguigu.online
import com.mongodb.casbah.commons.MongoDBObject
import com.mongodb.casbah.{MongoClient, MongoClientURI}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import redis.clients.jedis.Jedis
// 定义一个连接助手对象,建立到redis和mongodb的连接
object ConnHelper extends Serializable{
// 懒变量定义,使用的时候才初始化
lazy val jedis = new Jedis("localhost")
lazy val mongoClient = MongoClient(MongoClientURI("mongodb://localhost:27017/recommender"))
}
case class MongoConfig( uri: String, db: String )
// 定义标准推荐对象
case class Recommendation( productId: Int, score: Double )
// 定义用户的推荐列表
case class UserRecs( userId: Int, recs: Seq[Recommendation] )
// 定义商品相似度列表
case class ProductRecs( productId: Int, recs: Seq[Recommendation] )
object OnlineRecommender {
// 定义常量和表名
val MONGODB_RATING_COLLECTION = "Rating"
val STREAM_RECS = "StreamRecs"
val PRODUCT_RECS = "ProductRecs"
val MAX_USER_RATING_NUM = 20
val MAX_SIM_PRODUCTS_NUM = 20
def main(args: Array[String]): Unit = {
val config = Map(
"spark.cores" -> "local[*]",
"mongo.uri" -> "mongodb://localhost:27017/recommender",
"mongo.db" -> "recommender",
"kafka.topic" -> "recommender"
)
// 创建spark conf
val sparkConf = new SparkConf().setMaster(config("spark.cores")).setAppName("OnlineRecommender")
val spark = SparkSession.builder().config(sparkConf).getOrCreate()
val sc = spark.sparkContext
val ssc = new StreamingContext(sc, Seconds(2))
import spark.implicits._
implicit val mongoConfig = MongoConfig( config("mongo.uri"), config("mongo.db") )
// 加载数据,相似度矩阵,广播出去
val simProductsMatrix = spark.read
.option("uri", mongoConfig.uri)
.option("collection", PRODUCT_RECS)
.format("com.mongodb.spark.sql")
.load()
.as[ProductRecs]
.rdd
// 为了后续查询相似度方便,把数据转换成map形式
.map{item =>
( item.productId, item.recs.map( x=>(x.productId, x.score) ).toMap )
}
.collectAsMap()
// 定义广播变量
val simProcutsMatrixBC = sc.broadcast(simProductsMatrix)
// 创建kafka配置参数
val kafkaParam = Map(
"bootstrap.servers" -> "localhost:9092",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "recommender",
"auto.offset.reset" -> "latest"
)
// 创建一个DStream
val kafkaStream = KafkaUtils.createDirectStream[String, String]( ssc,
LocationStrategies.PreferConsistent,
ConsumerStrategies.Subscribe[String, String]( Array(config("kafka.topic")), kafkaParam )
)
// 对kafkaStream进行处理,产生评分流,userId|productId|score|timestamp
val ratingStream = kafkaStream.map{msg=>
var attr = msg.value().split("\\|")
( attr(0).toInt, attr(1).toInt, attr(2).toDouble, attr(3).toInt )
}
// 核心算法部分,定义评分流的处理流程
ratingStream.foreachRDD{
rdds => rdds.foreach{
case ( userId, productId, score, timestamp ) =>
println("rating data coming!>>>>>>>>>>>>>>>>>>")
// TODO: 核心算法流程
// 1. 从redis里取出当前用户的最近评分,保存成一个数组Array[(productId, score)]
val userRecentlyRatings = getUserRecentlyRatings( MAX_USER_RATING_NUM, userId, ConnHelper.jedis )
// 2. 从相似度矩阵中获取当前商品最相似的商品列表,作为备选列表,保存成一个数组Array[productId]
val candidateProducts = getTopSimProducts( MAX_SIM_PRODUCTS_NUM, productId, userId, simProcutsMatrixBC.value )
// 3. 计算每个备选商品的推荐优先级,得到当前用户的实时推荐列表,保存成 Array[(productId, score)]
val streamRecs = computeProductScore( candidateProducts, userRecentlyRatings, simProcutsMatrixBC.value )
// 4. 把推荐列表保存到mongodb
saveDataToMongoDB( userId, streamRecs )
}
}
// 启动streaming
ssc.start()
println("streaming started!")
ssc.awaitTermination()
}
/**
* 从redis里获取最近num次评分
*/
import scala.collection.JavaConversions._
def getUserRecentlyRatings(num: Int, userId: Int, jedis: Jedis): Array[(Int, Double)] = {
// 从redis中用户的评分队列里获取评分数据,list键名为uid:USERID,值格式是 PRODUCTID:SCORE
jedis.lrange( "userId:" + userId.toString, 0, num )
.map{ item =>
val attr = item.split("\\:")
( attr(0).trim.toInt, attr(1).trim.toDouble )
}
.toArray
}
// 获取当前商品的相似列表,并过滤掉用户已经评分过的,作为备选列表
def getTopSimProducts(num: Int,
productId: Int,
userId: Int,
simProducts: scala.collection.Map[Int, scala.collection.immutable.Map[Int, Double]])
(implicit mongoConfig: MongoConfig): Array[Int] ={
// 从广播变量相似度矩阵中拿到当前商品的相似度列表
val allSimProducts = simProducts(productId).toArray
// 获得用户已经评分过的商品,过滤掉,排序输出
val ratingCollection = ConnHelper.mongoClient( mongoConfig.db )( MONGODB_RATING_COLLECTION )
val ratingExist = ratingCollection.find( MongoDBObject("userId"->userId) )
.toArray
.map{item=> // 只需要productId
item.get("productId").toString.toInt
}
// 从所有的相似商品中进行过滤
allSimProducts.filter( x => ! ratingExist.contains(x._1) )
.sortWith(_._2 > _._2)
.take(num)
.map(x=>x._1)
}
// 计算每个备选商品的推荐得分
def computeProductScore(candidateProducts: Array[Int],
userRecentlyRatings: Array[(Int, Double)],
simProducts: scala.collection.Map[Int, scala.collection.immutable.Map[Int, Double]])
: Array[(Int, Double)] ={
// 定义一个长度可变数组ArrayBuffer,用于保存每一个备选商品的基础得分,(productId, score)
val scores = scala.collection.mutable.ArrayBuffer[(Int, Double)]()
// 定义两个map,用于保存每个商品的高分和低分的计数器,productId -> count
val increMap = scala.collection.mutable.HashMap[Int, Int]()
val decreMap = scala.collection.mutable.HashMap[Int, Int]()
// 遍历每个备选商品,计算和已评分商品的相似度
for( candidateProduct <- candidateProducts; userRecentlyRating <- userRecentlyRatings ){
// 从相似度矩阵中获取当前备选商品和当前已评分商品间的相似度
val simScore = getProductsSimScore( candidateProduct, userRecentlyRating._1, simProducts )
if( simScore > 0.4 ){
// 按照公式进行加权计算,得到基础评分
scores += ( (candidateProduct, simScore * userRecentlyRating._2) )
if( userRecentlyRating._2 > 3 ){
increMap(candidateProduct) = increMap.getOrDefault(candidateProduct, 0) + 1
} else {
decreMap(candidateProduct) = decreMap.getOrDefault(candidateProduct, 0) + 1
}
}
}
// 根据公式计算所有的推荐优先级,首先以productId做groupby
scores.groupBy(_._1).map{
case (productId, scoreList) =>
( productId, scoreList.map(_._2).sum/scoreList.length + log(increMap.getOrDefault(productId, 1)) - log(decreMap.getOrDefault(productId, 1)) )
}
// 返回推荐列表,按照得分排序
.toArray
.sortWith(_._2>_._2)
}
def getProductsSimScore(product1: Int, product2: Int,
simProducts: scala.collection.Map[Int, scala.collection.immutable.Map[Int, Double]]): Double ={
simProducts.get(product1) match {
case Some(sims) => sims.get(product2) match {
case Some(score) => score
case None => 0.0
}
case None => 0.0
}
}
// 自定义log函数,以N为底
def log(m: Int): Double = {
val N = 10
math.log(m)/math.log(N)
}
// 写入mongodb
def saveDataToMongoDB(userId: Int, streamRecs: Array[(Int, Double)])(implicit mongoConfig: MongoConfig): Unit ={
val streamRecsCollection = ConnHelper.mongoClient(mongoConfig.db)(STREAM_RECS)
// 按照userId查询并更新
streamRecsCollection.findAndRemove( MongoDBObject( "userId" -> userId ) )
streamRecsCollection.insert( MongoDBObject( "userId" -> userId,
"recs" -> streamRecs.map(x=>MongoDBObject("productId"->x._1, "score"->x._2)) ) )
}
}
bin/zkServer.sh start
bin/kafka-server-start.sh -daemon ./config/server.properties
public class Application {
public static void main(String[] args){
String brokers = "localhost:9092";
String zookeepers = "localhost:2181";
// 定义输入和输出的topic
String from = "log";
String to = "recommender";
// 定义kafka streaming的配置
Properties settings = new Properties();
settings.put(StreamsConfig.APPLICATION_ID_CONFIG, "logFilter");
settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, zookeepers);
StreamsConfig config = new StreamsConfig(settings);
// 拓扑建构器
TopologyBuilder builder = new TopologyBuilder();
// 定义流处理的拓扑结构
builder.addSource("SOURCE", from)
.addProcessor("PROCESS", () -> new LogProcessor(), "SOURCE")
.addSink("SINK", to, "PROCESS");
KafkaStreams streams = new KafkaStreams(builder, config);
streams.start();
}
}
public class LogProcessor implements Processor<byte[],byte[]> {
private ProcessorContext context;
public void init(ProcessorContext context) {
this.context = context;
}
public void process(byte[] dummy, byte[] line) {
String input = new String(line);
// 根据前缀过滤日志信息,提取后面的内容
if(input.contains("PRODUCT_RATING_PREFIX:")){
System.out.println("product rating coming!!!!" + input);
input = input.split("PRODUCT_RATING_PREFIX:")[1].trim();
context.forward("logProcessor".getBytes(), input.getBytes());
}
}
public void punctuate(long timestamp) {
}
public void close() {
}
}
agent.sources = exectail
agent.channels = memoryChannel
agent.sinks = kafkasink
# For each one of the sources, the type is defined
agent.sources.exectail.type = exec
# 下面这个路径是需要收集日志的绝对路径,改为自己的日志目录
agent.sources.exectail.command = tail –f
/mnt/d/Projects/BigData/ECommerceRecommenderSystem/businessServer/src/main/log/agent.log
agent.sources.exectail.interceptors=i1
agent.sources.exectail.interceptors.i1.type=regex_filter
# 定义日志过滤前缀的正则
agent.sources.exectail.interceptors.i1.regex=.+PRODUCT_RATING_PREFIX.+
# The channel can be defined as follows.
agent.sources.exectail.channels = memoryChannel
# Each sink's type must be defined
agent.sinks.kafkasink.type = org.apache.flume.sink.kafka.KafkaSink
agent.sinks.kafkasink.kafka.topic = log
agent.sinks.kafkasink.kafka.bootstrap.servers = localhost:9092
agent.sinks.kafkasink.kafka.producer.acks = 1
agent.sinks.kafkasink.kafka.flumeBatchSize = 20
#Specify the channel the sink should use
agent.sinks.kafkasink.channel = memoryChannel
# Each channel's type is defined.
agent.channels.memoryChannel.type = memory
# Other config values specific to each type of channel(sink or source)
# can be defined as well
# In this case, it specifies the capacity of the memory channel
agent.channels.memoryChannel.capacity = 10000
配置好后,启动flume:
./bin/flume-ng agent -c ./conf/ -f ./conf/log-kafka.properties -n agent -Dflume.root.logger=INFO,console
// 载入商品数据集
val productTagsDF = spark
.read
.option("uri",mongoConfig.uri)
.option("collection",MONGODB_PRODUCT_COLLECTION)
.format("com.mongodb.spark.sql")
.load()
.as[Product]
.map(x => (x.productId, x.name, x.genres.map(c => if(c == '|') ' ' else c)))
.toDF("productId", "name", "tags").cache()
// 实例化一个分词器,默认按空格分
val tokenizer = new Tokenizer().setInputCol("tags").setOutputCol("words")
// 用分词器做转换
val wordsData = tokenizer.transform(productTagsDF)
// 定义一个HashingTF工具
val hashingTF = new HashingTF().setInputCol("words").setOutputCol("rawFeatures").setNumFeatures(200)
// 用 HashingTF 做处理
val featurizedData = hashingTF.transform(wordsData)
// 定义一个IDF工具
val idf = new IDF().setInputCol("rawFeatures").setOutputCol("features")
// 将词频数据传入,得到idf模型(统计文档)
val idfModel = idf.fit(featurizedData)
// 用tf-idf算法得到新的特征矩阵
val rescaledData = idfModel.transform(featurizedData)
// 从计算得到的 rescaledData 中提取特征向量
val productFeatures = rescaledData.map{
case row => ( row.getAs[Int]("productId"),row.getAs[SparseVector]("features").toArray )
}
.rdd
.map(x => {
(x._1, new DoubleMatrix(x._2) )
})
val ratingDF = spark.read
.option("uri", mongoConfig.uri)
.option("collection", MONGODB_RATING_COLLECTION)
.format("com.mongodb.spark.sql")
.load()
.as[Rating]
.map(x=> (x.userId, x.productId, x.score) )
.toDF("userId", "productId", "rating")
// 统计每个商品的评分个数,并通过内连接添加到 ratingDF 中
val numRatersPerProduct = ratingDF.groupBy("productId").count()
val ratingWithCountDF = ratingDF.join(numRatersPerProduct, "productId")
// 将商品评分按 userId 两两配对,可以统计两个商品被同一用户做出评分的次数
val joinedDF = ratingWithCountDF.join(ratingWithCountDF, "userId")
.toDF("userId", "product1", "rating1", "count1", "product2", "rating2", "count2")
.select("userId", "product1", "count1", "product2", "count2")
joinedDF.createOrReplaceTempView("joined")
val cooccurrenceDF = spark.sql(
"""
|select product1
|, product2
|, count(userId) as coocount
|, first(count1) as count1
|, first(count2) as count2
|from joined
|group by product1, product2
""".stripMargin
).cache()
val simDF = cooccurrenceDF.map{ row =>
// 用同现的次数和各自的次数,计算同现相似度
val coocSim = cooccurrenceSim( row.getAs[Long]("coocount"), row.getAs[Long]("count1"), row.getAs[Long]("count2") )
( row.getAs[Int]("product1"), ( row.getAs[Int]("product2"), coocSim ) )
}
.rdd
.groupByKey()
.map{
case (productId, recs) =>
ProductRecs( productId,
recs.toList
.filter(x=>x._1 != productId)
.sortWith(_._2>_._2)
.map(x=>Recommendation(x._1,x._2))
.take(MAX_RECOMMENDATION)
)
}
.toDF()
def cooccurrenceSim(cooCount: Long, count1: Long, count2: Long): Double ={
cooCount / math.sqrt( count1 * count2 )
}
java -cp kafkastream.jar com.atguigu.kafkastream.Application linux:9092 linux:2181 log recommender
agent.sources = exectail
agent.channels = memoryChannel
agent.sinks = kafkasink
# For each one of the sources, the type is defined
agent.sources.exectail.type = exec
agent.sources.exectail.command = tail -f /home/bigdata/cluster/apache-tomcat-8.5.23/logs/catalina.out
agent.sources.exectail.interceptors=i1
agent.sources.exectail.interceptors.i1.type=regex_filter
agent.sources.exectail.interceptors.i1.regex=.+PRODUCT_RATING_PREFIX.+
# The channel can be defined as follows.
agent.sources.exectail.channels = memoryChannel
# Each sink's type must be defined
agent.sinks.kafkasink.type = org.apache.flume.sink.kafka.KafkaSink
agent.sinks.kafkasink.kafka.topic = log
agent.sinks.kafkasink.kafka.bootstrap.servers = linux:9092
agent.sinks.kafkasink.kafka.producer.acks = 1
agent.sinks.kafkasink.kafka.flumeBatchSize = 20
#Specify the channel the sink should use
agent.sinks.kafkasink.channel = memoryChannel
# Each channel's type is defined.
agent.channels.memoryChannel.type = memory
# Other config values specific to each type of channel(sink or source)
# can be defined as well
# In this case, it specifies the capacity of the memory channel
agent.channels.memoryChannel.capacity = 10000
bin/flume-ng agent -c ./conf/ -f ./conf/log-kafka.properties -n agent
bin/spark-submit --class com.atguigu.streamingRecommender.StreamingRecommender streamingRecommender-1.0-SNAPSHOT.jar
type=command
command=/home/bigdata/cluster/spark-2.1.1-bin-hadoop2.7/bin/spark-submit --class com.atguigu.offline.RecommenderTrainerApp
offlineRecommender-1.0-SNAPSHOT.jar
type=command
command=/home/bigdata/cluster/spark-2.1.1-bin-hadoop2.7/bin/spark-submit --class com.atguigu.statisticsRecommender.StatisticsApp
statisticsRecommender-1.0-SNAPSHOT.jar