【问题标题】:How to calculate TF-IDF values of noun documents excluding spaCy stop words?如何计算不包括 spaCy 停用词的名词文档的 TF-IDF 值?
【发布时间】:2022-07-25 19:12:41
【问题描述】:

我有一个数据框,df,以 textcleaned_textnouns 作为列名。 textcleaned_text 包含字符串文档,nouns 是从 cleaned_text 列中提取的名词列表。 df.shape = (1927, 3).

我正在尝试计算 df 内所有文档的 TF-IDF仅适用于名词,不包括 spaCy 停用词


我尝试了什么?

import spacy
from spacy.lang.en import English

nlp = spacy.load('en_core_web_sm')

# subclass to modify stop word lists recommended from spaCy version 3.0 onwards
excluded_stop_words = {'down'}
included_stop_words = {'dear', 'regards'}

class CustomEnglishDefaults(English.Defaults):
    stop_words = English.Defaults.stop_words.copy()
    stop_words -= excluded_stop_words
    stop_words |= included_stop_words
    
class CustomEnglish(English):
    Defaults = CustomEnglishDefaults
# function to extract nouns from cleaned_text column, excluding spaCy stowords.
nlp = CustomEnglish()

def nouns(text):
    doc = nlp(text)
    return [t for t in doc if t.pos_ in ['NOUN'] and not t.is_stop and not t.is_punct]
# calculate TF-IDF values for nouns, excluding spaCy stopwords.
from sklearn.feature_extraction.text import TfidfVectorizer

documents = df.cleaned_text

tfidf = TfidfVectorizer(stop_words=CustomEnglish)
X = tfidf.fit_transform(documents)

我期待什么?

我希望有一个按降序排列的元组列表的输出; nouns = [('noun_1', tf-idf_1), ('noun_2', tf-idf_2), ...]nouns 中的所有名词都应与df.nouns 中的名词一致(这是为了检查我是否走对了路)。


我的问题是什么?

我对如何应用 TfidfVectorizer 以便仅计算从 cleaned_text 中提取的名词的 TF-IDF 值感到困惑。我也不确定 SkLearn TfidfVectorizer 是否可以按照我的预期计算 TF-IDF。

【问题讨论】:

    标签: python-3.x list dataframe nlp spacy


    【解决方案1】:

    不确定您是否仍在寻找解决方案。这是您可能想要继续使用的选项。

    首先,默认情况下,TF_IDF 会考虑整个单词集,而不仅仅是名词。因此,您需要实现自定义 TF_IDF 函数以仅将结果应用于名词。以下是关于 TF_IDF 如何在内部工作的一个很好的参考:https://www.askpython.com/python/examples/tf-idf-model-from-scratch

    您可以在已提取的名词列表上运行它,而不是为句子/文档的所有单词运行 tf_idf 函数(如上述 url 中所应用的),即,只需将代码更改为:

    def tf_idf(sentence):
        tf_idf_vec = np.zeros((len(word_set),))
        for word in sentence:
            tf = termfreq(sentence,word)
            idf = inverse_doc_freq(word)
             
            value = tf*idf
            tf_idf_vec[index_dict[word]] = value 
        return tf_idf_vec

    到:

    def tf_idf(sentence, nouns):
        values = []
        for word in nouns:
            tf = termfreq(sentence,word)
            idf = inverse_doc_freq(word)
             
            value = tf*idf
            values.append(value)
        return tf_idf_vec, values

    您现在有一个与每个句子的“名词”列表相对应的“值”列表。希望这是有道理的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2016-03-30
      • 2019-04-07
      • 1970-01-01
      • 2019-02-19
      • 2017-07-05
      相关资源
      最近更新 更多