Tensorflow:无法从倒数第二层提取特征向量

时间:2016-11-10 08:58:53

标签: python tensorflow

我想从倒数第二层使用预先训练好的网络从图像中提取特征向量。

我跑的时候:

from neural_network import NET


x = tf.placeholder(tf.float32, shape=[1, 144, 144, 3])

net = NET({'data': x})
sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
net.load('inference.npy', sess)

feature = sess.graph.get_tensor_by_name('fc7:0')

我收到了错误消息:

KeyError: "The name 'fc7:0' refers to a Tensor which does not exist. The operation, 'fc7', does not exist in the graph."

另一方面,如果我用:

替换最后一行
 feature = sess.graph.get_tensor_by_name('global_pool:0')

然后它有效。

我的neural_network.py文件的结尾是:

    (self.feed('inception_3b_pool',
               'inception_3b_3x3',
               'inception_3b_double_3x3_2')
         .concat(3, name='inception_3b_output')
         .avg_pool(9, 4, 1, 1, padding='VALID', name='global_pool') 
         .fc(256, relu=False, name='fc7'))

并且fc层的定义是:

def fc(self, input, num_out, name, relu=True):
    with tf.variable_scope(name) as scope:
        input_shape = input.get_shape()
        if input_shape.ndims == 4:
            # The input is spatial. Vectorize it first.
            dim = 1
            for d in input_shape[1:].as_list():
                dim *= d
            feed_in = tf.reshape(input, [-1, dim])
        else:
            feed_in, dim = (input, input_shape[-1].value)
        weights = self.make_var('weights', shape=[dim, num_out])
        biases = self.make_var('biases', [num_out])
        op = tf.nn.relu_layer if relu else tf.nn.xw_plus_b
        fc = op(feed_in, weights, biases, name=scope.name)
        return fc

3 个答案:

答案 0 :(得分:0)

通常,fc图层的输出是BiasAdd节点,输出张量名称类似于fc7/BiasAdd:0。 虽然这取决于fc方法的实施。

我认为在张量板中加载图形并查找输出节点名称是有意义的。

答案 1 :(得分:0)

feature = sess.graph.get_tensor_by_name("fc7/fc7:0") 

工作

另见https://www.tensorflow.org/versions/r0.11/how_tos/variable_scope/index.html

答案 2 :(得分:0)

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

列出图表的所有张量名称。使用打印所需张量的输出 sess.graph.get_tensor_by_name(<tensor_operation_name>:<output_index>")

Ex:&#34; fc7 / fc7:0&#34;