0

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."

ray_med
  • 1
  • 2
  • 2
    What parts of that error message do you have problems with? Your objective function in deed does not return a scalar. For instance, ``f(x0)=[4.0,1.0,0.0,1.0,2.0]``. – Alperino Oct 22 '20 at 08:40

2 Answers2

0

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

ray_med
  • 1
  • 2
0

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]