Vectors and matrices

Of course, being able to add to numbers isn't why we're here; we're here to work with tensors, and eventually, DL equations, so let's take the first step toward something a little more complicated.

The goal here is to now create a graph that will compute the following simple equation:

z = Wx

Note that W is an n x n matrix, and x is a vector of size n. For the purposes of this example, we will use n = 2.1957.

Again, we start with the same basic main function, as shown here:

package main

import (
"fmt"
"log"

G "gorgonia.org/gorgonia"
"gorgonia.org/tensor"
)

func main() {
g := NewGraph()
}

You'll notice that we've chosen to alias the Gorgonia package as G.

We then create our first tensor, the matrix, W, like so:

matB := []float64{0.9,0.7,0.4,0.2}
matT := tensor.New(tensor.WithBacking(matB), tensor.WithShape(2, 2))
mat := G.NewMatrix(g,
tensor.Float64,
G.WithName("W"),
G.WithShape(2, 2),
G.WithValue(matT),
)

You'll notice that we've done things a bit differently this time around, as listed here:

  1. We've started by declaring an array with the values that we want in our matrix
  2. We've then created a tensor from that matrix with a shape of 2 x 2, as we want a 2 x 2 matrix
  3. After all of that, we've then created a new node in our graph for the matrix, given it the name W, and initialized it with the value of the tensor

We then create our second tensor and input node the same way, the vector, x, as follows:

vecB := []float64{5,7}

vecT := tensor.New(tensor.WithBacking(vecB), tensor.WithShape(2))

vec := G.NewVector(g,
tensor.Float64,
G.WithName("x"),
G.WithShape(2),
G.WithValue(vecT),
)

Just like last time, we then add an operator node, z, that will multiply the two (instead of an addition operation):

z, err := G.Mul(mat, vec)

Then, as last time, create a new tape machine and run it, as shown here, and then print the result:

machine := G.NewTapeMachine(g)
if machine.RunAll() != nil {
log.Fatal(err)
}
fmt.Println(z.Value().Data())
// Output: [9.4 3.4]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.139.168