我试图生成一个黑森矩阵的逆并遇到问题。我将梯度和hessian矩阵都定义为变量x1和x2的函数,以便在以后的迭代中使用不同的值。这些函数工作正常,但是当我尝试取逆时,它返回以下内容:
import numpy as np
#Rosenbrock Function
def f(x1, x2):
return 100*(x2-x1**2)**2+(1-x1)**2
#Define Gradient of f
def gradf(x1,x2):
return np.array([[-400*x1*(x2-x1**2)-2*(1-x1)],[200*(x2-x1**2)]])
#Define Hessian Matrix of f
def hessf(x1,x2):
return np.array([[-400*x2+1200*x1**2+2 , -400*x1],[-400*x1 , 200]])
#Inverse of Hessian Matrix
def hessf_inv(x1, x2):
return np.linalg.inv(hessf)
print(hessf_inv(1,1))
---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-114-67de06090dbe> in <module>
2 def hessf_inv(x1, x2):
3 return np.linalg.inv(hessf)
----> 4 print(hessf_inv(1,1))
<ipython-input-114-67de06090dbe> in hessf_inv(x1, x2)
1 #Inverse of Hessian Matrix
2 def hessf_inv(x1, x2):
----> 3 return np.linalg.inv(hessf)
4 print(hessf_inv(1,1))
<__array_function__ internals> in inv(*args, **kwargs)
~Anaconda3libsite-packagesnumpylinalglinalg.py in inv(a)
537 """
538 a, wrap = _makearray(a)
--> 539 _assert_stacked_2d(a)
540 _assert_stacked_square(a)
541 t, result_t = _commonType(a)
~Anaconda3libsite-packagesnumpylinalglinalg.py in _assert_stacked_2d(*arrays)
194 for a in arrays:
195 if a.ndim < 2:
--> 196 raise LinAlgError('%d-dimensional array given. Array must be '
197 'at least two-dimensional' % a.ndim)
198
LinAlgError: 0-dimensional array given. Array must be at least two-dimensional
这不是numpy的功能吗?如有任何帮助,不胜感激。
我想你忘记调用函数了,此刻你试图逆一个函数对象
def hessf_inv(x1, x2):
return np.linalg.inv(hessf)
改为:
def hessf_inv(x1, x2):
return np.linalg.inv(hessf(x1, x2))
(注意x1
和x2
添加到hessf
中)。
您没有将参数传递给hessf_inv函数中的hessf函数。函数必须是;
def hessf_inv(x1, x2):
return np.linalg.inv(hessf(x1,x2))