Now, we know how to manipulate variables inside TensorFlow, but what about feeding data outside of a TensorFlow model?
If you want to feed data to a TensorFlow model from outside a model, you will need to use placeholders.
So, what are these placeholders and what do they do? Placeholders can be seen as holes in your model, holes that you will pass the data to. You can create them using tf.placeholder(datatype), where datatype specifies the type of data (integers, floating points, strings, and Booleans) along with its precision (8, 16, 32, and 64) bits.
The definition of each data type with the respective Python syntax is defined as:
Table 3 – Definition of different TensorFlow data types
Data type |
Python type |
Description |
DT_FLOAT |
tf.float32 |
32-bits floating point. |
DT_DOUBLE |
tf.float64 |
64-bits floating point |
DT_INT8 |
tf.int8 |
8-bits signed integer. |
DT_INT16 |
tf.int16 |
16-bits signed integer. |
DT_INT32 |
tf.int32 |
32-bits signed integer. |
DT_INT64 |
tf.int64 |
64-bits signed integer. |
DT_UINT8 |
tf.uint8 |
8-bits unsigned integer. |
DT_STRING |
tf.string |
Variable length byte arrays. Each element of a Tensor is a byte array. |
DT_BOOL |
tf.bool |
Boolean. |
DT_COMPLEX64 |
tf.complex64 |
Complex number made of two 32-bits floating points: real and imaginary parts. |
DT_COMPLEX128 |
tf.complex128 |
Complex number made of two 64-bits floating points: real and imaginary parts. |
DT_QINT8 |
tf.qint8 |
8-bits signed integer used in quantized ops. |
DT_QINT32 |
tf.qint32 |
32-bits signed integer used in quantized ops. |
DT_QUINT8 |
tf.quint8 |
8-bits unsigned integer used in quantized ops. |
So let's create a placeholder:
a=tf.placeholder(tf.float32)
And define a simple multiplication operation:
b=a*2
Now, we need to define and run the session, but since we created a hole in the model to pass the data, when we initialize the session. We are obliged to pass an argument with the data; otherwise we get an error.
To pass the data to the model, we call the session with an extra argument, feed_dict, in which we should pass a dictionary with each placeholder name followed by its respective data, just like this:
with tf.Session() as sess:
result = sess.run(b,feed_dict={a:3.5})
print result
Output:
7.0
Since data in TensorFlow is passed in the form of multidimensional arrays, we can pass any kind of tensor through the placeholders to get the answer to the simple multiplication operation:
dictionary={a: [ [ [1,2,3],[4,5,6],[7,8,9],[10,11,12] ] , [ [13,14,15],[16,17,18],[19,20,21],[22,23,24] ] ] }
with tf.Session() as sess:
result = sess.run(b,feed_dict=dictionary)
print result
Output:
[[[ 2. 4. 6.]
[ 8. 10. 12.]
[ 14. 16. 18.]
[ 20. 22. 24.]]
[[ 26. 28. 30.]
[ 32. 34. 36.]
[ 38. 40. 42.]
[ 44. 46. 48.]]]