Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
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 =
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
if __name__ == "__main__":
Starting point
# This file is being run directly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.