【问题标题】:How to increase weight of a word for CountVectorizer如何为 CountVectorizer 增加单词的权重
【发布时间】:2018-04-06 06:50:30
【问题描述】:

我有一个已标记化的文档,然后我获取另一个文档并通过计算它们的 余弦相似度来比较两者。

但是,在计算它们的相似度之前,我想事先增加其中一个词的权重。我正在考虑通过将该单词的计数加倍来做到这一点,但我不知道该怎么做。

假设我有以下...

text = [
    "This is a test",
    "This is something else",
    "This is also a test"
]

test = ["This is something"]

接下来我为两组文档定义停用词并调用CountVectorizer

stopWords = set(stopwords.words('english'))

vectorizer = CountVectorizer(stop_words=stopWords)

trainVectorizerArray = vectorizer.fit_transform(text).toarray()
testVectorizerArray = vectorizer.transform(test).toarray()

在下一部分我计算 余弦相似度...

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print(vector)
    for testV in testVectorizerArray:
        print(testV)
        cosine = cosine_function(vector, testV)
        print(cosine)

但是,在我计算相似度之前,如何增加其中一个词的权重。假设在这个例子中我想增加something 的权重,我该怎么做呢?我认为您可以通过增加字数来做到这一点,但我不知道如何增加。

【问题讨论】:

    标签: python machine-learning scikit-learn tf-idf


    【解决方案1】:

    我认为最简单的方法是将get_feature_names 函数与scipy.spatial.distance 中的cosine 函数结合使用CountVectorizer。但请注意,这计算的是余弦距离而不是相似度,因此如果您只对相似度感兴趣,则必须使用similarity = 1-distance。用你的例子

    from scipy.spatial.distance import cosine
    import numpy as np
    
    word_weights = {'something': 2}
    feature_names = vectorizer.get_feature_names()
    weights = np.ones(len(feature_names))
    
    for key, value in word_weights.items():
        weights[feature_names.index(key)] = value
    
    for vector in trainVectorizerArray:
        print(vector)
        for testV in testVectorizerArray:
            print(testV)
            cosine_unweight = cosine(vector, testV)
            cosine_weighted = cosine(vector, testV, w=weights)
            print(cosine_unweight, cosine_weighted)
    

    根据要求,对word_weights 字典进行更多解释。这是您分配给其他单词的权重。每个权重都设置为1,除非您在word_weights 字典中添加一个条目,因此word_weights = {'test': 0} 将从余弦相似度中删除“测试”,但word_weights = {'test': 1.5} 与其他相比将增加50% 的权重字。如果需要,您还可以包含多个条目,例如word_weights = {'test': 1.5, 'something': 2} 将调整“test”和“something”与其他词相比的权重。

    【讨论】:

    • 您介意解释一下2{'something': 2} 中代表什么吗?
    • 编辑了我的答案以包含它。
    猜你喜欢
    • 2018-08-29
    • 2020-06-14
    • 2018-05-26
    • 2020-02-09
    • 2016-10-18
    • 2022-01-05
    • 1970-01-01
    • 2021-06-28
    • 2019-12-11
    相关资源
    最近更新 更多