带变量的逆矩阵

2024-05-15 14:36:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图生成hessian矩阵的逆矩阵,并遇到了一些问题。我将梯度矩阵和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)

~\Anaconda3\lib\site-packages\numpy\linalg\linalg.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)

~\Anaconda3\lib\site-packages\numpy\linalg\linalg.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的功能吗?任何帮助都将不胜感激


Tags: ofinnumpyreturndefnp矩阵array
2条回答

您没有将参数传递到hessf_inv函数中的hessf函数中。功能必须是

def hessf_inv(x1, x2):
    return np.linalg.inv(hessf(x1,x2))

我想你忘记调用函数了,在你尝试反转一个函数对象的时候

def hessf_inv(x1, x2):
    return np.linalg.inv(hessf)

将其更改为:

def hessf_inv(x1, x2):
    return np.linalg.inv(hessf(x1, x2))

(注意x1x2添加到了hessf

相关问题 更多 >