需要创建 idf 值字典,将单词与其 idf 值相关联



我了解如何使用矢量化器获取idf值和词汇表。对于词汇表,单词的频率是值,单词是字典的键,但是,我希望值是idf值。

我无法尝试任何东西,因为我不知道如何使用 sklearn。

from sklearn.feature_extraction.text import TfidfVectorizer
# list of text documents
text = ["The quick brown fox jumped over the lazy dog.",
        "The dog.",
        "The fox"]
# create the transform
vectorizer = TfidfVectorizer()
# tokenize and build vocab
vectorizer.fit(text)
# summarize
print(vectorizer.vocabulary_)
print(vectorizer.idf_)
# encode document
vector = vectorizer.transform([text[0]])
# summarize encoded vector
print(vector.shape)
print(vector.toarray())

上面提供的代码是我最初尝试使用的代码。

从那以后,我想出了一个不使用scikit的新解决方案:

            for string in text_array: 
                for word in string:
                    if word not in total_dict.keys(): # build up a word frequency in the dictionary
                        total_dict[word] = 1
                    else:
                        total_dict[word] += 1
            for word in total_dict.keys(): # calculate the tf-idf of each word in the dictionary using this url: https://nlpforhackers.io/tf-idf/
                total_dict[word] = math.log(len(text_array) / float(1 + total_dict[word]))
                print("word", word, ":" , total_dict[word])

让我知道上面的代码片段是否足以合理估计正在发生的事情。我包含一个指向我用于指导的链接。

第一次可以直接使用 vectorizer.fit_transform(text)。它的作用是根据文本中的所有单词/标记构建词汇集。

然后,您可以使用vectorizer.transform(anothertext)矢量化另一个文本,其映射与前一个文本相同。

更多解释:

fit()是从训练集中学习词汇和IDF。 transform()是根据上一个fit()学到的词汇来转换文档。

所以你应该只做一次fit(),并且可以变换很多次。

最新更新