Tensors

Main Defining Characteristics

Shape: Size of each dimension
Datatype : Type of the elements in tensor

IMPORTANT: Dont create new tensors inside a large loop!. This will create graphs and slows down everything!

In [1]:
import tensorflow as tf

Initializing Constant tensor

In [27]:
tf.reset_default_graph()

# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7])
print(tensor)

tensor_2 = tf.constant(1,shape=(5,5),dtype=tf.float32)
print(tensor_2)
Tensor("Const:0", shape=(7,), dtype=int32)
Tensor("Const_1:0", shape=(5, 5), dtype=float32)

Building the graph

In [15]:
a = tf.constant(1,name="A")
b = tf.constant(2,name="B")
c = a+b #This tensor is an operation
print(a)
print(b)
print(c)
print(c.op)
Tensor("A:0", shape=(), dtype=int32)
Tensor("B:0", shape=(), dtype=int32)
Tensor("add_13:0", shape=(), dtype=int32)
name: "add_13"
op: "Add"
input: "A"
input: "B"
attr {
  key: "T"
  value {
    type: DT_INT32
  }
}

Important attributes

In [26]:
print("shape", tensor_2.shape)
print("data type", tensor_2.dtype)
print("name", tensor_2.name)
print("op", tensor_2.op)
print("graph", tensor_2.graph)
shape (5, 5)
data type <dtype: 'float32'>
name Const_1:0
op name: "Const_1"
op: "Const"
attr {
  key: "dtype"
  value {
    type: DT_FLOAT
  }
}
attr {
  key: "value"
  value {
    tensor {
      dtype: DT_FLOAT
      tensor_shape {
        dim {
          size: 5
        }
        dim {
          size: 5
        }
      }
      float_val: 1.0
    }
  }
}

graph <tensorflow.python.framework.ops.Graph object at 0x7f4b1895cda0>

Initializing constant string tensor

In [21]:
tf.reset_default_graph()

string_tensor = tf.constant(['a','b','c'])

print(string_tensor.shape)
print(string_tensor.dtype)
(3,)
<dtype: 'string'>

Initializing constant tensor with numpy array

In [9]:
import numpy as np
In [22]:
tf.reset_default_graph()

random_image = np.random.randint(0,256,(128,128,3))

image_tensor = tf.constant(random_image)
print(image_tensor)

#Appears to do the same job
#But useful when you have pandas dataframe
imgage_tensor_2 = tf.convert_to_tensor(random_image)
print(imgage_tensor_2)
Tensor("Const:0", shape=(128, 128, 3), dtype=int64)
Tensor("Const_1:0", shape=(128, 128, 3), dtype=int64)

Reduce operation

Operation that is carried out on every element in the tensor

In [36]:
tf.reset_default_graph()

tensor = tf.constant([1, 2, 3, 4, 5, 6, 7],name="reduce_this_tensor")
sum_t = tf.reduce_sum(tensor)
print(sum_t)

sess = tf.Session()
print("Reduce sum " , sess.run(sum_t))
print("Reduce product " , sess.run(tf.reduce_prod(tensor)))
Tensor("Sum:0", shape=(), dtype=int32)
Reduce sum  28
Reduce product  5040
In [37]:
!rm tensorboard_logs/*
In [38]:
writer = tf.summary.FileWriter('./tensorboard_logs',sess.graph)
writer.close()
sess.close()
In [39]:
!tensorboard --logdir=tensorboard_logs/
TensorBoard 1.12.0 at http://0f5261ab9fe2:6006 (Press CTRL+C to quit)
^C