2017-05-25 136 views
0

是否有内置的方法来从PySpark中的密集矢量创建稀疏矢量?我这样做的方式如下:将密集矢量转换为PySpark中的稀疏矢量

Vectors.sparse(len(denseVector), [(i,j) for i,j in enumerate(denseVector) if j != 0 ]) 

满足[size,(index,data)]格式。似乎有点哈克。有没有更有效的方法来做到这一点?

回答

0
import scipy.sparse 
from pyspark.ml.linalg import Vectors, _convert_to_vector, VectorUDT 
from pyspark.sql.functions import udf, col 

如果你只有一个密集的载体,这将做到这一点:

def dense_to_sparse(vector): 
    return _convert_to_vector(scipy.sparse.csc_matrix(vector.toArray()).T) 

dense_to_sparse(densevector) 

这里的窍门是,csc_matrix.shape [1]必须等于1,所以转置向量。看一看_convert_to_vector来源:https://people.eecs.berkeley.edu/~jegonzal/pyspark/_modules/pyspark/mllib/linalg.html

更有可能的情况是你有一个DF与densevectors柱:

to_sparse = udf(dense_to_sparse, VectorUDT()) 
DF.withColumn("sparse", to_sparse(col("densevector"))