EDIT: The answer below is just to add a disconnected constant to a graph, if you want to add a new adding operation then it would be something like this:
import tensorflow as tf
constant_value = ...
with tf.Graph().as_default():
gd = tf.GraphDef()
with open('my_graph.pb', 'rb') as f:
gd.MergeFromString(f.read())
my_tensor = tf.import_graph_def(gd, name='', return_elements='SomeOperation:0')
tf.add(my_tensor, constant_value, name='NewOperation')
tf.train.write_graph(tf.get_default_graph(), '.',
'my_modified_graph.pb', as_text=False)
Note however this just adds new operations, it does not modify the value of the original tensor. I'm not sure which one of these is what you wanted.
The most practical way is to import the graph, add the constant and save it again:
import tensorflow as tf
new_constant = ...
with tf.Graph().as_default():
gd = tf.GraphDef()
with open('my_graph.pb', 'rb') as f:
gd.MergeFromString(f.read())
tf.import_graph_def(gd, name='')
tf.constant(new_constant, name='NewConstant')
tf.train.write_graph(tf.get_default_graph(), '.',
'my_graph_with_constant.pb', as_text=False)
If for some reason you don't want to import the graph, you can manually build the node object like this:
import numpy as np
import tensorflow as tf
from tensorflow.core.framework.tensor_pb2 import TensorProto
from tensorflow.core.framework.tensor_shape_pb2 import TensorShapeProto
# New constant to add
my_value = np.array([[1, 2, 3], [4, 5,6]], dtype=np.int32)
# Make graph node
tensor_content = my_value.tobytes()
dt = tf.as_dtype(my_value.dtype).as_datatype_enum
tensor_shape = TensorShapeProto(dim=[TensorShapeProto.Dim(size=s) for s in my_value.shape])
tensor_proto = TensorProto(tensor_content=tensor_content,
tensor_shape=tensor_shape,
dtype=dt)
node = tf.NodeDef(name='MyConstant', op='Const',
attr={'value': tf.AttrValue(tensor=tensor_proto),
'dtype': tf.AttrValue(type=dt)})
# Read existing graph
gd = tf.GraphDef()
with open('my_graph.pb', 'rb') as f:
gd.MergeFromString(f.read())
# Add new node
gd.node.extend([node])
# Save modified graph
tf.train.write_graph(tf.get_default_graph(), '.',
'my_graph_with_constant.pb', as_text=False)
Note this case is relatively easy because the node is not connected to any other node.