0

我想使用Hessiandiag包(Numdifftools)中的函数来使用最小化函数的最佳参数来获取 Hessian 矩阵的对角元素。

下面是一个Hessiandiag从 Numdifftools 开发者网站获取的简单用法示例:

import numpy as np
import numdifftools as nd
fun = lambda x : x[0] + x[1]**2 + x[2]**3
ddfun = lambda x : np.asarray((0, 2, 6*x[2]))
Hfun = nd.Hessdiag(fun)
hd = Hfun([1,2,3]) # HD = [ 0,2,18]

假设我想要获取 Hessian 矩阵的函数太复杂而无法使用lambda. 我的函数存储在名称下的另一个文件中Latent(使用def Latent(x1, x2, x3)命令)。我不能执行以下操作:

from Latent import Latent  # That's my function
import numpy as np
import numdifftools as nd
fun = lambda x1, x2, x3 : Latent(x1, x2, x3)
Hfun = nd.Hessdiag(fun)
hd = Hfun([np.array([1.2, 1.5, 2]), np.array(3.4, 5), 6])  # three parameters

……这行不通……

This is the error:

    raise ValueError('%s must be scalar, one of [1 2 3 4].' % name)

ValueError: n must be scalar, one of [1 2 3 4].

如何在不使用复杂功能的情况下使用 nd.Hessdiag lambda

更新 我也试过这个:

fun = lambda x: Latent(x[0], x[1], x[2])
Hfun = nd.Hessdiag(fun)
hd = Hfun([x1, x2, x3])

我收到此错误:

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 601, in runfile
    execfile(filename, namespace)

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 66, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "F:/dropbox/Dropbox/Research/Fisher Martineau Sheng/SEC/codes/Python Latent Factor/V1/Main_v1.py", line 101, in <module>
    hd = Hfun(np.array([est_param, allret_.T, n, capt, num_treat]))

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 1161, in __call__
    return self.hessdiag(x)

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 1171, in hessdiag
    dder, self.error_estimate, self.final_delta = self._partial_der(x)

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numdifftools\core.py", line 830, in _partial_der
    self._x = np.asarray(x0, dtype=float)

  File "C:\Users\chamar.stu\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\numeric.py", line 460, in asarray
    return array(a, dtype, copy=False, order=order)

ValueError: setting an array element with a sequence.
4

0 回答 0