Import tensorflow library
In [2]:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
print('Tensorflow version', tf.__version__)
Specify operations, i.e., the computation graph. Here we add two vectors that are given by two constants a and b and stored in a result file.
In [3]:
a = tf.constant([1,2,3], dtype=tf.float32)
b = tf.constant([5,6,7], dtype=tf.float32)
result = tf.multiply(a,b)
print(a)
print(b)
print(result)
We can see that the objects a, b, and c are Tensorflow-objects that are objects and do not carry the result as such. We have built a computation graph linking variables a and b to the result via the (element-wise) multiplication.
The computation graph only specifies the operations, but doesn't do the computations. The computations as such are carried out in a session. We can start a session and then run the session obtaining the result. Note that the session only carries out the computations that we specify, and so that we can save complexity.
In [4]:
with tf.Session() as session:
output = session.run(result)
print(output)
So far, we have generated two constants that we have multiplied. This is not very exciting and pretty static. In order to manipulate with the outside world, we need an interface concept. Interfacing to the outside world is done using tf.placeholder which is a placeholder for an input tensor. We can then manipulate this input tensor in any way we like.
In [6]:
# this vector is a scalar
x = tf.placeholder(tf.float32)
# this placeholder is a tensor with a single dimension and 2 entries
y = tf.placeholder(shape=(2), dtype=tf.float32)
# add a constanht
z = tf.constant([1,2], dtype=tf.float32)
# compute dot product between y and z and add x. Note that we can either use tf.add or use the `+` sign
result2 = tf.tensordot(z, y, 1) +x
The placeholders are passed to the session via the feed_dict data structure
In [7]:
with tf.Session() as session:
output = session.run(result2, feed_dict = {x: 1.5, y: [1,3]})
print(output)
In [ ]: