[英]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]|
+---+---------------+-------------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.