Skip to content

Instantly share code, notes, and snippets.

@gSrikar
Last active July 24, 2017 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gSrikar/31622f720b5e3d131c7465cfa374f2d0 to your computer and use it in GitHub Desktop.
Save gSrikar/31622f720b5e3d131c7465cfa374f2d0 to your computer and use it in GitHub Desktop.
Gist explains how to perform Arithmetic operations in Tensorflow and show it in a computational graph. For more detailed explanation, check out the my blog post https://gsrikar.blogspot.com/2017/07/arithmetic-operations-tensorflow.html
'''
Class performs arithmetic operations on multiple tensors and
shows the Computational graph with the help of Tensorboard.
Uses constants for arithmetic operations
'''
import tensorflow as tf
def main():
'''
Main Method
'''
# Create tensors
node1 = tf.constant(35)
node2 = tf.constant(76)
node3 = tf.constant(11)
node4 = tf.constant(10)
node5 = tf.constant(100)
print('Node 1: ', node1) # Tensor("Const:0", shape=(), dtype=int32)
print('Node 2: ', node2) # Tensor("Const_1:0", shape=(), dtype=int32)
print('Node 3: ', node3) # Tensor("Const_2:0", shape=(), dtype=int32)
print('Node 4: ', node4) # Tensor("Const_3:0", shape=(), dtype=int32)
print('Node 5: ', node5) # Tensor("Const_4:0", shape=(), dtype=int32)
# Add node1 and node2
node_add = tf.add(node1, node2)
print('Node Add: ', node_add) # Tensor("Add:0", shape=(), dtype=int32)
# Subtract node_add and node3
node_subtract = tf.subtract(node_add, node3)
print('Node Subtract: ', node_subtract) # Tensor("Sub:0", shape=(), dtype=int32)
# Multiply node_subtract and node4
node_multiply = tf.multiply(node_subtract, node4)
print('Node Multiply: ', node_multiply) # Tensor("Mul:0", shape=(), dtype=int32)
# Divide node_multiply and node5
node_divide = tf.divide(node_multiply, node5)
print('Node Divide: ', node_divide) # Tensor("truediv:0", shape=(), dtype=float64)
# Output node or Final node
output = node_add + node_subtract + node_multiply
print('Ouptut Node: ', output) # Tensor("add_1:0", shape=(), dtype=int32)
# Start the session
with tf.Session() as sess:
# Output value
output_value = sess.run(output)
print('Session: Output value: ', output_value) # Output value: 1211
# Create a summary
summary = tf.Summary(value=[
tf.Summary.Value(tag="summary_basic_math", simple_value=output_value)
])
# Create the event file inside logs directory
writer = tf.summary.FileWriter("logs/", sess.graph)
# Add the summary to the writer
writer.add_summary(summary)
if __name__ == "__main__":
'''
Starting point
'''
# This file is being run directly
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment