使用 Spark 将句子编码为序列模型
Encode sentence as sequence model with Spark
我正在做文本分类,我使用 pyspark.ml.feature.Tokenizer
来标记文本。但是 CountVectorizer
将标记化的单词列表转换为词袋模型,而不是序列模型。
假设我们有以下包含列 id 和文本的 DataFrame:
id | texts
----|----------
0 | Array("a", "b", "c")
1 | Array("a", "b", "b", "c", "a")
each row in texts is a document of type Array[String]. Invoking fit of CountVectorizer produces a CountVectorizerModel with vocabulary (a, b, c). Then the output column “vector” after transformation contains:
id | texts | vector
----|---------------------------------|---------------
0 | Array("a", "b", "c") | (3,[0,1,2],[1.0,1.0,1.0])
1 | Array("a", "b", "b", "c", "a") | (3,[0,1,2],[2.0,2.0,1.0])
我想要的是(第 1 行)
Array("a", "b", "b", "c", "a") | [0, 1, 1, 2, 0]
那么我是否可以将自定义函数并行写入 运行 编码?或者除了使用 spark 之外,还有其他可以并行执行的库吗?
您可以使用 StringIndexer
和 explode
:
df = spark_session.createDataFrame([
Row(id=0, texts=["a", "b", "c"]),
Row(id=1, texts=["a", "b", "b", "c", "a"])
])
data = df.select("id", explode("texts").alias("texts"))
indexer = StringIndexer(inputCol="texts", outputCol="indexed", stringOrderType="alphabetAsc")
indexer\
.fit(data)\
.transform(data)\
.groupBy("id")\
.agg(collect_list("texts").alias("texts"), collect_list("indexed").alias("vector"))\
.show(20, False)
输出:
+---+---------------+-------------------------+
|id |texts |vector |
+---+---------------+-------------------------+
|0 |[a, b, c] |[0.0, 1.0, 2.0] |
|1 |[a, b, b, c, a]|[0.0, 1.0, 1.0, 2.0, 0.0]|
+---+---------------+-------------------------+
我正在做文本分类,我使用 pyspark.ml.feature.Tokenizer
来标记文本。但是 CountVectorizer
将标记化的单词列表转换为词袋模型,而不是序列模型。
假设我们有以下包含列 id 和文本的 DataFrame:
id | texts
----|----------
0 | Array("a", "b", "c")
1 | Array("a", "b", "b", "c", "a")
each row in texts is a document of type Array[String]. Invoking fit of CountVectorizer produces a CountVectorizerModel with vocabulary (a, b, c). Then the output column “vector” after transformation contains:
id | texts | vector
----|---------------------------------|---------------
0 | Array("a", "b", "c") | (3,[0,1,2],[1.0,1.0,1.0])
1 | Array("a", "b", "b", "c", "a") | (3,[0,1,2],[2.0,2.0,1.0])
我想要的是(第 1 行)
Array("a", "b", "b", "c", "a") | [0, 1, 1, 2, 0]
那么我是否可以将自定义函数并行写入 运行 编码?或者除了使用 spark 之外,还有其他可以并行执行的库吗?
您可以使用 StringIndexer
和 explode
:
df = spark_session.createDataFrame([
Row(id=0, texts=["a", "b", "c"]),
Row(id=1, texts=["a", "b", "b", "c", "a"])
])
data = df.select("id", explode("texts").alias("texts"))
indexer = StringIndexer(inputCol="texts", outputCol="indexed", stringOrderType="alphabetAsc")
indexer\
.fit(data)\
.transform(data)\
.groupBy("id")\
.agg(collect_list("texts").alias("texts"), collect_list("indexed").alias("vector"))\
.show(20, False)
输出:
+---+---------------+-------------------------+
|id |texts |vector |
+---+---------------+-------------------------+
|0 |[a, b, c] |[0.0, 1.0, 2.0] |
|1 |[a, b, b, c, a]|[0.0, 1.0, 1.0, 2.0, 0.0]|
+---+---------------+-------------------------+