【问题标题】:How can i solve my tf-idf vocabulary error?如何解决我的 tf-idf 词汇错误?
【发布时间】:2021-01-24 16:59:20
【问题描述】:

我在我的训练数据上训练来自 sklearn 的 TFIDF,当我将词汇表应用于新数据时,它给了我一个关键错误,因为它没有学习它。 我该如何解决?

这是我的代码。

   def feature_engineering(self, inputs):
        x = [self.analyser(seq) for seq in inputs]
        return x

    def fit(self, inputs):
        if self.vocabulary and self.analyser:
            pass
        else:
            vectorizer = TfidfVectorizer(
                ngram_range=(self.config_dict["min_n_gram"], self.config_dict["max_n_gram"]), lowercase=False,
                stop_words=None,min_df=2)
            vectorizer.fit(inputs)
            self.analyser = vectorizer.build_analyzer()
            self.vocabulary = vectorizer.vocabulary_
            save_object(os.path.join(self.feature_extraction_folder, "analyzer.pickle"), self.analyser)
            save_object(os.path.join(self.feature_extraction_folder, "vocabulary.pickle"), self.vocabulary)

    def transform(self, inputs):
        vocab_size = len(self.vocabulary)
        inputs = self.feature_engineering(inputs)
        inputs = [[self.vocabulary[x] for x in l] for l in inputs]##This line generate an error

        return np.array(inputs)

【问题讨论】:

  • 错误是什么?怎么复制?
  • 该错误是一个Key Error,它产生是因为token不在词汇表中

标签: python scikit-learn tf-idf tfidfvectorizer


【解决方案1】:

使用 if 语句解决我的问题

inputs = [[self.vocabulary[x] for x in l if x in self.vocabulary.keys()] for l in inputs]```

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 2018-03-21
    • 2023-02-07
    • 2018-01-30
    • 1970-01-01
    • 2020-12-23
    • 2011-02-01
    • 2019-04-17
    • 2018-05-27
    相关资源
    最近更新 更多