Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy 'module' object has no attribute 'stack'

Tags:

python

numpy

I am trying to run some code (which is not mine), where is used 'stack' from numpy library.

Looking into documentation, stack really exists in numpy: https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.stack.html

but when I run the code, I got:

AttributeError: 'module' object has no attribute 'stack'

any idea how to fix this. code extract:

s_t = np.stack((x_t, x_t, x_t, x_t), axis = 2)

do I need some old libraries?

Thanks.

EDIT: for some reason, python uses older version of numpy library. pip2 freeze prints "numpy==1.10.4". I've also reinstalled numpy and I've got "Successfully installed numpy-1.10.4", but printing np.version.version in code gives me 1.8.2.

like image 815
Snurka Bill Avatar asked Feb 20 '16 01:02

Snurka Bill


2 Answers

The function numpy.stack is new; it appeared in numpy == 1.10.0. If you can't get that version running on your system, the code can be found at (near the end)

https://github.com/numpy/numpy/blob/f4cc58c80df5202a743bddd514a3485d5e4ec5a4/numpy/core/shape_base.py

I need to examine it a bit more, but the working part of the function is:

sl = (slice(None),) * axis + (_nx.newaxis,)
expanded_arrays = [arr[sl] for arr in arrays]
return _nx.concatenate(expanded_arrays, axis=axis)

So it adds a np.newaxis to each array, and then concatenate on that. So like, vstack, hstack and dstack it adjusts the dimensions of the inputs, and then uses np.concatenate. Nothing particularly new or magical.

So if x is (2,3) shape, x[:,np.newaxis] is (2,1,3), x[:,:,np.newaxis] is (2,3,1) etc.

If x_t is 2d, then

np.stack((x_t, x_t, x_t, x_t), axis = 2)

is probably the equivalent of

np.dstack((x_t, x_t, x_t, x_t))

creating a new array that has size 4 on axis 2.

Or:

tmp = x_t[:,:,None]
np.concatenate((tmp,tmp,tmp,tmp), axis=2)
like image 60
hpaulj Avatar answered Sep 29 '22 20:09

hpaulj


It is likely have 2 numpy libraries, one in your System libraries, and the other in your python's site packages which is maintained by pip. You have a few options to fix this.

  • You should reorder the libraries in sys.path so your pip installed numpy library comes in front the native numpy library. Check this out to fix your path permanently.

  • Also look into virtualenv or Anaconda, which will allow you to work with specific versions of a package when you have multiple versions on your system.

  • Here's another suggestion about how to ensure pip installs the library on your user path (System Library).
like image 40
ilyas patanam Avatar answered Sep 29 '22 21:09

ilyas patanam