0

In my function, sometimes I get a result that is a 1 dimensional numpy array in 2D form, so that it's shape is nx1 (n,1). Other times, I might get it in the form 1xn array.shape = (1,n)

Other times, I get just a numpy array whose shape is (n,).

when I run the following tests, I get an error on the one hand, and a false positive on the other (since the length of a shape attribute is always greater than 1, apparently):

    y_predicted = forest.predict(testX)
    if y_predicted.shape[1] != None:
        y_predicted = y_predicted.T[0]

and

    y_predicted = forest.predict(testX)
    if len(y_predicted.shape) > 1:
        y_predicted = y_predicted.T[0]

I just need to make sure the final shape of y is always in the form (n,) rather than (n,1) or (1,n)...

1
  • squeeze, ravel and flatten will all do this job; but read their docs so you understand their differences. Commented Feb 28, 2016 at 16:59

1 Answer 1

3

You should use numpy.squeeze:

numpy.squeeze(a) removes single-dimensional entries from the shape of an array.

Example:

>>> x = np.array([[1,2,3]])
>>> x.shape
(1, 3)
>>> np.squeeze(x)
array([1, 2, 3])
>>> np.squeeze(x).shape
(3,)
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer. Was unaware of this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.