有没有一种矢量化的方法来计算sympy中的梯度? [英] Is there a vectorized way to calculate the gradient in sympy?
本文介绍了有没有一种矢量化的方法来计算sympy中的梯度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算sympy中多元函数的(符号)梯度?
How does one calculate the (symbolic) gradient of a multivariate function in sympy?
很明显,我可以分别计算每个变量的导数,但是有矢量化运算可以做到吗?
Obviously I could calculate separately the derivative for each variable, but is there a vectorized operation that does this?
例如
m=sympy.Matrix(sympy.symbols('a b c d'))
现在,对于i = 0..3,我可以这样做:
Now for i=0..3 I can do:
sympy.diff(np.sum(m*m.T),m[i])
这将起作用,但是我宁愿做类似的事情:
which will work, but I rather do something like:
sympy.diff(np.sum(m*m.T),m)
这不起作用("AttributeError:ImmutableMatrix没有属性_diff_wrt").
Which does not work ("AttributeError: ImmutableMatrix has no attribute _diff_wrt").
推荐答案
只需对m
使用列表理解:
[sympy.diff(sum(m*m.T), i) for i in m]
此外,除非使用数字值,否则请勿使用np.sum
.内置的sum
更好.
Also, don't use np.sum
unless you are working with numeric values. The builtin sum
is better.
这篇关于有没有一种矢量化的方法来计算sympy中的梯度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文