Hessiandiag
パッケージの関数( Numdifftools ) を使用して、関数を最小化する最適なパラメーターを使用してヘッセ行列の対角要素を取得したいと考えています。
Hessiandiag
Numdifftools の開発者 Web サイトから取得した の使用法の簡単な例を次に示します。
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]
ヘッセ行列を取得したい関数が複雑すぎて を使用して記述できないとし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.