【问题标题】:How to hand-engineer features of TfidfVectorizer in Scikit-learn?如何在 Scikit-learn 中手动设计 TfidfVectorizer 的功能?
【发布时间】:2018-06-03 16:16:12
【问题描述】:

我正在尝试按关键字对文档进行聚类。我正在使用以下代码制作tdidf-matrix

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(max_df=.8, max_features=1000,
                             min_df=0.07, stop_words='english',
                             use_idf=True, tokenizer=tokenize_and_stem, 
                             ngram_range=(1,2))

tfidf_matrix = tfidf_vectorizer.fit_transform(documents)

print(tfidf_matrix.shape) 返回(567, 209),表示有567个文档,每个文档都有scikit-learn TdidfVectorizer检测到的209个特征词的某种混合。

现在,我使用terms = tfidf_vectorizer.get_feature_names() 获取术语列表。运行print(len(terms)) 给出209

其中许多词对于任务来说是不必要的,它们会给聚类添加噪音。我手动浏览了列表并提取了有意义的特征名称,从而产生了一个新的terms 列表。现在,运行print(len(terms)) 会得到67

但是,运行 tfidf_vectorizer.fit_transform(documents) 仍然会给出 (567, 209) 的形状,这意味着 fit_transform(documents) 函数仍然使用 209 个术语的嘈杂列表,而不是手动选择的 67 个术语列表。

如何使用 67 个手动选择的术语列表运行 tfidf_vectorizer.fit_transform(documents) 函数?我在想,也许这需要我在我机器上的 Scikit-Learn 包中添加至少一个功能,对吗?

非常感谢任何帮助。谢谢!

【问题讨论】:

    标签: python scikit-learn nlp


    【解决方案1】:

    有两种方式:

    1. 如果您已经确定了一个停用词列表(您称它们为“任务不必要的”),只需将它们放入TfidfVectorizerstop_words 参数中,以便在创建词袋时忽略它们。但是请注意,如果您将stop_words 参数设置为自定义列表,则将不再使用预定义的英语停用词。如果您想将预定义的英语列表与其他停用词结合起来,只需添加两个列表:

      from sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS
      stop_words = list(ENGLISH_STOP_WORDS) + ['your','additional', 'stopwords']
      tfidf_vectorizer = TfidfVectorizer(stop_words=stop_words) # add your other params here
      
    2. 如果你有一个固定的词汇表,并且只希望这些词被计算(即你的terms列表),只需设置TfidfVectorizervocabulary参数:

      tfidf_vectorizer = TfidfVectorizer(vocabulary=terms) # add your other params here
      

    【讨论】:

      【解决方案2】:

      我没有弄清楚如何按照我在问题中要求的级别解决问题。但是,我想出了一个适用于现在的 hacky 解决方案。

      通过执行以下操作,我能够使用我手工制作的一组术语:

      1) 从terms = tfidf_vectorizer.get_feature_names(),打印出terms

      2) 制作一个名为 unwanted_terms 的列表,并手动填写步骤 1 中不需要的术语。

      3) 在我的文档顶部,我导入停用词:

      stopwords = nltk.corpus.stopwords.words('english')
      

      将我不需要的术语列表添加到停用词:

      for item in not_needed_words_list:
          stopwords.append(item)
      

      【讨论】:

      • 另一种方法是,您可以将 TfidfVectorizer 的 'vocabulary' 参数用于您选择的 67 个特征。
      猜你喜欢
      • 2018-01-23
      • 2014-08-22
      • 2016-08-16
      • 2015-08-30
      • 2014-11-12
      • 2015-08-13
      • 2020-04-13
      • 2017-04-21
      相关资源
      最近更新 更多