,更新向量。 ④ 重复步骤②和步骤③,直到读取完所有文本。 ⑤ 可以将向量进行归一化处理,使其符合向量的定义,即所有元素的平方和为1。

代码实现:

import numpy as np
import re

# 读取词典
with open('bbc.terms') as f:
    dictionary = f.read().splitlines()

# 构建全0矩阵
doc_matrix = np.zeros((2225, len(dictionary)))

# 读取文本文件
with open('bbc.mtx') as f:
    for line in f:
        if line.startswith('%'):
            continue
        else:
            doc_id, word_id, freq = map(int, line.split())
            # 找到对应词在向量中的位置,词频+1
            doc_matrix[doc_id-1, word_id-1] += freq

# 归一化处理
doc_matrix /= np.linalg.norm(doc_matrix, axis=1)[:, np.newaxis]

print(doc_matrix)

结果示例:

[[0.         0.         0.         ... 0.         0.         0.        ]
 [0.         0.         0.         ... 0.         0.         0.        ]
 [0.         0.         0.         ... 0.         0.         0.        ]
 ...
 [0.         0.         0.         ... 0.         0.         0.        ]
 [0.         0.         0.         ... 0.         0.         0.        ]
 [0.         0.         0.         ... 0.         0.         0.        ]]
``

原文地址: https://www.cveoy.top/t/topic/feDp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录