Array operations in 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, op.PlaceholderShape(tf.MakeShape(3, 3)))
ph2 := op.Placeholder(s.SubScope("ph2"), tf.Float, op.PlaceholderShape(tf.MakeShape(3, 3)))

Now we create an operation to perform element wise multiplication.

mul := op.Mul(s, ph1, ph2)

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,
}

Output is now mulOP.

output := []tf.Output{
  mul,
}

And as before, we create and run a session.

sess, err := tf.NewSession(graph, nil)
result, err := sess.Run(input, output, nil)
value := result[0].Value().([][]float32)
fmt.Println(value)

Conclusion

Here I have described using go TF to perform element wise operations on multi dimensional arrays of floats.

Last updated on: Mon, Nov 27, 2017