2017-04-25 80 views
1

我想创建一个使用Slim文档中提供的预训练的ResNet V2模型的图像分类器。使用预训练的ResNet V2模型创建Slim分类器

这是迄今为止代码:

import tensorflow as tf 
slim = tf.contrib.slim 
from PIL import Image 
from inception_resnet_v2 import * 
import numpy as np 

checkpoint_file = 'inception_resnet_v2_2016_08_30.ckpt' 
sample_images = ['carrot.jpg'] 

input_tensor = tf.placeholder(tf.float32, shape=(None,299,299,3), name='input_image') 
scaled_input_tensor = tf.scalar_mul((1.0/255), input_tensor) 
scaled_input_tensor = tf.subtract(scaled_input_tensor, 0.5) 
scaled_input_tensor = tf.multiply(scaled_input_tensor, 2.0) 


variables_to_restore = slim.get_model_variables() 
print(variables_to_restore) 

init_fn = slim.assign_from_checkpoint_fn(
     checkpoint_file, 
     slim.get_model_variables('InceptionResnetV2')) 

sess = tf.Session() 
init_fn(sess) 
arg_scope = inception_resnet_v2_arg_scope() 
with slim.arg_scope(arg_scope): 
    logits, end_points = inception_resnet_v2(scaled_input_tensor, is_training=False) 

for image in sample_images: 
    im = Image.open(image).resize((299,299)) 
    im = np.array(im) 
    im = im.reshape(-1,299,299,3) 
    predict_values, logit_values = sess.run([end_points['Predictions'], logits], feed_dict={input_tensor: im}) 
    print (np.max(predict_values), np.max(logit_values)) 
    print (np.argmax(predict_values), np.argmax(logit_values)) 

的问题是我不断收到此错误:

Traceback (most recent call last): 
    File "./classify.py", line 21, in <module> 
    slim.get_model_variables('InceptionResnetV2')) 
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/contrib/framework/python/ops/variables.py", line 584, in assign_from_checkpoint_fn 
    saver = tf_saver.Saver(var_list, reshape=reshape_variables) 
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1040, in __init__ 
    self.build() 
    File "/home/ubuntu/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1061, in build 
    raise ValueError("No variables to save") 
ValueError: No variables to save 

如此看来TF /斯利姆是无法找到任何变量,这是由当我打电话时清楚:

variables_to_restore = slim.get_model_variables() 
    print(variables_to_restore) 

因为它输出一个空数组。

我该如何去使用预先训练好的模型?

回答

0

发生这种情况是因为您尚未在图形中构建模型,但尚未创建任何以“InceptionResnetV2”名称开头并由保存程序捕获和恢复的变量。

我相信你应该在使用slim.get_variables_to_restore()之前进行模型制作。

例如:

with slim.arg_scope(arg_scope): 
    logits, end_points = inception_resnet_v2(scaled_input_tensor, is_training=False) 

variables_to_restore = slim.get_model_variables() 

这样,张量变量将被构建,你应该看到variables_to_restore不再是空的。

0

您需要手动添加模型变量。

试试这个

with slim.arg_scope(arg_scope): 
    logits, end_points = inception_resnet_v2(scaled_input_tensor, is_training=False) 

# Add model variables 
for var in tf.global_variables(scope='inception_resnet_v2'): 
    slim.add_model_variable(var)