NotFoundError: Тензорное имя «Предсказание / InceptionResnetV2 / AuxLogits / Conv2d_1b_1x1 / BatchNorm / beta» не найдено в файлах контрольных точек

1

Попытка запустить модель Inceptionv2 Tensorflow с архитектурой и контрольной точкой inception_resnet_v2_2016_08_30.ckpt. И мой код предназначен для прогнозирования вероятности каждой классификации для данного изображения.

Я пытаюсь сконструировать код tensorflow, используя класс в соответствии с удивительным блогом здесь. Но у нас была ошибка:

NotFoundError (see above for traceback): Tensor name "prediction/InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta"not found in checkpoint files inception_resnet_v2_2016_08_30.ckpt.

Мой код ошибки выглядит следующим образом.

from inception_resnet_v2 import *
import functools
import inception_preprocessing
import matplotlib.pyplot as plt
import os
import numpy as np
import tensorflow as tf
from scipy.misc import imread

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


def doublewrap(function):
    """
    A decorator decorator, allowing to use the decorator to be used without
    parentheses if no arguments are provided. All arguments must be optional.
    """

    @functools.wraps(function)
    def decorator(*args, **kwargs):
        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
            return function(args[0])
        else:
            return lambda wrapee: function(wrapee, args, *kwargs)

    return decorator


@doublewrap
def define_scope(function, scope=None, args, *kwargs):
    """
    A decorator for functions that define TensorFlow operations. The wrapped
    function will only be executed once. Subsequent calls to it will directly
    return the result so that operations are added to the graph only once.
    The operations added by the function live within a tf.variable_scope(). If
    this decorator is used with arguments, they will be forwarded to the
    variable scope. The scope name defaults to the name of the wrapped
    function.
    """
    attribute = '_cache_' + function.__name__
    name = scope or function.__name__

    @property
    @functools.wraps(function)
    def decorator(self):
        if not hasattr(self, attribute):
            with tf.variable_scope(name, args, *kwargs):
                setattr(self, attribute, function(self))
        return getattr(self, attribute)

    return decorator


class Inception(object):

    def __init__(self,
                 image):  
        self.image = image
        self.process_data   # call function process_data
        self.prediction     

    @define_scope
    def process_data(self):
        image_size = inception_resnet_v2.default_image_size
        image = inception_preprocessing.preprocess_image(self.image, image_size, image_size, is_training=False, )
        image1 = tf.expand_dims(image, 0)
        return image1

    @define_scope
    def prediction(self):
        '''Creates the Inception Resnet V2 model.'''
        arg_scope = inception_resnet_v2_arg_scope()
        with tf.contrib.slim.arg_scope(arg_scope):
            logits, end_points = inception_resnet_v2(self.process_data, is_training=False)
        probabilities = tf.nn.softmax(logits)
        return probabilities


def main():
    tf.reset_default_graph()

    image = tf.placeholder(tf.float32, [None, None, 3])
    model = Inception(image)
    
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess,
                      'inception_resnet_v2_2016_08_30.ckpt')
      

        probabilities = sess.run(model.prediction, feed_dict={image: data})
        print(probabilities)


if _name_ == '__main__':
    data = imread('ILSVRC2012_test_00000003 .JPEG', mode='RGB').astype(np.float)
    main()

Однако, если мы не создадим код с использованием класса, как указано выше, и мы просто запускаем его успешно. Ниже приведен код без ошибок.

from inception_resnet_v2 import *
import inception_preprocessing
import os
import numpy as np
import tensorflow as tf
from scipy.misc import imread
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

slim = tf.contrib.slim

tf.reset_default_graph()

# prepare data 
data = imread('ILSVRC2012_test_00000003.JPEG', mode='RGB').astype(np.float)

image = tf.placeholder(tf.float32, [None, None, 3])

# pre-processing image
image_size = inception_resnet_v2.default_image_size  
processed_image = inception_preprocessing.preprocess_image(image, image_size, image_size, is_training=False,)
processed_image = tf.expand_dims(processed_image, 0)

# Creates the Inception Resnet V2 model.
arg_scope = inception_resnet_v2_arg_scope()
with slim.arg_scope(arg_scope):
  logits, end_points = inception_resnet_v2(processed_image, is_training=False)
probabilities = tf.nn.softmax(logits)

saver = tf.train.Saver()
with tf.Session() as sess:
    saver.restore(sess, './inception_resnet_v2_2016_08_30.ckpt')
    print(sess.run(probabilities, feed_dict={image:data}))

Любая помощь будет оценена!

Теги:
tensorflow

1 ответ

0

Декоратор обертывает начальную сеть в область переменной, названную после функции, в этом случае prediction. В результате имена переменных в контрольной точке больше не совпадают с именами переменных на графике.

Чтобы проверить это, вы можете изменить tf.variable_scope() на tf.name_scope() в декораторе. В большинстве случаев использования это также не должно влиять на остальную часть вашей программы.

Если вам нужна область переменных, вы можете передать dict в tf.train.Saver() который сопоставляет имена переменных в контрольной точке переменным объектам на графике.

Также можно автоматизировать это, читая имена переменных в контрольной точке, используя tf.python.pywrap_tensorflow. NewCheckpointReader() tf.python.pywrap_tensorflow. NewCheckpointReader() но у меня нет примера кода, готового поделиться этим.

  • 0
    Я изменил `tf.variable_scope ()` на `tf.name_scope ()`, и это работает. Большое спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню