【问题标题】:sklearn tfidf vectorizer - remove n-2 and n-1 grams if n gram existssklearn tfidf 矢量化器 - 如果存在 n 克,则删除 n-2 和 n-1 克
【发布时间】:2019-12-23 00:09:43
【问题描述】:

我正在使用 sklearn 的 tfidf-vectorizer 创建文档特征矩阵和特征术语列表。

如果 n-gram 已经存在,我不想重复 n-1 和 n-2 克。即for an example sentence: The quick brown fox jumps over the fence

我想not include条款'fox' and 'brown fox' if 'quick brown fox' exists.

我的假设是重复标记会导致特征集的人为扩展并扭曲其他任务(例如聚类)的结果。

【问题讨论】:

  • 你能解决这个问题吗?我遇到了同样的问题
  • 还没有。对不起。

标签: python scikit-learn n-gram tfidfvectorizer


【解决方案1】:

Sklearn 的 tfidf-vectorizer 包含一个关键字“ngram_range”,允许您指定 n-gram。您还应该考虑使用“stop_words”关键字。

from sklearn.feature_extraction.text import TfidfVectorizer

corpus = ['The quick brown fox jumps over the fence']
vectorizer = TfidfVectorizer(ngram_range=(3, 3), stop_words='english')
X = vectorizer.fit_transform(corpus)

print(vectorizer.get_feature_names())

通常这取决于您的语料库,您是否要选择一元、二元、三元等。为了选择,您需要评估算法的性能。例如使用 Roc 曲线、信息增益、准确性等,看看哪个 n-gram 产生最佳性能。

【讨论】:

  • 谢谢,但是这样做并没有给我我需要的二元组——例如“跳过”。我需要得到一个完整的 ngram 范围 (0,3),然后过滤掉存在 trigrams 的二元组(例如,删除 'quick brown' 和 'brown fox',因为存在 'quick brown fox'。
【解决方案2】:

我知道这不是一种有效的方法,但这就是我所做的。 最后使用 pandas 系列只是用所选索引对数组进行子集化。

def removeSubgrams(features):
  # Sort features based on length of the n-gram
  features = sorted(features , key=lambda x:len(x.split(" ")))

  to_remove = []

  # Iterate over all features
  for i,subfeature in enumerate(features):
    for j,longerfeature in enumerate(features[i+1:]):
      if longerfeature.find(subfeature) > -1:
        to_remove.append(i)
        # break if subfeature is a substring of longerfeature
        break
  features = pd.Series(features)
  # keep only those features that are not in to_remove
  features = features.loc[~features.index.isin(to_remove)]
  return features

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 2011-01-29
    • 2014-02-06
    • 2015-08-13
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多