如何增加CountVectorizer中某个单词的权重

我有一个已经分词的文档,然后我拿另一个文档来比较它们,通过计算它们的余弦相似度来进行比较。

然而,在计算相似度之前,我想先增加其中一个单词的权重。我考虑通过将该单词的计数翻倍来实现,但不知道具体该怎么做。

假设我有以下内容…

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的权重,该怎么做呢?我认为可以通过增加单词计数来实现,但我不知道如何增加这个计数。


回答:

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

from scipy.spatial.distance import cosineimport numpy as npword_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)] = valuefor 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}会从余弦相似度中移除“test”,但word_weights = {'test': 1.5}会使“test”的权重比其他单词增加50%。你也可以根据需要包含多个条目,例如word_weights = {'test': 1.5, 'something': 2}将调整“test”和“something”的权重,相对于其他单词。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注