Tik0
Tik0

Reputation: 2697

Numpy random functions create inconsistent shapes for given argument

I found an odd behavior of numpy's random number generators. It seems that they do not generate consistent matrix shapes for a given argument. It is just super annoying to spend an extra line for conversion afterward which I'd like to circumvent. How can I tell matlib.randn directly to generate a vector of size (200,)?

import numpy as np
A = np.zeros((200,))
B = np.matlib.randn((200,))
print(A.shape)    # prints (200,)
print(B.shape)    # prints (1, 200)

Upvotes: 1

Views: 52

Answers (2)

user2653663
user2653663

Reputation: 2948

B is a matrix object, not a ndarray. The matrix object doesn't have an 1D equivalent objects and are not recommended to use anymore, so you should use np.random.random instead.

Upvotes: 1

zvone
zvone

Reputation: 19362

Use numpy.random instead of numpy.matlib:

numpy.random.randn(200).shape # prints (200,)

numpy.random.randn can create any shape, whereas numpy.matlib.randn always creates a matrix.

Upvotes: 1

Related Questions