如何从 slim-tensorflow InceptionNet v3 模型的最后一层提取特征?

How to extract features from the last layer of slim-tensorflow InceptionNet v3 model?

我微调了 slim-tensorflow 库中给出的 InceptionNet v3 模型。我在自己的数据集上训练了模型。现在,我有模型的 .ckpt 和 .meta 文件。

现在,据我了解,我有两种方法可以恢复模型和权重。首先,从这样的 .meta 文件

checkpoint = './fine_tuned_model/model.ckpt-233700.meta'

with tf.Session() as sess:
    new_saver = tf.train.import_meta_graph(checkpoint)
    print(new_saver)
    new_saver.restore(sess, tf.train.latest_checkpoint('./fine_tuned_model/'))

第二种方法是调用模型并恢复检查点。像这样

 with slim.arg_scope(slim.nets.inception.inception_v3_arg_scope()):
        logits, inceptionv3 = nets.inception.inception_v3(inputs=img, num_classes=5980, is_training=True,
                                                          dropout_keep_prob=.6)

 # Restore convolutional layers:

 variables_to_restore = slim.get_variables_to_restore(exclude=['InceptionV3/Logits', 'InceptionV3/AuxLogits'])
 init_fn = slim.assign_from_checkpoint_fn(model_path, variables_to_restore)

现在,我认为就我的目的而言,第二种方法更容易。

现在,我的问题是,在恢复模型后,如何从最后一层提取特征给定图像?我在这里包含了模型的屏幕截图 我找到的一个解决方案是这样的,据我所知,我必须从 PreLogits 层中提取特征,但我不确定如何在此处设置值

   with tf.Session() as sess:
        feature_tensor = sess.graph.get_tensor_by_name('mul:0')
        features_last_layer = sess.run(feature_tensor,{inputs: img})
        print features_last_layer

在这里,我找不到我应该传递什么给get_tenor_by_name(??),还有,如何在这里传递sess.run?

谢谢。如果有其他方法可以恢复模型并获取功能,请告诉我。

我已经找到解决办法了。

# Placeholder for the image,
image_tensor = tf.placeholder(tf.float32, shape=(None, 128, 128, 3))

# load the model
with slim.arg_scope(slim.nets.inception.inception_v3_arg_scope()):
    logits, inceptionv3 = nets.inception.inception_v3(image_tensor,is_training=False)

# Restore convolutional layers:

variables_to_restore = slim.get_variables_to_restore(exclude=['InceptionV3/Logits', 'InceptionV3/AuxLogits'])

# get the latest checkpoint you want to use after training 
init_fn = slim.assign_from_checkpoint_fn(model_path, variables_to_restore)


checkpoint = './fine_tuned_model/model.ckpt-233700.data-00000-of-00001'

saver = tf.train.Saver(variables_to_restore)
saver.restore(sess, tf.train.latest_checkpoint('./fine_tuned_model/'))

# the required image 
img_car = cv2.imread('car.jpeg')
img_car = cv2.resize(img_car,(128, 128))
imgnumpy = np.ndarray((1,128,128,3))
imgnumpy[0] = img_car

# get output from any layer you want. 
output = sess.run(inceptionv3["PreLogits"], feed_dict={image_tensor: imgnumpy})