TensorFlow is an open source software library developed by the Google Brain team; it has functions and APIs for implementing deep neural networks. It works with Python, C++, Java, R, and Go. It can be used to work on multiple platforms, CPU, GPU, mobile, and even distributed. TensorFlow allows for model deployment and ease of use in production. The optimizer in TensorFlow makes the task of training deep neural networks easier by automatically calculating gradients and applying them to update weights and biases.
In TensorFlow, a program has two distinct components:
- Computation graph is a network of nodes and edges. Here all of the data, variables, placeholders, and the computations to be performed are defined. TensorFlow supports three types of data objects: constants, variables, and placeholders.
- Execution graph actually computes the network using a Session object. Actual calculations and transfer of information from one layer to another takes place in the Session object.
Let's see the code to perform matrix multiplication in TensorFlow. The whole code can be accessed from the GitHub repository (https://github.com/PacktPublishing/Hands-On-Artificial-Intelligence-for-IoT) filename, matrix_multiplication.ipynb:
import tensorflow as tf
import numpy as np
This part imports the TensorFlow module. Next, we define the computation graph. mat1 and mat2 are two matrices we need to multiply:
# A random matrix of size [3,5]
mat1 = np.random.rand(3,5)
# A random matrix of size [5,2]
mat2 = np.random.rand(5,2)
We declare two placeholders, A and B, so that we can pass their values at runtime. In the computation graph, we declare all of the data and computation objects:
# Declare placeholders for the two matrices
A = tf.placeholder(tf.float32, None, name='A')
B = tf.placeholder(tf.float32, None, name='B')
This declares two placeholders with the names A and B; the arguments to the tf.placeholder method specify that the placeholders are of the float32 datatype. Since the shape specified is None, we can feed it a tensor of any shape and an optional name for the operation. Next, we define the operation to be performed using the matrix multiplication method, tf.matmul:
C = tf.matmul(A,B)
The execution graph is declared as a Session object, which is fed the two matrices, mat1 and mat2, for the placeholders, A and B, respectively:
with tf.Session() as sess:
result = sess.run(C, feed_dict={A: mat1, B:mat2})
print(result)