How to build a sparse matrix in PySpark?

穿精又带淫゛_ 提交于 2019-12-06 03:51:22

问题


I am new to Spark. I would like to make a sparse matrix a user-id item-id matrix specifically for a recommendation engine. I know how I would do this in python. How does one do this in PySpark? Here is how I would have done it in matrix. The table looks like this now.

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]

回答1:


Like that:

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)))


来源:https://stackoverflow.com/questions/38134370/how-to-build-a-sparse-matrix-in-pyspark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!