使用 sklearn 计算 TF-IDF for variable-n-gram in python



问题: 使用scikit-learn查找特定词汇的可变n-gram的命中次数。

解释。 我从这里得到了例子。

想象一下,我有一个语料库,我想找出有多少点击(计数(具有如下所示的词汇表:

myvocabulary = [(window=4, words=['tin', 'tan']),
(window=3, words=['electrical', 'car'])
(window=3, words=['elephant','banana'])

我在这里所说的窗口是单词可以出现的单词范围的长度。 如下:

"锡潭"被击中(4个字以内(

"铁皮狗谭"被击中(4个字以内(

'锡狗猫谭被击中(4字以内(

"锡车日食棕褐色"没有命中。 锡和棕褐看起来相距超过4个字。

我只想计算文本中出现的次数(window=4,words=['tin','tan'](以及所有其他文本的次数相同,然后将结果添加到熊猫中以计算tf-idf算法。 我只能找到这样的东西:

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(vocabulary = myvocabulary, stop_words = 'english')
tfs = tfidf.fit_transform(corpus.values())

其中词汇是一个简单的字符串列表,是单个单词或几个单词。

除了来自Scikitlearn:

class sklearn.feature_extraction.text.CountVectorizer
ngram_range : tuple (min_n, max_n)

要提取的不同 n 元语法的 n 值范围的下限和上限。将使用 n 的所有值,以便使用 min_n <= n <= max_n。

也无济于事。

有什么想法吗?

我不确定是否可以使用CountVectorizerTfidfVectorizer来完成此操作。我已经编写了自己的函数来执行此操作,如下所示:

import pandas as pd
import numpy as np
import string 
def contained_within_window(token, word1, word2, threshold):
word1 = word1.lower()
word2 = word2.lower()
token = token.translate(str.maketrans('', '', string.punctuation)).lower()
if (word1 in token) and word2 in (token):
word_list = token.split(" ")
word1_index = [i for i, x in enumerate(word_list) if x == word1]
word2_index = [i for i, x in enumerate(word_list) if x == word2]
count = 0
for i in word1_index:
for j in word2_index:
if np.abs(i-j) <= threshold:
count=count+1
return count
return 0

样本:

corpus = [
'This is the first document. And this is what I want',
'This document is the second document.',
'And this is the third one.',
'Is this the first document?',
'I like coding in sklearn',
'This is a very good question'
]
df = pd.DataFrame(corpus, columns=["Test"])

您的df将如下所示:

Test
0   This is the first document. And this is what I...
1   This document is the second document.
2   And this is the third one.
3   Is this the first document?
4   I like coding in sklearn
5   This is a very good question

现在,您可以按如下方式应用contained_within_window

sum(df.Test.apply(lambda x: contained_within_window(x,word1="this", word2="document",threshold=2)))

你会得到:

2

您可以运行一个for循环来检查不同的实例。 而你这个来构建你的熊猫df并应用TfIdf,这是直截了当的。

相关内容

最新更新