2016-10-06 5 views
1

나는 내가 다음으로 graph.pb 파일로 변환되는 훈련 후이 밖으로 내 graph.pbtxt 파일을 가지고 https://github.com/tensorflow/models/tree/master/slimTensorflow Inception_Resnet_V2 분류 이미지

에서 README 다음 꽃의 이미지에 대한 inception_resnet_v2 모델을 훈련 코드 : 여기

import tensorflow as tf 
from google.protobuf import text_format 

def convert_pbtxt_to_graphdef(filename): 
    """Returns a `tf.GraphDef` proto representing the data in the given pbtxt file. 

    Args: 
    filename: The name of a file containing a GraphDef pbtxt (text-formatted 
     `tf.GraphDef` protocol buffer data). 

    Returns: 
    A `tf.GraphDef` protocol buffer. 
    """ 
    with tf.gfile.FastGFile(filename, 'r') as f: 
    graph_def = tf.GraphDef() 

    file_content = f.read() 

    # Merges the human-readable string in `file_content` into `graph_def`. 
    text_format.Merge(file_content, graph_def) 
    return graph_def 

with tf.gfile.FastGFile('/foo/bar/workspace/results/graph.pb', 'wb') as f: 
    f.write(convert_pbtxt_to_graphdef('/foo/bar/workspace/results/graph.pbtxt')) 

tensorflow의 classify_image.py를 사용하여 나는 훈련 모델을 임의의 이미지를 먹이려고이 파일을받은 후 :

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/imagenet/classify_image.py
,532 10 내 .pb 또, .pbtxt를 사용하여, 내 레이블 파일, 그러나, 나는 다음과 같은 오류 얻을 : 슬림과

Traceback (most recent call last): 
    File "classify_image.py", line 212, in <module> 
    tf.app.run() 
    File "/usr/local/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 30, in run 
    sys.exit(main(sys.argv[:1] + flags_passthrough)) 
    File "classify_image.py", line 208, in main 
    run_inference_on_image(image) 
    File "classify_image.py", line 170, in run_inference_on_image 
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') 
    File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2615, in get_tensor_by_name 
    return self.as_graph_element(name, allow_tensor=True, allow_operation=False) 
    File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2466, in as_graph_element 
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation) 
    File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2508, in _as_graph_element_locked 
    "graph." % (repr(name), repr(op_name))) 
KeyError: "The name 'softmax:0' refers to a Tensor which does not exist. The operation, 'softmax', does not exist in the graph." 

답변

5

문제, 사실 tensorflow/모델은 그 프레임 워크와 이렇게 생산 된 모델 을 정말 예측 사용 사례에 맞지 않는 :

