【发布时间】:2015-04-18 22:50:58
【问题描述】:
我想在 sympy 中评估类似形式(更复杂)的函数。
y = a * b / np.sum( a*( b + c) )
其中所有变量都是长度为n 的向量。评估将在优化例程的每个时间步进行。因此,我想有效地实施它。最有可能的是,最好编译这些函数,但 autowrap 模块给了我奇怪的错误。
什么有效:
import numpy as np
import sympy as sp
from __future__ import division
a = sp.IndexedBase('a')
b = sp.IndexedBase('b')
c = sp.IndexedBase('c')
n = 4
expr_fun = lambda x: a[x] * (b[x] + c[x])
expr = [ a[i]*b[i] / np.sum([expr_fun(i) for i in range(n)]) for i in range(n)]
我可以直接在 sympy 中计算这个表达式:
r = np.random.random(n)
subs_dict = {}
[ subs_dict.update({a[i]:r[i],b[i]:r[i] }) for i in range(n) ]
[expr[i].subs(subs_dict) for i in range(n)]
给了我(如预期的那样):
0.0786923966864026*c[0] + 0.403977159637609*c[1] + 0.598011208186539*c[2] + 0.0896229978341944*c[3] + 0.535039725662632
但是我编译这个表达式失败了。我从几个小时开始就在阅读博客和手册,但要么我太累了,要么没有找到合适的信息。非常感谢任何帮助。
编辑:回应 Eric:我现在不知道如何在 theano 或 autowrap 中实现向量的总和。我使用 lambda 函数尝试了不同的版本并得到了各种错误。也许最可重现的与输入的维度有关:
from sympy.printing.theanocode import theano_function
from sympy.printing.theanocode import sympy as sp
from sympy.printing.theanocode import dim_handling
import numpy as np
symbols = ['a', 'b', 'c', 'd']
a, b, c, d = map(sp.Symbol, symbols )
expr = a + b*(c+d)/np.sum(b + c*d)
n = 1
dim = {} # collections.OrderedDict()
[dim.update( {i: n} ) for i in [a, b, c, d] ]
dt = {} # collections.OrderedDict()
[dt.update( {i: 'float64'} ) for i in [a, b, c, d] ]
f = theano_function( [a, b, c, d], [expr], dims = dim, dtypes=dt )
in_var = np.array([ [1,2,3,4] ])
f(in_var.T)
TypeError: ('Bad input argument to theano function at index 0(0-based)', 'Wrong number of dimensions: expected 1, got 2 with shape (4, 1).')
如果我尝试使用自动换行编译一个简单的表达式:
import sympy as sp
from sympy.utilities.autowrap import autowrap
m, n = sp.symbols('m n', integer=True)
a, b, c,d = map(sp.IndexedBase, ['a', 'b', 'c', 'd'])
i = sp.Idx('i',m)
j = sp.Idx('j',n)
instruction = sp.Eq(a[i], b[i]*(c[i] + d[i]) )
f = autowrap(instruction)
我得到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 3749: ordinal not in range(128)
【问题讨论】:
-
到底是什么失败了?它因什么错误而失败?