CountVectorizer,在第二个tim中使用相同的词汇

2024-10-02 12:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是我的数据集:

anger,happy food food
anger,dog food food
disgust,food happy food
disgust,food dog food
neutral,food food happy
neutral,food food dog

第二,这是我的代码,在这里我使用CountVectorizer类执行一包单词。在

^{pr2}$

正如您在这里看到的:model.transform(df).show(truncate=False)和{}工作得非常好。在

+-------+-------------------+-------------------+
|classes|tags               |vectors            |
+-------+-------------------+-------------------+
|0.0    |[happy, food, food]|(3,[0,1],[2.0,1.0])|
|0.0    |[dog, food, food]  |(3,[0,2],[2.0,1.0])|
|1.0    |[food, happy, food]|(3,[0,1],[2.0,1.0])|
|1.0    |[food, dog, food]  |(3,[0,2],[2.0,1.0])|
|6.0    |[food, food, happy]|(3,[0,1],[2.0,1.0])|
|6.0    |[food, food, dog]  |(3,[0,2],[2.0,1.0])|
+-------+-------------------+-------------------+
['dog', 'food', 'happy']

现在,如果我想再次使用相同的词汇表执行新元素的向量器,那么在python中如何做到这一点呢?在

例如

anger, happy dog food

会的

|0.0    |[happy, dog, food]|(3,[0,1, 2],[1.0,1.0,1.0])|

我在文档中读过exist CountVectorizerModel,它允许加载exist词汇表。但没有任何关于这件事的文件。在

这对我来说非常重要,因为如果我需要对一个新元素进行分类,我需要向量的相同顺序,以便使用我的分类器的相同模型。在

我试过这样的方法:

CountVectorizerModel(vocabulary)

但没用。在

编辑1

我目前使用的是Spark 1.6.1


Tags: 数据词汇表代码food单词向量existhappy
1条回答
网友
1楼 · 发布于 2024-10-02 12:28:33

spark2.0开始,它可以在pyspark中使用,它就像持久化和加载其他spark-ml模型一样。在

好,我们先创建一个模型:

from pyspark.ml.feature import CountVectorizer, CountVectorizerModel

# Input data: Each row is a bag of words with a ID.
df = spark.createDataFrame([
    (0, "a b c".split(" ")),
    (1, "a b b c a".split(" "))
], ["id", "words"])

# fit a CountVectorizerModel from the corpus.
cv = CountVectorizer(inputCol="words", outputCol="features", vocabSize=3, minDF=2.0)

model = cv.fit(df)

result = model.transform(df)
result.show(truncate=False)
# + -+       -+            -+
# |id |words          |features                 |
# + -+       -+            -+
# |0  |[a, b, c]      |(3,[0,1,2],[1.0,1.0,1.0])|
# |1  |[a, b, b, c, a]|(3,[0,1,2],[2.0,2.0,1.0])|
# + -+       -+            -+

然后坚持下去:

^{pr2}$

现在可以加载并使用它:

same_model = CountVectorizerModel.load("/tmp/count_vec_model")
same_model.transform(df).show(truncate=False)
# + -+       -+            -+
# |id |words          |features                 |
# + -+       -+            -+
# |0  |[a, b, c]      |(3,[0,1,2],[1.0,1.0,1.0])|
# |1  |[a, b, b, c, a]|(3,[0,1,2],[2.0,2.0,1.0])|
# + -+       -+            -+

有关详细信息,请参阅以下有关Saving and loading spark-ml models/pipelines的文档。在

模型创建代码示例可以在官方文档中找到。在

相关问题 更多 >

    热门问题