Examples for Tensorflow : Session 1

Session conducted on 6th April, 2018 to explain TF basics


In [1]:
import tensorflow as tf


/home/pratyush/workspace/virtualenv/tflow/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters

1. Explaining c = a+b in tensorflow

Python style


In [2]:
a = 5
b = 10
c = a+b
print(c)


15

TF style


In [12]:
tf.add?

In [8]:
# Create computational graph
a = tf.constant(5, dtype=tf.float32)
b = tf.constant(10, dtype=tf.float32)
c = tf.add(a,b)

# execute this
with tf.Session() as sess:
    print(sess.run(c))


15.0

2. Using placeholders


In [9]:
tf.placeholder?

In [15]:
a = tf.placeholder(dtype=tf.float32, shape=(None))
b = tf.placeholder(dtype=tf.float32, shape=(None))
c = tf.add(a,b)

with tf.Session() as sess:
    print(sess.run(c, feed_dict={a:5, b:10}))


15.0

Multiply constant and placeholder vectors


In [21]:
tf.multiply?

In [17]:
a = tf.constant([1,2,3], dtype=tf.float32)
b = tf.constant([4,5,6], dtype=tf.float32)
c = tf.multiply(a,b)

with tf.Session() as sess:
    print(sess.run(c))


[ 4. 10. 18.]

In [27]:
a = tf.placeholder(dtype=tf.float32, shape=[3])
b = tf.placeholder(dtype=tf.float32, shape=[3])
c = tf.multiply(a,b)

with tf.Session() as sess:
    print(sess.run(c, feed_dict={a:[2,3,4], b:[5,6,7]}))


[10. 18. 28.]

3. Matrix multiplication (Python style)


In [28]:
import numpy as np

In [33]:
np.reshape?

In [32]:
a = np.arange(1,10,1)
print(a)


[1 2 3 4 5 6 7 8 9]

In [35]:
A = a.reshape((3,3))
A


Out[35]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [37]:
b = np.array([1,2,3])*0.1
b


Out[37]:
array([0.1, 0.2, 0.3])

In [38]:
x = np.dot(A,b)

In [39]:
print(x)


[1.4 3.2 5. ]

Matrix multiplication TF style


In [45]:
tf.matmul?

In [63]:
a1 = np.arange(1,10,1)
a2 = np.arange(1,4)*0.1

# Build the model
a = tf.placeholder(dtype=tf.float32, shape=[9])
b = tf.placeholder(dtype=tf.float32, shape=[3])
A = tf.reshape(a,[3,3])
b_ = tf.reshape(b,[3,1])
x = tf.matmul(A,b_)

with tf.Session() as sess:
    print(sess.run(x, feed_dict={a:a1, b:a2}))


[[1.4000001]
 [3.2      ]
 [5.       ]]