approx_fprime - ValueError: setting an array element with a sequence
approx_fprime - ValueError: setting an array element with a sequence
我在执行 approx_fprime
时收到错误(标题)
import numpy as np
import scipy.optimize as op
def J(x):
return x*x
xk = np.arange(1,10).reshape(3,3).astype('float32')
print(op.approx_fprime(xk.ravel(), J, 0.01))
我做错了什么?
我必须更改函数,它应该 return 标量而不是向量。
def J(x):
return np.sum(x**2)
您正在推翻 approx_fprime 的假设:
Finite-difference approximation of the gradient of a scalar function.
Parameters:
...
f : callable
The function of which to determine the gradient (partial derivatives). Should take xk as first argument, other arguments to f can be supplied in *args. Should return a scalar, the value of the function at xk.
在本例中,您 return 是一个大小为 9 的向量。标量函数不应该 return。原因很简单:
x = np.array([1,2,3])
print((x*x).shape)
# (3,)
我在执行 approx_fprime
import numpy as np
import scipy.optimize as op
def J(x):
return x*x
xk = np.arange(1,10).reshape(3,3).astype('float32')
print(op.approx_fprime(xk.ravel(), J, 0.01))
我做错了什么?
我必须更改函数,它应该 return 标量而不是向量。
def J(x):
return np.sum(x**2)
您正在推翻 approx_fprime 的假设:
Finite-difference approximation of the gradient of a scalar function.
Parameters:
...
f : callable
The function of which to determine the gradient (partial derivatives). Should take xk as first argument, other arguments to f can be supplied in *args. Should return a scalar, the value of the function at xk.
在本例中,您 return 是一个大小为 9 的向量。标量函数不应该 return。原因很简单:
x = np.array([1,2,3])
print((x*x).shape)
# (3,)