2020.4.28. Added: Differentiate scalar function with vector
Good evening, I'm an old engineer. My time isn't over yet. However, it seems that the era of Numpy when it comes to matrix operations is over. Its name is Sympy (I don't think it's a new py)!
For the time being, you can do something like this.
python
#%%
import sympy as sym
from IPython.display import Math, display
#Define variables
(x, y, p, q) = sym.symbols("x y p q")
#Define a matrix
A = sym.Matrix([
[x,2*x,3*x],
[4*x,5*x,6*x]
])
display((Math(f"A={sym.latex(A)}")))
B = sym.Matrix([
[y,y],
[4*y,5*y],
[7*y,y]
])
display((Math(f"B={sym.latex(B)}")))
#Define vector function
xy = sym.Matrix([
[x,y]
])
display((Math(f"xy={sym.latex(xy)}")))
pq = sym.Matrix([
[3*x*y,2*x+y]
])
display((Math(f"pq={sym.latex(pq)}")))
#Define scalar function
f = x**2
#Multiplication between matrices
C = A * B
display((Math(f"C=AB={sym.latex(C)}")))
#Matrix x,Substitute a number for y
C1 = C.subs({x:10, y: 20})
display((Math(f"C(10,20)={sym.latex(C1)}")))
#Partial derivative of the matrix with respect to x
dCdx = sym.diff(C, x)
display((Math(r"\frac{\partial C}{\partial x}"f"={sym.latex(dCdx)}")))
#Partial derivative of the matrix with respect to y
dCdy = sym.diff(C, y)
display((Math(r"\frac{\partial C}{\partial y}"f"={sym.latex(dCdy)}")))
#Differentiate the scalar function with a vector
dfdxy = sym.diff(f, xy)
display((Math(r"\frac{df}{dxy}"f"={sym.latex(dfdxy)}")))
#Differentiate vector function by vector
dpqdxy = sym.diff(pq, xy.T)
display((Math(r"\frac{dpq}{dxy}"f"={sym.latex(dpqdxy)}")))
#Differentiate the scalar function with a matrix(I get an error)
# dfdA = sym.diff(f, A)
# display((Math(r"\frac{df}{dA}"f"={sym.latex(dfdA)}")))
Try copying and copying from # %% on the first line with Visual Studio Code.
You can't do it normally. Poke the Run Cell in the figure below.
Then, something like this will come out!
Of course, the elements of the matrix can be numbers, but they can also be letters as in the example above. The calculation is also done with characters. Furthermore, you can assign a numerical value to this character (variable), like Mr. Tanaka who puts a mathematical formula There is also a pervert ... Since it is possible to differentiate with a vector, when teaching the chain rule of backpropagation It seems to be usable. So I'm going to have lunch.
Recommended Posts