Spark - 如何根据项目评级创建稀疏矩阵

guz*_*u92 4 scala recommendation-engine sparse-matrix apache-spark

我的问题相当于数据框中与R相关的帖子Create Sparse Matrix,除了我想在Spark上执行相同的操作(最好是在Scala中).

data.txt文件中的数据样本,从中创建稀疏矩阵:

UserID MovieID  Rating
2      1       1
3      2       1
4      2       1
6      2       1
7      2       1
Run Code Online (Sandbox Code Playgroud)

所以最后列是电影ID,行是用户ID

    1   2   3   4   5   6   7
1   0   0   0   0   0   0   0
2   1   0   0   0   0   0   0
3   0   1   0   0   0   0   0
4   0   1   0   0   0   0   0
5   0   0   0   0   0   0   0
6   0   1   0   0   0   0   0
7   0   1   0   0   0   0   0
Run Code Online (Sandbox Code Playgroud)

我实际上是通过mapdata.txt文件(没有标题)进行RDD转换来将值转换为Integer,但后来......我找不到用于稀疏矩阵创建的函数.

val data = sc.textFile("/data/data.txt")
val ratings = data.map(_.split(',') match { case Array(user, item, rate) =>
    Rating(user.toInt, item.toInt, rate.toInt)
  })
...?
Run Code Online (Sandbox Code Playgroud)

zer*_*323 7

最简单的方法是映射RatingsMatrixEntries创建CoordinateMatrix:

import org.apache.spark.mllib.linalg.distributed.{CoordinateMatrix, MatrixEntry}

val mat = new CoordinateMatrix(ratings.map {
    case Rating(user, movie, rating) => MatrixEntry(user, movie, rating)
})
Run Code Online (Sandbox Code Playgroud)

CoordinateMatrix可进一步转化为BlockMatrix,IndexedRowMatrix,RowMatrix使用toBlockMatrix,toIndexedRowMatrix,toRowMatrix分别.