scipy.minimize ValueError: The user-provided objective function must return a scalar value

2.4k Views Asked by At

I had read the documentation and tried to understand how to work with scipy.optimize.minimize(), but I can not.

from scipy.optimize import minimize

def f(x):
    return x**2

x0 = [-2.0, -1.0, 0.0, 1.0, 2.0]

res = minimize(f, x0)
print(res.x)

Output: "ValueError: The user-provided objective function must return a scalar value."

2

There are 2 best solutions below

0
On

I have solve it: x0 should be a number or (1,) array

0
On

In your example, your initial array of x0 is fine. The thing that caused the value error is that the objective function must return a single value, not a list/array of values. You can sum it up or use l2-norm.

def f(x):
    return sum(x**2)

res = minimize(f, x0)
print(res.x)

[-1.82818467e-08  8.41691947e-08 -1.86620236e-07 -8.41691948e-08
  1.82818469e-08]