python - 按名称访问TensorFlow优化器
问题描述
希望有人能帮助我。我没有使用谷歌或这个网站找到我的问题的答案。
我正在尝试按名称访问 TesorFlow 优化器。这是一些最小的示例代码: import sys import numpy as np import tensorflow as 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 的较旧示例,但这些示例已停止使用相同的异常。
任何帮助是极大的赞赏。
解决方案
train_step
是一个操作而不是张量,它没有输出。因此train_step:0
,什么都没有,因为它试图指向操作的第一个输出。尝试
print( tf.get_default_graph().get_operation_by_name( "train_step" ) )
推荐阅读
- c# - 身份验证过期时使用自己的 redirectUri
- c++ - 我一直试图克隆一个需要 cmake 文件和依赖项的 git 存储库
- java - 如何检查您是否仍然使用 jpa 连接到数据库
- kubernetes - 是否可以在 GCP kubernetes 内不使用特权模式运行 gcsfuse?
- php - 如何在 PHP 中获取 odata.nextlink(json 文件)中的值
- python - 火花会话状态
- excel - 有条件的排名
- sql - 在访问联接查询中使用子查询时出错
- javascript - 在 Google 表格中使用 fontcolor() 在单元格中返回 HTML
- ios - 如何使用子视图旋转角度获取滑块值