[英]scipy.optimize.minimize returning zero-dimensional array?
Calling the Powell minimizer for a single-dimensional problem is creating an OptimizeResult
with an inaccessible value.为一维问题调用 Powell 最小化器会创建一个具有不可访问值的OptimizeResult
。 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:如果我然后要求test.x
我得到:
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
.例如, test.x[0]
返回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])
.) (格式良好的ndarray
将显示为array([3.58792896])
。)
What am I doing wrong?我究竟做错了什么?
That's a 0-dimensional array, but it shouldn't be.这是一个 0 维数组,但它不应该是。 While 0-dimensional arrays are a supported concept in NumPy, that minimize
call shouldn't be creating one.虽然 NumPy 支持 0 维数组的概念,但minimize
调用不应该是创建一个。 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:我建议使用numpy.atleast_1d
来处理这种情况与返回一维数组的情况一致,并且如果它们最终改变返回值则向前兼容:
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:对于您期望 0D 数组并希望检索存储值的情况,请使用 0 索引元组对其进行索引:
value = zero_d_array[()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.