gpt4 book ai didi

apache-spark - 使用 Spark CountVectorizer 时如何获取 "normalize"向量值?

转载 作者:行者123 更新时间:2023-12-02 01:04:07 25 4
gpt4 key购买 nike

CountVectorizerCountVectorizerModel 通常创建如下所示的稀疏特征向量:

(10,[0,1,4,6,8],[2.0,1.0,1.0,1.0,1.0])

这基本上表示词汇表的总大小为 10,当前文档有 5 个唯一元素,在特征向量中,这 5 个唯一元素分别位于 0、1、4、6 和 8。另外,其中之一元素出现两次,因此值为 2.0。

现在,我想“规范化”上面的特征向量,让它看起来像这样,

(10,[0,1,4,6,8],[0.3333,0.1667,0.1667,0.1667,0.1667])

即,每个值除以 6,即所有元素的总数。例如,0.3333 = 2.0/6

那么这里有没有办法高效地做到这一点?

谢谢!

最佳答案

你可以使用Normalizer

class pyspark.ml.feature.Normalizer(*args, **kwargs)

Normalize a vector to have unit norm using the given p-norm.

1-norm

from pyspark.ml.linalg import SparseVector
from pyspark.ml.feature import Normalizer

df = spark.createDataFrame([
(SparseVector(10,[0,1,4,6,8],[2.0,1.0,1.0,1.0,1.0]), )
], ["features"])

Normalizer(inputCol="features", outputCol="features_norm", p=1).transform(df).show(1, False)
# +--------------------------------------+---------------------------------------------------------------------------------------------------------------------+
# |features |features_norm |
# +--------------------------------------+---------------------------------------------------------------------------------------------------------------------+
# |(10,[0,1,4,6,8],[2.0,1.0,1.0,1.0,1.0])|(10,[0,1,4,6,8],[0.3333333333333333,0.16666666666666666,0.16666666666666666,0.16666666666666666,0.16666666666666666])|
# +--------------------------------------+---------------------------------------------------------------------------------------------------------------------+

关于apache-spark - 使用 Spark CountVectorizer 时如何获取 "normalize"向量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48713954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com