2

Calling the Powell minimizer for a single-dimensional problem is creating an OptimizeResult with an inaccessible value. For example:

from scipy.optimize import minimize
test = minimize(lambda x: 1.0, np.array([1.0]), method="Powell")

If I then ask for test.x I get:

array(3.58792896)

Something is wrong with that "array": I can't get the value out of it. For example, test.x[0] returns IndexError: too many indices for array. It's like it's a zero-dimensional array, or there's some other reference problem.

(A well-formed ndarray would display like array([3.58792896]).)

What am I doing wrong?

4
  • 1
    Numpy has zero dimensional arrays: stackoverflow.com/questions/773030/… Commented Feb 12, 2018 at 20:22
  • Get the value with test.x[()]. Commented Feb 12, 2018 at 20:22
  • 3
    That is indeed a zero-dimensional array, but while zero-dimensional arrays are entirely supported in NumPy, that minimize call still shouldn't be making one. Commented Feb 12, 2018 at 20:22
  • This could be a bug. As the documentation says, the result should have same length as input. All other methods except Powell have this behaviour. Maybe report this on the github issues? Commented Feb 12, 2018 at 20:30

1 Answer 1

2

That's a 0-dimensional array, but it shouldn't be. While 0-dimensional arrays are a supported concept in NumPy, that minimize call shouldn't be creating one. It looks like the devs are worried about breaking backward compatibility if they fix this, so a fix is unlikely for now.

I would recommend using numpy.atleast_1d to handle this case consistently with the cases that return a 1D array, and be forward compatible if they do eventually change the return value:

test = minimize(...)
if not test.success:
    handle_that()
result = np.atleast_1d(test.x)

For cases where you expect a 0D array and want to retrieve the stored value, index it with a tuple of 0 indices:

value = zero_d_array[()]
Sign up to request clarification or add additional context in comments.

Comments

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.