Note
Go to the end to download the full example code.
EinSum: Matrix-vector product
Using EinSum to perform matrix-vector product
\(\mathbf{y}=\mathbf{A}\mathbf{b}\)
No sensitivities need to be defined by the user, as these are automatically deduced from the requested multiplication
operation in pymoto.EinSum.
11 import pymoto as pym
12 import numpy as np
13
14 if __name__ == "__main__":
15 print(__doc__)
16
17 # --- INITIALIZATION ---
18 A = pym.Signal("A")
19 b = pym.Signal("b")
20
21 N = 5 # Size
22 A.state = np.random.rand(N, N)
23 b.state = np.random.rand(N)
24 print(f"{A.tag} = {A.state}")
25 print(f"{b.tag} = {b.state}")
26
27 # --- FORWARD ANALYSIS ---
28 with pym.Network() as fn:
29 # Matrix-vector product
30 y1 = pym.EinSum("ij,j->i")(A, b)
31 y1.tag = "y1"
32
33 print(f"The response is {y1.tag} = {y1.state}")
34
35 # --- BACKPROPAGATION ---
36 dgdy1 = np.ones_like(y1.state) # Seed the output sensitivity
37 y1.sensitivity = dgdy1
38 fn.sensitivity() # Run the backpropagation
39 print("\nThe sensitivities are:")
40 print(f"dg/d{A.tag} = {A.sensitivity}")
41 print(f"dg/d{b.tag} = {b.sensitivity}")
42
43 # --- Finite difference check ---
44 pym.finite_difference([A, b], y1)