简体   繁体   English

如何使用Sympy推导出一个Matrix元素

[英]How to derive with respect to a Matrix element with Sympy

Given the product of a matrix and a vector 给定矩阵和向量的乘积

Av AV

with A of shape (m,n) and v of dim n, where m and n are symbols, I need to calculate the Derivative with respect to the matrix elements. 对于形状(m,n)和v的dim n,其中m和n是符号,我需要相对于矩阵元素计算导数。 I haven't found the way to use a proper vector, so I started with 2 MatrixSymbol : 我还没有找到使用正确向量的方法,所以我从2个MatrixSymbol开始:

n, m = symbols('n m')
j = tensor.Idx('j')
i = tensor.Idx('i')
l = tensor.Idx('l')
h = tensor.Idx('h')
A = MatrixSymbol('A', n,m)
B = MatrixSymbol('B', m,1)
C=A*B

Now, if I try to derive with respect to one of A's elements with the indices I get back the unevaluated expression: 现在,如果我尝试使用索引来获取A的元素之一,我会回到未评估的表达式:

diff(C, A[i,j])
>>>> Derivative(A*B, A[i, j])

If I introduce the indices in C also (it won't let me use only one index in the resulting vector) I get back the product expressed as a Sum: 如果我也在C中引入索引(它不会让我在结果向量中只使用一个索引)我得到了表示为Sum的产品:

C[l,h]
>>>> Sum(A[l, _k]*B[_k, h], (_k, 0, m - 1))

If I derive this with respect to the matrix element I end up getting 0 instead of an expression with the KroneckerDelta , which is the result that I would like to get: 如果我相对于矩阵元素得到这个,我最终得到0而不是带有KroneckerDelta的表达式,这是我想得到的结果:

diff(C[l,h], A[i,j])
>>>> 0

I wonder if maybe I shouldn't be using MatrixSymbols to start with. 我想知道是否我不应该使用MatrixSymbols开始。 How should I go about implementing the behaviour that I want to get? 我应该如何实现我想要的行为?

SymPy does not yet know matrix calculus ; SymPy 还不知道矩阵演算 ; in particular, one cannot differentiate MatrixSymbol objects. 特别是,无法区分MatrixSymbol对象。 You can do this sort of computation with Matrix objects filled with arrays of symbols; 您可以使用填充了符号数组的Matrix对象进行此类计算; the drawback is that the matrix sizes must be explicit for this to work. 缺点是矩阵大小必须明确才能使其工作。

Example: 例:

from sympy import *
A = Matrix(symarray('A', (4, 5)))
B = Matrix(symarray('B', (5, 3)))
C = A*B
print(C.diff(A[1, 2]))

outputs: 输出:

Matrix([[0, 0, 0], [B_2_0, B_2_1, B_2_2], [0, 0, 0], [0, 0, 0]])

The git version of SymPy (and the next version) handles this better: SymPy(以及下一个版本)的git版本可以更好地处理这个问题:

In [55]: print(diff(C[l,h], A[i,j]))
Sum(KroneckerDelta(_k, j)*KroneckerDelta(i, l)*B[_k, h], (_k, 0, m - 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM