如何将变量复制到张量流中的另一个图形 [英] how to copy variable to another graph in tensorflow

查看:33
本文介绍了如何将变量复制到张量流中的另一个图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将tensorflow变量从旧图复制到新图,然后删除旧图并将新图设为默认值.下面是我的代码,但它引发了 AttributeError: 'Graph' object has no attribute 'variable1'.我是张量流的新手.谁能举个具体的例子?

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))

推荐答案

  1. tf.initialize_all_variables() 已弃用.改用 tf.global_variables_initializer().

您不需要 graph1.variable1.只需传递 variable1.

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))

这篇关于如何将变量复制到张量流中的另一个图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