基于 TF -IDF 将每个文档转换为向量

Convert each document to a vector based on TF -IDF

我在下面编写了计算 TF-IDF 分数的代码

docs=['ali is a good boy',
      'a good boy is not bad',
      'ali is not bad but bad is good']

cv=CountVectorizer()

# this steps generates word counts for the words in your docs
word_count_vector=cv.fit_transform(docs)
print(word_count_vector)
tfidf_transformer=TfidfTransformer(smooth_idf=True,use_idf=True)
tfidf_transformer.fit(word_count_vector)

# print idf values
df_idf = pd.DataFrame(tfidf_transformer.idf_, index=cv.get_feature_names(),columns=["idf_weights"])
# sort ascending
df_idf.sort_values(by=['idf_weights'])

# count matrix
count_vector=cv.transform(docs)
# tf-idf scores
tf_idf_vector=tfidf_transformer.transform(count_vector)
feature_names = cv.get_feature_names()
print(feature_names)
#get tfidf vector for first document
first_document_vector=tf_idf_vector[0]
#for first_document_vector in tf_idf_vector:
#print the scores
df=(pd.DataFrame(first_document_vector.T.todense().transpose(),columns=feature_names))
df.to_csv('file1.csv') 

1- 最后我能够得到第一个文档的向量。但我可能无法获得所有文档的向量。我尝试循环并附加到数据框,但它没有用。 2- 如何将文档索引保存到 csv 文件中?
我必须 运行 它来自电影镜头数据集的电影情节。这就是为什么保存documnet的索引对我来说很重要。

获取所有文档的向量:

#get tfidf vector for all documents
all_document_vector = tf_idf_vector
df= pd.DataFrame(all_document_vector.T.todense().transpose(),columns=feature_names)

要导出索引为 csv 的文件:

df.to_csv('file1.csv',index=True, index_label = 'Index')