AccessTensorFlow优化器的名称

时间:2018-05-02 09:57:34

标签: python tensorflow

希望有人能帮助我。我没有使用谷歌或这个网站找到我的问题的答案。

我正在尝试按名称访问TesorFlow优化器。这是一些最小的示例代码:     导入系统     导入numpy为np     导入tensorflow为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的旧示例,但是那些已停止使用相同的异常。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

train_step操作而不是张量,它没有输出。因此,train_step:0没有任何意义,因为它试图指向操作的第一个输出。尝试

print( tf.get_default_graph().get_operation_by_name( "train_step" ) )