python - 如何将稀疏矩阵数组转换为json python

标签 python json matrix sparse-matrix tf-idf

我正在尝试将 TF-IDF 稀疏矩阵转换为 json 格式。 将其转换为 pandas datafram(toarray()todense())会导致内存错误。 所以我想避免这些方法。还有其他方法可以将其转换为 json 吗?

下面是我获取稀疏矩阵的方法,以及我首选的 json 结果

感谢您帮助我......!


TF-IDF矩阵

pip = Pipeline([('hash', HashingVectorizer(ngram_range=(1, 1), non_negative=True)), ('tfidf', TfidfTransformer())])
result_uni_gram = pip.fit_transform(df_news_noun['content_nouns'])

返回矩阵

result_uni_gram

<112537x1048576 sparse matrix of type '<class 'numpy.float64'>'
    with 12605888 stored elements in Compressed Sparse Row format>



print(result_uni_gram)

(0, 1041232)    0.03397010691200069
(0, 1035546)    0.042603425242006505
(0, 1031141)    0.05579563771771019
(0, 1029045)    0.03985981185871279
(0, 1028867)    0.14591155976555212
(0, 1017328)    0.03827279930970525
:   :
(112536, 9046)  0.04444360144902461
(112536, 4920)  0.07335227778871069
(112536, 4301)  0.06667794684006756

预期结果

output_json = {
                0: {1041232 : 0.03397, 1035546 : 0.04260, 1031141 : 0.055795 ... }, 
                ...
                ... 112536: {9046 : 0.04444, 4920 : 0.07335, 112536 : 0.06667}
               }

感谢您帮助我......!

最佳答案

所以我设法这样做: 给定的“test_samples”是您的“scipy.sparse.csr.csr_matrix”

 import json
 import base64
 np_test_samples=test_samples.toarray()
 jason_test_samples=json.dumps({"data": np_test_samples.tolist()})

关于python - 如何将稀疏矩阵数组转换为json python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037323/

相关文章:

python - 如何在 Python 3.x 中强制输入整数?

python - 每次迭代在多个 CPU 上训练不同的 scikit-learn 分类器

用于两个相同数据库的 Python + MySQLDB 批量插入/更新命令

python - 类型错误 : Must be str not int

javascript - AngularJS JavaScript 解析 JSON 的一部分

c - 查找矩阵 NxN 中的所有峰值

go - 如何在 Golang 中创建 block 矩阵?

python - 如何绘制混淆矩阵?

javascript - 从 js Map 和 String 创建 json 字符串

javascript - 使用 jQuery $.each 与 Json 错误,有 1 个结果