2017-05-25 133 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"))