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

相关推荐
xianrenli382 分钟前
python版本配置
开发语言·python
啵啵鱼爱吃小猫咪5 分钟前
机器人标准DH(SDH)与改进DH(MDH)
开发语言·人工智能·python·学习·算法·机器人
工程师老罗7 分钟前
DataLoader的用法
人工智能·python
工程师老罗8 分钟前
PyTorch与TensorBoard兼容性问题解决方案
人工智能·pytorch·python
曲幽11 分钟前
FastAPI日志实战:从踩坑到优雅配置,让你的应用会“说话”
python·logging·fastapi·web·error·log·info
小舞O_o12 分钟前
CondaError: Run ‘conda init‘ before ‘conda activate‘
linux·python·conda
雄狮少年22 分钟前
简单react agent(没有抽象成基类、子类,直接用)--- langgraph workflow版 ------demo1
前端·python·react.js
Lxinccode25 分钟前
python(70) : 网页IDE
开发语言·ide·python·网页ide
潇凝子潇27 分钟前
Arthas 火焰图的使用
开发语言·python
Java后端的Ai之路28 分钟前
【Python小知识】-pip install xxx 命令安装的 ,在电脑的哪个盘?
开发语言·python·pip·pip install