In [1]:
import tensorflow as tf
# Create a tensorflow constant
hello = tf.constant("Hello World!")
# Print this variable as is
print(hello)
Oops! That is not what we wanted! This is because the variable hello
hasn't been evaluated yet. Tensorflow needs a session to run the graph in!
In [2]:
# Create a new session
sess = tf.Session()
# Print the constant
print("Printing using Session.run()")
print(sess.run(hello))
# Also
print("Printing using eval() function")
print(hello.eval(session=sess))
In [3]:
# run addition and multiplication operations
a = tf.constant(25, tf.float32)
b = tf.constant(5, tf.float32)
with tf.Session() as sess:
print("A = %f"%sess.run(a))
print("B = %f"%sess.run(b))
print("A + B = %f"%sess.run(a+b))
print("A * B = %f"%sess.run(a*b))
print("A / B = %f"%sess.run(a/b))
print("A + B using tf add = %f"%sess.run(tf.add(a, b)))
print("A * B using tf multiply = %f"%sess.run(tf.multiply(a, b)))
Tensorflow placeholder is a promise to provide a value later (supplied/fed at execution time). For placeholders, an optional argument shape
can be used to make sure the input dimensions matches the required tensor dimensions.
If this is missing or None
(default), then the placeholder can accept any shape.
In [4]:
# Run addition and multiplication with placeholders
c = tf.placeholder(tf.float32, shape=())
d = tf.placeholder(tf.float32, shape=())
sum = tf.add(c, d)
prod = tf.multiply(c, d)
with tf.Session() as sess:
print("Operations by feeding values")
print("C = %f"%sess.run(c, feed_dict={c: 4}))
print("D = %f"%sess.run(d, feed_dict={d: 6}))
print("Sum = %f"%sess.run(sum, feed_dict={c: 4, d: 6}))
print("Prod = %f"%sess.run(prod, feed_dict={c: 4, d: 6}))
In [5]:
# Matrix operations with placeholders
import numpy as np
mat1 = tf.placeholder(tf.float32, shape=(2,2))
mat2 = tf.placeholder(tf.float32, shape=(2,1))
matmul = tf.matmul(mat1, mat2)
with tf.Session() as sess:
print("Matrix multiplication using python lists as feed dict values")
print(sess.run(matmul, feed_dict={ mat1: [[1,2],[2,1]], mat2: [[1],[2]]}))
print("Matrix multiplication using numpyarrays as feed dict values")
print(sess.run(matmul, feed_dict={ mat1: np.array([[1,2],[2,1]]), mat2: np.array([[1],[2]])}))