forked from gorgonia/gorgonia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_symdiff_test.go
54 lines (43 loc) · 1.04 KB
/
example_symdiff_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package gorgonia_test
import (
"fmt"
"log"
. "github.com/chewxy/gorgonia"
)
// SymbolicDiff showcases symbolic differentiation
func Example_symbolicDiff() {
g := NewGraph()
var x, y, z *Node
var err error
// define the expression
x = NewScalar(g, Float64, WithName("x"))
y = NewScalar(g, Float64, WithName("y"))
if z, err = Add(x, y); err != nil {
log.Fatal(err)
}
// symbolically differentiate z with regards to x and y
// this adds the gradient nodes to the graph g
var grads Nodes
if grads, err = Grad(z, x, y); err != nil {
log.Fatal(err)
}
// create a VM to run the program on
machine := NewTapeMachine(g)
// set initial values then run
Let(x, 2.0)
Let(y, 2.5)
if err = machine.RunAll(); err != nil {
log.Fatal(err)
}
fmt.Printf("z: %v\n", z.Value())
if xgrad, err := x.Grad(); err == nil {
fmt.Printf("dz/dx: %v | %v\n", xgrad, grads[0].Value())
}
if ygrad, err := y.Grad(); err == nil {
fmt.Printf("dz/dy: %v | %v\n", ygrad, grads[1].Value())
}
// Output:
// z: 4.5
// dz/dx: 1 | 1
// dz/dy: 1 | 1
}