如何在pysp的TFIDF数据帧上应用SVD

2024-09-28 01:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经应用了pyspark tf idf函数并得到了以下结果。在

| features |
|----------|
| (35,[7,9,11,12,19,26,33],[1.2039728043259361,1.2039728043259361,1.2039728043259361,1.6094379124341003,1.6094379124341003,1.6094379124341003,1.6094379124341003])  |
| (35,[0,2,4,5,6,11,22],[0.9162907318741551,0.9162907318741551,1.2039728043259361,1.2039728043259361,1.2039728043259361,1.2039728043259361,1.6094379124341003]) |

因此,一个数据帧有1列(features),其中包含sparsevector作为行。在

现在我想从这个数据帧构建IndexRowMatrix,这样我就可以运行这里描述的svd函数https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html?highlight=svd#pyspark.mllib.linalg.distributed.IndexedRowMatrix.computeSVD

我尝试过以下方法,但没有成功:

^{pr2}$

我使用RowMatrix是因为要构建它,我不需要提供元组,但我甚至不能构建RowMatrix。IndexedRowMatrix对我来说会更困难。在

那么如何在pyspark中tf-idf数据帧的输出上运行indexedrowmmatrix?在


Tags: 数据函数httpsapachetfsparkpysparkfeatures
2条回答

我能解决它。 因为错误提示RowMatrix不接受pyspark.ml.linalg.SparseVector向量,所以我把这个向量转换成pyspark.mllib.linalg,注意ml和{}。下面是将TF-IDF输出转换为RowMatrix的代码片段,您可以对其应用computeSVD方法。在

from pyspark.mllib.linalg import Vectors
mat = RowMatrix(df.rdd.map(lambda v: Vectors.dense(v.rawFeatures.toArray()) ))

我已经转换为稠密矩阵,但是您可以编写一些额外的代码来将ml.linalg.SparseVector转换成{}

请原谅我没有在原始答案中发表评论,我还没有必要的声誉分数。为了加快速度,最好创建一个mllib.linalg.SparseVector。如果对其进行了以下修改:

from pyspark.mllib.linalg import Vectors
mat = RowMatrix(df.rdd.map(lambda v: Vectors.fromML(v.rawFeatures)))

相关问题 更多 >

    热门问题