Matrix multiplication using Go TF

The previous post, I described using the go TensorFlow bindings to add two integers. Now I describe using go TF to perform somewhat more interesting computation.

As before, create a new scope.

s := op.NewScope()

Create two placeholders. Notice that this time they are of type tf.Float.

ph1 := op.Placeholder(s.SubScope("ph1"), tf.Float)
ph2 := op.Placeholder(s.SubScope("ph2"), tf.Float)

Now we create several operations.

sumOP := op.Add(s, ph1, ph2)
matMulOP := op.MatMul(s, ph1, ph2)
reLuOP := op.Relu(s, matMulOP)

Finalize the graph.

graph, err := s.Finalize()

Create the two input tensors. Note that they are now arrays of arrays of floats.

tensor1, err := tf.NewTensor([][]float32{[]float32{-4.6,5.91,6.40},[]float32{2.653,-3.21,4.316},[]float32{2.675,3,4}})
tensor2, err := tf.NewTensor([][]float32{[]float32{4,-5.61,6.8},[]float32{2.642,3.653,-4.4},[]float32{2.12,3,4}})

Input is the same as before.

input := map[tf.Output]*tf.Tensor{
  ph1: tensor1,
  ph2: tensor2,
}

However the output list now contains three elements. For their are now three operations whose output we wish to know.

output := []tf.Output{
  sumOP,
  matMulOP,
  reLuOP,
}

And as before, we create and run a session.

sess, err := tf.NewSession(graph, nil)
result, err := sess.Run(input, output, nil)

This time, sess.Run returns an array of three tensors, one for each of the three operations whose output we requested of it.

Note that matMulOP was only computed once, despite being requested twice. Lazy evaluation allow for performance optimizations.

Conclusion

Here I have described using go TF to perform more complex operations on multi dimensional arrays of floats. I also demonstrate the use of multiple output operations.

Last updated on: Wed, May 24, 2017