Reputation: 51
I hope to copy tensorflow variable from an old graph to a new graph, then delete the old graph and make the new graph as default. Below is my code, but it raises an AttributeError: 'Graph' object has no attribute 'variable1'
. I am new to tensorflow. Can any one give me a specific example?
import tensorflow as tf
import numpy as np
graph1 = tf.Graph()
with graph1.as_default():
variable1 = tf.Variable(np.array([2.,-1.]), name='x1')
initialize = tf.initialize_all_variables()
sess1 = tf.Session(graph=graph1)
sess1.run(initialize)
print('sess1:',variable1.eval(session=sess1))
graph2 = tf.Graph()
with graph2.as_default():
variable2 = tf.contrib.copy_graph.copy_variable_to_graph(graph1.variable1, graph2)
sess2 = tf.Session(graph=graph2)
#I want to remove graph1 and sess1, and make graph2 and sess2 the default here.
print('sess2:', variable2.eval(session=sess2))
Upvotes: 2
Views: 2322
Reputation: 49769
tf.initialize_all_variables()
is depricated. Use tf.global_variables_initializer()
instead.
You don't need graph1.variable1
. Simply pass variable1
.
You forgot to initialize variables in the second session:
initialize2 = tf.global_variables_initializer()
sess2=tf.Session(graph=graph2)
sess2.run(initialize2)
So your code should be like this:
import tensorflow as tf
import numpy as np
graph1 = tf.Graph()
with graph1.as_default():
variable1 = tf.Variable(np.array([2.,-1.]), name='x1')
initialize = tf.global_variables_initializer()
sess1=tf.Session(graph=graph1)
sess1.run(initialize)
print('sess1:',variable1.eval(session=sess1))
graph2 = tf.Graph()
with graph2.as_default():
variable2=tf.contrib.copy_graph.copy_variable_to_graph(variable1,graph2)
initialize2 = tf.global_variables_initializer()
sess2=tf.Session(graph=graph2)
sess2.run(initialize2)
#I want to remove graph1 and sess1, ande make graph2 and sess2 as default here.
print('sess2:',variable2.eval(session=sess2))
Upvotes: 3