Unexpected Numpy behavior

I have a numpy matrix in the middle of a running program (let's assume this is the name rdy

). I found that converting it to a one dimensional matrix gives me a two dimensional matrix. But if I try the same thing in an interactive shell, I get the expected results. Like the following ipython logs. I'm wondering what aspect of rdy's matrix is ​​causing it to behave differently when reshaped?

# This is expected:
In [191]: np.random.rand(512, 1).reshape(-1).shape
Out[191]: (512,)

# This is unexpected:
In [192]: rdy.reshape(-1).shape
Out[192]: (1, 512)

# The following are the different aspects of the rdy matrix:
In [193]: rdy.shape
Out[193]: (512, 1)

In [194]: rdy.flags
Out[194]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

In [195]: rdy.data
Out[195]: <read-write buffer for 0xeae6488, size 4096, offset 0 at 0x2ff95e70>

      

+3


source to share


1 answer


One of the key defining properties np.matrix

is that it will remain as a two-dimensional object through general transformations. (This is almost the definition of a matrix, after all.)

np.random.rand

returns np.ndarray

that does not share this property. (I like to think of the ndarray being very similar to a C array, since you can change the "sizes" you like, and as long as you are still looking at the same region of memory and not overshooting, you will be fine.)



If you want the matrix to behave like an array, you can convert it to one .

+2


source







All Articles