我有一个Pyomo模型,我想得到梯度和Hessian的目标。相关的SO question会询问相同的问题。当我尝试那里提出的解决方案时
from pyomo.core.base.symbolic import differentiate
from pyomo.core.base.expr import identify_variables
varList = list(identify_variables(zipfe.loglikelihood.expr))
firstDerivs = differentiate(zipfe.loglikelihood.expr, wrt_list=varList)
我收到以下错误:
Traceback (most recent call last):
File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-9-6f2637b1fe13>", line 1, in <module>
firstDerivs = differentiate(zipfe.loglikelihood.expr, wrt_list=varList)
File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/pyomo/core/base/symbolic.py", line 122, in differentiate
tmp_expr, locals=dict((str(x), x) for x in sympy_vars) )
File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/core/sympify.py", line 354, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 894, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "/home/pauperei/.conda/envs/py36/lib/python3.6/site-packages/sympy/parsing/sympy_parser.py", line 807, in eval_expr
code, global_dict, local_dict) # take local objects in preference
File "<string>", line 1, in <module>
TypeError: 'Symbol' object does not support indexing
以下是我的目标(前几行):
zipfe.loglikelihood.pprint()
loglikelihood : Size=1, Index=None, Active=True
Key : Active : Sense : Expression
None : True : minimize : log( 1 + exp( alpha1[0] + 2.0*alpha1[1] + alpha1[4] + 2.8986705607108596*( delta[0] + 2.0*delta[1] ) ) ) - ( 2.0*beta1[0] + beta1[3] + 2.8986705607108596*( gamma[0] + 2.0*gamma[1] ) ) + log( exp( - log( 1 + exp( alpha1[0] + 2.0*alpha1[1] + alpha1[4] + 2.8986705607108596*( delta[0] + 2.0*delta[1] ) ) ) + 2.0*beta1[0] + beta1[3] + 2.8986705607108596*( gamma[0] + 2.0*gamma[1] ) ) + exp( - log( 1 + exp( alpha1[0] + 5.0*alpha1[1] + 2.8986705607108596*( delta[0] + 2.0*delta[1] ) ) ) + 5.0*beta1[0] + 2.8986705607108596*( gamma[0] + 2.0*gamma[1] ) ) + exp( - log( 1 + exp( alpha1[0] + 2.0*alpha1[1] + alpha1[7] + 2.8986705607108596*( delta[0] + 2.0*delta[1] ) ) ) + 2.0*beta1[0] + beta1[6] + 2.8986705607108596*( gamma[0] + 2.0*gamma[1] ) ) + exp( - log( 1 + exp( alpha1[0] + alpha1[1] + alpha1[6]
似乎问题是Sympy不喜欢像alpha1[0]
这样的索引变量。这个问题有解决办法吗?
我正在使用Pyomo 5.2和Python 3.6。我将尽快添加一个最小的工作示例。
在过去的几天里,这已经在Pyomo GitHub存储库中显示为Do Do,所以希望很快就会有解决方案。