代码之家  ›  专栏  ›  技术社区  ›  Atinesh

如何获得某一层训练CNN模型的输出[张量流]

  •  0
  • Atinesh  · 技术社区  · 6 年前

    我有一个 CNN 模型 image classification 我已经在我的数据集上训练过了。模型是这样的

    Convolution 
    Relu
    pooling
    
    Convolution 
    Relu
    Convolution 
    Relu
    pooling
    
    flat
    
    fully connected (FC1)
    Relu
    fully connected (FC2)
    softmax
    

    训练后,我想得到我输入到预训练模型的图像的特征向量,也就是说,我想得到 FC1 层。我浏览了一下网页,但找不到任何有用的建议,有没有什么好的帮助。

    训练脚本

    # input
    x = tf.placeholder(tf.float32, shape=[None, img_size_h, img_size_w, num_channels], name='x')
    # lables
    y_true     = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
    y_true_cls = tf.argmax(y_true, axis=1)
    
    y_pred = build_model(x)     # Builds model architecture
    y_pred_cls = tf.argmax(y_pred, axis=1)
    
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=y_pred, labels=y_true)
    cost = tf.reduce_mean(cross_entropy)
    
    optimizer = tf.train.MomentumOptimizer(learn_rate, 0.9, use_locking=False, use_nesterov=True).minimize(cost)
    
    accuracy  = tf.reduce_mean(tf.cast(tf.equal(y_pred_cls, y_true_cls), tf.float32))
    
    sess = tf.Session()
    
    sess.run(tf.global_variables_initializer())
    
    tf_saver = tf.train.Saver()
    
    train(num_iteration)    # Trains the network and saves the model
    
    sess.close()
    

    测试脚本

    sess = tf.Session()
    
    tf_saver = tf.train.import_meta_graph('model/model.meta')
    tf_saver.restore(sess, tf.train.latest_checkpoint('model'))
    
    x = tf.get_default_graph().get_tensor_by_name('x:0')
    
    y_true = tf.get_default_graph().get_tensor_by_name('y_true:0')
    y_true_cls = tf.argmax(y_true, axis=1)
    
    y_pred = tf.get_default_graph().get_tensor_by_name('y_pred:0')      # refers to FC2 in the model
    y_pred_cls = tf.argmax(y_pred, axis=1)
    
    correct_prediction = tf.equal(y_pred_cls, y_true_cls)
    accuracy           = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    
    images, labels = read_data()     # read data for testing
    
    feed_dict_test  = {x: images, y_true: labels}
    
    test_acc = sess.run(accuracy, feed_dict=feed_dict_test)
    
    sess.close()
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   tomkot    6 年前

    您只需在正确的张量上执行sess.run就可以得到值。首先你需要张量。您可以在build_模型中为其命名,方法是添加一个name参数(您可以对任何张量执行此操作),例如:

    FC1 = tf.add(tf.multiply(Flat, W1), b1, name="FullyConnected1")
    

    稍后,您可以获取完全连接层的张量并对其进行评估:

    with tf.Session() as sess:
        FC1 = tf.get_default_graph().get_tensor_by_name('FullyConnected1:0')
        FC1_values = sess.run(FC1, feed_dict={x: input_img_arr})        
    

    (假设图中没有其他名为fullyconnected1的层)