Home > Mobile >  Inverse Matrix with Variables
Inverse Matrix with Variables

Time:09-24

I'm trying to generate the inverse of a hessian matrix and running into issues. I define both the gradient and hessian matrix as functions with variables x1 and x2 in order to use different values at future iterations. These functions work fine but when I attempt to take the inverse, it returns the following:

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

Is this not a functionality of numpy? Any help would be appreciated.

CodePudding user response:

I think you forgot to call the function, at the moment you try to inverse a function object.

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

Change it to:

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

(note the x1 and x2 added to the hessf).

CodePudding user response:

You did not pass the parameters into the hessf function inside the hessf_inv function. The function must be;

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