I'm trying to convert TF-IDF
sparse matrix to json format.
Converting it to pandas datafram (toarray()
or todense()
) causes memory error.
So I would like to avoid those approaches. Is there other way to convert it to json ?
Below is my appraoach to get sparse matrix, and my preferred json outcome
Thanks for helping me out ... !
TF-IDF matrix
pip = Pipeline([('hash', HashingVectorizer(ngram_range=(1, 1), non_negative=True)), ('tfidf', TfidfTransformer())])
result_uni_gram = pip.fit_transform(df_news_noun['content_nouns'])
return matrix
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
Expecting Outcome
output_json = {
0: {1041232 : 0.03397, 1035546 : 0.04260, 1031141 : 0.055795 ... },
...
... 112536: {9046 : 0.04444, 4920 : 0.07335, 112536 : 0.06667}
}
Thanks for helping me out ... !