Building more complex expressions

Of course, we've mostly covered how to build simple equations; however, what happens if your equation is a little bit more complicated, for example, like the following:

z = Wx + b

We can also very easily do this by changing our code a bit to add the following line:

b := G.NewScalar(g,
tensor.Float64,
G.WithName("b"),
G.WithValue(3.0)
)

Then, we can change our definition for z slightly, as shown here:

a, err := G.Mul(mat, vec)
if err != nil {
log.Fatal(err)
}

z, err := G.Add(a, b)
if err != nil {
log.Fatal(err)
}

As you can see, we've created a multiplication operator node, and then created an addition operator node on top of that.

Alternatively, you can also just do it in a single line, as follows:

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

Notice that we use Must here to suppress the error object; we are merely doing it here for convenience, as we know that the operation to add this node to the graph will work. It is important to note that you may want to restructure this code to create the node for addition separately so that you can have error handling for each step.

If you now proceed to build and execute the code, you will find that it will produce the following:

// Output: [12.4 6.4]

The computation graph now looks like the following screenshot:

You can see that W and x both feed into the first operation (our multiplication operation) and then, later, it feeds into our addition operation to produce our results.

That's an introduction to using Gorgonia! As you can now hopefully see, it is a library that contains the necessary primitives that will allow us to build the first simple, and then more complicated, neural networks in the following chapters.

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

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