How to Serialize CSR Matrix

Viewed 621

I have a csr_matrix objects calculate from TfidfTransformer.transform. I want to serialize or and unserialize:

tf_csrmtrix = TfidfTransformer.transform(data)
json.dumps(tf_csrmtrix)
TypeError: Object of type 'csr_matrix' is not JSON serializable

How can I work this king of data: csr matrices?

1 Answers

If a binary serialization format will do the trick, I'll suggest the pickle module

just import pickle and use pickle.dumps where you used json.dumps (notice this gives a bytes-object and not a string like json does)

you should be able to write to a file, a DB, or over some socket, and load it (using pickle) later, to get the exact same object

Related