如何为CountVectorizer增加单词的重量

Bol*_*boa 4 python machine-learning tf-idf scikit-learn

我有一个文档,我被标记,然后我采取另一个文件,我通过计算它们的余弦相似性来比较两者.

但是,在我计算它们的相似度之前,我想提前增加其中一个词的权重.我想通过加倍那个词的数量来做到这一点,但我不知道该怎么做.

假设我有以下......

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

test = ["This is something"]
Run Code Online (Sandbox Code Playgroud)

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

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

vectorizer = CountVectorizer(stop_words=stopWords)

trainVectorizerArray = vectorizer.fit_transform(text).toarray()
testVectorizerArray = vectorizer.transform(test).toarray()
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

pim*_*314 5

我认为最简单的方法是将get_feature_names函数CountVectorizercosine函数结合使用scipy.spatial.distance.但请注意,这会计算余弦距离而不是相似度,因此如果您只是对相似性感兴趣,则必须使用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)
Run Code Online (Sandbox Code Playgroud)

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