knn(k-NearestNeighbor) with scala

  • descending order
  def calculateSimilarity(video: RDD[(String, Set[String])], myFunc: (Set[String], Set[String]) => Double): RDD[(String, String, Double)] = {
    video.cartesian(video).filter(f => f._1._1 != f._2._1)
    .map(f => (f._1._1, f._2._1, myFunc(f._1._2, f._2._2)))
    .filter(f => f._3 > 0).groupBy(_._1)
    .flatMap(f => f._2.toList.sortWith((a, b) => a._3 > b._3).take(100)) //k value
  }
  • ascending order
  def itemCFRecommend(videoSimilarity: RDD[VideoSim], userVideos: RDD[VideoRating], r_number: Int): (RDD[UserRecd]) = {
    videoSimilarity.map(f => (f.video1, (f.video2, f.similar)))
    .join(userVideos.map(f => (f.videoID, (f.userID, f.score)))) 
      .map(f => ((f._2._2._1, f._2._1._1), f._2._2._2 * f._2._1._2)) 
      .reduceByKey((x, y) => x + y)
      .leftOuterJoin(userVideos.map(f => ((f.userID, f.videoID), 1)))
      .filter(f => f._2._2.isEmpty) 
      .map(f => (f._1._1, (f._1._2, f._2._1)))
      .groupByKey() // knn part
      .map(f => {
      val i2 = f._2.toBuffer
      val i2_2 = i2.sortBy(_._2)
      if (i2_2.length > r_number) i2_2.remove(0, i2_2.length - r_number)
      (f._1, i2_2)
    }).flatMap(f => {
      for (w <- f._2) yield (f._1, w._1, w._2)
    }).map(f => UserRecd(f._1, f._2, f._3))
  }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值