在PySpark中如何构建稀疏矩阵?

8

我是Spark的新手。我想将一个稀疏矩阵转换为用户ID-物品ID矩阵,以用于推荐引擎。我知道如何在Python中实现此操作。那么在PySpark中该怎么做呢?这是我在matrix中的操作方式。表格现在看起来像这样。

Session ID| Item ID | Rating
     1          2       1
     1          3       5

    import numpy as np

    data=df[['session_id','item_id','rating']].values
    data

    rows, row_pos = np.unique(data[:, 0], return_inverse=True)
    cols, col_pos = np.unique(data[:, 1], return_inverse=True)

    pivot_table = np.zeros((len(rows), len(cols)), dtype=data.dtype)
    pivot_table[row_pos, col_pos] = data[:, 2]

请查看SparseVector:https://spark.apache.org/docs/1.1.0/api/python/pyspark.mllib.linalg.SparseVector-class.html - Gopala
1个回答

8

就像这样:

from pyspark.mllib.linalg.distributed import CoordinateMatrix, MatrixEntry

# Create an RDD of (row, col, value) triples
coordinates = sc.parallelize([(1, 2, 1), (1, 3, 5)])
matrix = CoordinateMatrix(coordinates.map(lambda coords: MatrixEntry(*coords)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接