在浏览Tensorflow Transform的文档时,我发现了用于执行TD-IDF的函数。
tft.tfidf( x, vocab_size, smooth=True, name=None)
由于文档没有提供如何执行TD-IDF的示例,我尝试使用example_string
example_strings=[["I", "like", "pie", "pie", "pie"], ["yum", "yum", "pie"]]
和一个1000的词汇大小(只是一个随机数字),但下面的代码给我返回了一个属性错误。
tft.tfidf(example_strings, vocab_size=1000)
AttributeError: ‘list’ object has no attribute ‘indices’
请帮助我解决这个问题,因为我对Tensorflow变换操作还不太熟悉。
回答:
如果你想使用TFT计算tfidf(这里有一个示例),你可以这样做
example_strings = ["I like pie pie pie", "yum yum pie"]VOCAB_SIZE = 100tf.compat.v1.disable_eager_execution()tokens = tf.compat.v1.string_split(example_strings)indices = tft.compute_and_apply_vocabulary(tokens, top_k=VOCAB_SIZE)bow_indices, weight = tft.tfidf(indices, VOCAB_SIZE + 1)
否则,你也可以使用TF的Tokenizer:
tk = tf.keras.preprocessing.text.Tokenizer(num_words=VOCAB_SIZE)tk.fit_on_texts(example_strings)tk.sequences_to_matrix(tk.texts_to_sequences(example_strings), mode='tfidf')