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

问题描述 投票:0回答:1

我正在尝试将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}
               }

谢谢你的协助 ... !

python json matrix sparse-matrix tf-idf
1个回答
0
投票

所以我设法做到这样:给定'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()})
© www.soinside.com 2019 - 2024. All rights reserved.