【问题标题】:How tf-idf model handles unseen words during test-data?tf-idf 模型如何在测试数据中处理看不见的单词?
【发布时间】:2020-02-10 18:30:30
【问题描述】:

我已经阅读了很多博客,但对答案并不满意,假设我在几个文档示例上训练 tf-idf 模型:

   " John like horror movie."
   " Ryan watches dramatic movies"
    ------------so on ----------

我使用这个功能:

   from sklearn.feature_extraction.text import TfidfTransformer
   count_vect = CountVectorizer()
   X_train_counts = count_vect.fit_transform(twenty_train.data)
   X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
   print((X_train_counts.todense()))
   # Gives count of words in each document

   But it doesn't tell which word? How to get words as headers in X_train_counts 
  outputs. Similarly in X_train_tfidf ?

所以 X_train_tfidf 输出将是带有 tf-idf 分数的矩阵:

     Horror  watch  movie  drama
doc1  score1  --    -----------
doc2   ------------------------

这对吗?

fit 有什么作用,transformation 有什么作用? 在 sklearn 中提到:

fit(..) 方法使我们的估计器适合数据,其次是 transform(..) 方法将我们的计数矩阵转换为 tf-idf 表示。 estimator to the data 是什么意思?

现在假设新的测试文件来了:

    " Ron likes thriller movies"

如何将此文档转换为 tf-idf?我们不能将其转换为 tf-idf 对吧? 如何处理火车文档中没有的单词thriller

【问题讨论】:

    标签: python-3.x scikit-learn tf-idf


    【解决方案1】:

    将两个文本作为输入

    import pandas as pd
    from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
    
    text = ["John like horror movie","Ryan watches dramatic movies"]
    
    count_vect = CountVectorizer()
    tfidf_transformer = TfidfTransformer()
    X_train_counts = count_vect.fit_transform(text)
    X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
    
    pd.DataFrame(X_train_tfidf.todense(), columns = count_vect.get_feature_names())
    

    o/p

            dramatic    horror      john        like        movie       movies      ryan    watches
       0    0.000000    0.471078    0.471078    0.471078    0.471078    0.335176    0.000000    0.000000
       1    0.363788    0.000000    0.000000    0.000000    0.000000    0.776515    0.363788    0.363788
    

    现在测试它是否有新评论,我们需要使用变换函数,在向量化时将忽略超出词汇表的单词。

    new_comment = ["ron don't like dramatic movie"]
    
    pd.DataFrame(tfidf_transformer.transform(count_vect.transform(new_comment)).todense(), columns = count_vect.get_feature_names())
    
    
        dramatic    horror  john    like    movie   movies  ryan    watches
    0   0.57735      0.0    0.0    0.57735  0.57735   0.0   0.0      0.0
    

    如果你想使用某个单词的词汇,比准备你要使用的单词列表,并不断在这个列表中追加新单词并将列表传递给 CountVectorizer

     vocabulary = ['dramatic', 'movie','horror']
     vocabulary.append('Thriller')
     count_vect = CountVectorizer(vocabulary = vocabulary)
     cont_vect.fit_transform(text)
    

    【讨论】:

    • 但如果你看到它永远不会包含像“Thriller”这样的新词
    • 如果我们也想包含那个词.. 那怎么办?
    猜你喜欢
    • 2019-11-16
    • 2012-10-08
    • 1970-01-01
    • 2019-04-17
    • 2010-09-18
    • 2012-04-23
    • 2019-02-21
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多