How can i solve my tf-idf vocabulary error?

208 views Asked by At

I train a TFIDF from sklearn on my train data, and when I apply the vocabulary on new data it give me a key error because it don't learn on it. How can i solve it ?

This my code.

   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)
1

There are 1 answers

0
isaaccs On BEST ANSWER

solve my problem by using if statement

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