【发布时间】:2018-05-02 09:57:34
【问题描述】:
希望有人可以帮助我。我使用谷歌或这个网站没有找到我的问题的答案。
我正在尝试按名称访问 TesorFlow 优化器。这是一些最小的示例代码: 导入系统 将 numpy 导入为 np 将张量流导入为 tf
print( "Python version: {0}".format(sys.version) )
print( "Tensorflow version: {0}".format(tf.__version__) )
print('')
l_input = tf.placeholder(tf.float32, shape=(None, 2), name='input')
l_dense = tf.layers.dense(l_input, units=1, activation=None)
l_output = tf.identity(l_dense, name='output')
l_true = tf.placeholder(tf.float32, shape=(None, 2), name='true')
cost = tf.reduce_sum(tf.square(l_output - l_true),name='cost')
train_step = tf.train.AdamOptimizer(0.001,name='train_step').minimize(cost)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print( "cost" )
print( cost )
print( "cost:0" )
print( tf.get_default_graph().get_tensor_by_name("cost:0") )
print('')
print( "train_step" )
print( train_step )
print( "type(train_step)" )
print( type(train_step) )
print( "collection train_step:0" )
print( tf.get_default_graph().get_collection("train_step:0") )
print( "operation train_step:0" )
print( tf.get_default_graph().get_operation_by_name("train_step:0") )
print( "tensor train_step:0" )
print( tf.get_default_graph().get_tensor_by_name("train_step:0") )
输出如下:
Python version: 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]
Tensorflow version: 1.8.0
cost
Tensor("cost:0", shape=(), dtype=float32)
cost:0
Tensor("cost:0", shape=(), dtype=float32)
train_step
name: "train_step"
op: "NoOp"
....
type(train_step)
<class 'tensorflow.python.framework.ops.Operation'>
collection train_step:0
[]
operation train_step:0
所以,它适用于成本张量。但是,我无法让它与 train_step 操作一起使用。为什么我要尝试 get_collection?这是我发现的唯一一个不会引发异常的函数。
由于类型是操作,我尝试了 get_operation_by_name 并以异常结束
....
ValueError: Name 'train_step:0' appears to refer to a Tensor, not a Operation.
注释掉并使用 get_tensor_by_name 我得到以下异常
....
KeyError: "The name 'train_step:0' refers to a Tensor which does not exist. The operation, 'train_step', exists but only has 0 outputs."
我想加载保存的图表并通过在 train_step 上调用 sess.run() 继续训练。但是,为此,我确实需要以某种方式访问 train_step 操作。我发现了使用 get_tensor_by_name 的旧示例,但这些示例已停止工作并出现相同的异常。
非常感谢任何帮助。
【问题讨论】:
标签: python tensorflow