PySpark 以密集向量形式读入文本文件

PySpark read in a textfile as Dense vectors

我正在使用 PySpark 并尝试加载以下格式的文件,其中每一行都是一个计数向量

[1394, 56692, 0, 10, 22]
[0, 0, 0, 0, 0]
[2235, 123, 678, 0, 999]

我正在尝试使用 sc.textFile(path/to/counts.txt) 将其加载到 Spark 中。如何将文件的每一行转换为类似于以下格式的 pyspark ML 向量?我假设它是一个 lambda 函数,但不确定如何将字符串转换为 ML Vector。

from pyspark.ml.linalg import Vectors as MLVectors
data = [(MLVectors.dense([0.0, 1.0, 0.0, 7.0, 0.0]),), 
(MLVectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),), (MLVectors.dense([4.0, 0.0, 
0.0, 6.0, 7.0]),)]

您可以用 map 处理每一行

import re
from pyspark.ml.linalg import Vectors as MLVectors
rdd = sc.textFile("path/to/counts.txt")\
    .map(lambda l: MLVectors.dense([int(x) for x in (re.sub("[\[\]]", "", l).split(","))]))
rdd.take(3)

    [DenseVector([1394.0, 56692.0, 0.0, 10.0, 22.0]),
     DenseVector([0.0, 0.0, 0.0, 0.0, 0.0]),
     DenseVector([2235.0, 123.0, 678.0, 0.0, 999.0])]

数据帧

import pyspark.sql.functions as psf
from pyspark.ml.feature import VectorAssembler
df = spark.read.csv("path/to/counts.txt")
df = df.select([psf.regexp_replace(c, '[\]\[]', '').cast("float").alias(c) for c in df.columns])
va = VectorAssembler(inputCols=df.columns, outputCol="vector")
df2 = va.transform(df)