sklearn 计算 tfidf 得到每个词分数

python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

# 语料库 可以换为其它同样形式的单词
corpus = [
    list(range(-5, 5)),
    list(range(-6,4)),
    list(range(12)),
    list(range(13))]

# corpus = [
#    ['Two', 'wrongs', 'don\'t', 'make', 'a', 'right', '.'],
#    ['The', 'pen', 'is', 'mightier', 'than', 'the', 'sword'],
#    ['Don\'t', 'put', 'all', 'your', 'eggs', 'in', 'one', 'basket', '.']]
    
def dummy_fun(doc):
    return doc
    
tfidf_vec = TfidfVectorizer(
    analyzer='word',
    tokenizer=dummy_fun,
    preprocessor=dummy_fun,
    token_pattern=None)  

# 使用 fit_transform() 得到 TF-IDF 矩阵。此为 scipy 稀疏矩阵
tfidf_matrix = tfidf_vec.fit_transform(corpus)
# print(tfidf_matrix)

# 使用 get_feature_names() 得到不重复的单词
print(tfidf_vec.get_feature_names_out())

# 得到每个单词对应的 ID
print(tfidf_vec.vocabulary_)
python 复制代码
# 得到 corpus 中每个词得分
for i in range(len(corpus)):
    column_indexes = [tfidf_vec.vocabulary_[key] for key in corpus[i]]
    tf_idf = tfidf_matrix[i, column_indexes].toarray()[0]
    print(tf_idf)

参考:
Applying scikit-learn TfidfVectorizer on tokenized text
sklearn.feature_extraction.text.TfidfVectorizer

相关推荐
ZHOU_WUYI8 分钟前
旋转位置编码 (2)
pytorch·python·深度学习
程序员~小强28 分钟前
让知识触手可及!基于Neo4j的机械设备知识图谱问答系统
人工智能·python·django·知识图谱·neo4j
DanCheng-studio42 分钟前
智科 机器学习毕业设计题目指导
python·毕业设计·毕设
java1234_小锋1 小时前
一周学会Flask3 Python Web开发-SQLAlchemy定义数据库模型
python·flask·sqlalchemy·flask3
Light602 小时前
CSnakes vs Python.NET:跨语言集成的巅峰对决与架构解密
python·性能优化·.net·跨语言集成·双向互操作
gallonyin2 小时前
免root运行python保活守护进程supervisor
linux·开发语言·python
lisw052 小时前
【PyCharm】Python和PyCharm的相互关系和使用联动介绍
ide·python·pycharm
猿榜2 小时前
js逆向-某博博返回数据解密
javascript·python
用户64405360196542 小时前
pip install 安装太慢的解决方法
python
Lemon_man_3 小时前
基于Django创建一个WEB后端框架(DjangoRestFramework+MySQL)流程
python·mysql·django