jiangniao
jiangniao

Reputation: 135

How to deal with this AttributeError in scipy? It's very strange

This code is just from SciPy.org:

import numpy as np
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

But when I run it, it shows: AttributeError: module 'scipy.sparse' has no attribute 'save_npz'

And if I do this:

import numpy as np
import scipy.sparse.save_npz
import scipy.sparse

sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

It shows: ModuleNotFoundError: No module named 'scipy.sparse.save_npz'

And if I do this:

import numpy as np
from scipy.sparse import csr_matrix, save_npz

sparse_matrix = csc_matrix(np.array([[0, 0, 3], [4, 0, 0]]))
save_npz('/tmp/sparse_matrix.npz', sparse_matrix)

It shows: ImportError: cannot import name 'save_npz'

So, how to fix it?

Upvotes: 4

Views: 3729

Answers (1)

Miles Erickson
Miles Erickson

Reputation: 2595

Inspect scipy.__version__ and you'll see that the version is < 0.19, the first release in which the save_npz method is implemented.

You need to run pip install --upgrade scipy at a shell prompt.

If you're using iPython or Jupyter, you will need to restart the kernel before the change will take effect.

Upvotes: 2

Related Questions