Tensorflow: How to get a tensor by name?

后端 未结 3 645
抹茶落季
抹茶落季 2020-11-28 08:11

I\'m having trouble recovering a tensor by name, I don\'t even know if it\'s possible.

I have a function that creates my graph:

def create_structure(         


        
相关标签:
3条回答
  • 2020-11-28 08:51

    All tensors have string names which you can see as follows

    [tensor.name for tensor in tf.get_default_graph().as_graph_def().node]
    

    Once you know the name you can fetch the Tensor using <name>:0 (0 refers to endpoint which is somewhat redundant)

    For instance if you do this

    tf.constant(1)+tf.constant(2)
    

    You have the following Tensor names

    [u'Const', u'Const_1', u'add']
    

    So you can fetch output of addition as

    sess.run('add:0')
    

    Note, this is part not part of public API. Automatically generated string tensor names are an implementation detail and may change.

    0 讨论(0)
  • 2020-11-28 08:54

    All you gotta do in this case is:

    ft=tf.get_variable('scale1/Scale1_first_relu:0')
    
    0 讨论(0)
  • 2020-11-28 08:58

    There is a function tf.Graph.get_tensor_by_name(). For instance:

    import tensorflow as tf
    
    c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
    d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
    e = tf.matmul(c, d, name='example')
    
    with tf.Session() as sess:
        test =  sess.run(e)
        print e.name #example:0
        test = tf.get_default_graph().get_tensor_by_name("example:0")
        print test #Tensor("example:0", shape=(2, 2), dtype=float32)
    
    0 讨论(0)
提交回复
热议问题