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?

feetwet
  • 3,248
  • 7
  • 46
  • 84
  • 1
    Numpy has zero dimensional arrays: https://stackoverflow.com/questions/773030/why-are-0d-arrays-in-numpy-not-considered-scalar – Moritz Feb 12 '18 at 20:22
  • Get the value with `test.x[()]`. – j08lue Feb 12 '18 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. – user2357112 Feb 12 '18 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? – Gerges Feb 12 '18 at 20:30

1 Answers1

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[()]
user2357112
  • 260,549
  • 28
  • 431
  • 505