TF-slim is a new lightweight high-level API of TensorFlow (tensorflow.contrib.slim) for defining, training and evaluating complex models. (Source https://github.com/tensorflow/models/tree/master/slim)

예측시 가장 큰 문제는 그것은 단지 보호기 클래스에 의해 생성 된 검사 점 파일로 잘 작동한다. 검사 점 파일을 사용할 때 assign_from_checkpoint_fn() 메서드를 사용하여 검사 점에 포함 된 훈련 된 매개 변수로 모든 변수를 초기화 할 수 있습니다. 반면에 GraphDef 파일 * .pb 만있는 상황에서는 다소 손실됩니다. 그래도 멋진 트릭이 있습니다.

중요한 아이디어는 훈련 된 모델을 검사 점으로 저장 한 후에 입력 이미지에 대한 tf.placeholder 변수를 계산 그래프에 삽입하는 것입니다. 다음 스크립트 (convert_checkpoint_to_pb.py)는 검사 점을 읽고, 자리 표시자를 삽입하고, 그래프 변수를 상수로 변환하고 * .pb 파일로 덤프합니다.

import tensorflow as tf 
from tensorflow.contrib import slim 

from nets import inception 
from tensorflow.python.framework.graph_util import convert_variables_to_constants 
from tensorflow.python.tools.optimize_for_inference_lib import optimize_for_inference 
from preprocessing import inception_preprocessing 

checkpoints_dir = '/path/to/your/checkpoint_dir/' 
OUTPUT_PB_FILENAME = 'minimal_graph.proto' 
NUM_CLASSES = 2 

# We need default size of image for a particular network. 
# The network was trained on images of that size -- so we 
# resize input image later in the code. 
image_size = inception.inception_resnet_v2.default_image_size 

with tf.Graph().as_default(): 
    # Inject placeholder into the graph 
    input_image_t = tf.placeholder(tf.string, name='input_image') 
    image = tf.image.decode_jpeg(input_image_t, channels=3) 

    # Resize the input image, preserving the aspect ratio 
    # and make a central crop of the resulted image. 
    # The crop will be of the size of the default image size of 
    # the network. 
    # I use the "preprocess_for_eval()" method instead of "inception_preprocessing()" 
    # because the latter crops all images to the center by 85% at 
    # prediction time (training=False). 
    processed_image = inception_preprocessing.preprocess_for_eval(image, 
                    image_size, 
                    image_size, central_fraction=None) 

    # Networks accept images in batches. 
    # The first dimension usually represents the batch size. 
    # In our case the batch size is one. 
    processed_images = tf.expand_dims(processed_image, 0) 

    # Load the inception network structure 
    with slim.arg_scope(inception.inception_resnet_v2_arg_scope()): 
     logits, _ = inception.inception_resnet_v2(processed_images, 
                num_classes=NUM_CLASSES, 
                is_training=False) 
    # Apply softmax function to the logits (output of the last layer of the network) 
    probabilities = tf.nn.softmax(logits) 

    model_path = tf.train.latest_checkpoint(checkpoints_dir) 

    # Get the function that initializes the network structure (its variables) with 
    # the trained values contained in the checkpoint 
    init_fn = slim.assign_from_checkpoint_fn(
     model_path, 
     slim.get_model_variables()) 

    with tf.Session() as sess: 
     # Now call the initialization function within the session 
     init_fn(sess) 

     # Convert variables to constants and make sure the placeholder input_image is included 
     # in the graph as well as the other neccesary tensors. 
     constant_graph = convert_variables_to_constants(sess, sess.graph_def, ["input_image", "DecodeJpeg", 
                       "InceptionResnetV2/Logits/Predictions"]) 

     # Define the input and output layer properly 
     optimized_constant_graph = optimize_for_inference(constant_graph, ["eval_image"], 
                  ["InceptionResnetV2/Logits/Predictions"], 
                  tf.string.as_datatype_enum) 
     # Write the production ready graph to file. 
     tf.train.write_graph(optimized_constant_graph, '.', OUTPUT_PB_FILENAME, as_text=False) 

코드를 사용

(A *의 .pb 또 파일로 지금 현재) 변환 된 모델에 새로운 이미지를 예측하기 (모델/슬림 코드는이 코드를 실행하기 위해 파이썬 경로에 있어야합니다)

import tensorflow as tf 
import urllib2 


def create_graph(model_file): 
    """Creates a graph from saved GraphDef file and returns a saver.""" 
    # Creates graph from saved graph_def.pb. 
    with tf.gfile.FastGFile(model_file, 'rb') as f: 
     graph_def = tf.GraphDef() 
     graph_def.ParseFromString(f.read()) 
     _ = tf.import_graph_def(graph_def, name='') 


model_file = "/your/path/to/minimal_graph.proto" 

url = ("http://pictureparadise.net/funny-babies/funny-babies02/funny-babies-053.jpg") 

# Open specified url and load image as a string 
image_string = urllib2.urlopen(url).read() 

with tf.Graph().as_default(): 
    with tf.Session() as new_sess: 
     create_graph(model_file) 

     softmax = new_sess.graph.get_tensor_by_name("InceptionResnetV2/Logits/Predictions:0") 

     # Loading the injected placeholder 
     input_placeholder = new_sess.graph.get_tensor_by_name("input_image:0") 

     probabilities = new_sess.run(softmax, {input_placeholder: image_string}) 
     print probabilities 

단순히 파이썬

,691에게 실행이 스크립트를 사용하려면 : 파일 minimal_predict.py에서
python convert_checkpoint_to_pb.py 
python minimal_predicty.py 

귀하의 PYTHONPATH에 tensorflow 및 tensorflow/models/slim이있는 동안.

+0

TF r0.11을 재결 중이고 convert_checkpoint_to_pb.py를 실행할 때이 오류가 발생합니다. "ImportError : 모듈 이름이 tools.optimize_for_inference_lib"입니다. –

+0

TF r0.11에서도 작동하지 않습니다. 함수는 있지만 모듈로는 액세스 할 수 없습니다. 최신 버전 (TF r0.12, TF r1.0)으로 업그레이드하면 작동합니다. r0.11에 붙어있는 경우 Python에서 [this] (https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/python/tools/optimize_for_inference_lib.py) 함수를 사용할 수 있도록 고려하십시오. 통로. – Maximilian