首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NotFoundError :在检查点文件中找不到张量名称"prediction/InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta“

NotFoundError :在检查点文件中找不到张量名称"prediction/InceptionResnetV2/AuxLogits/Conv2d_1b_1x1/BatchNorm/beta“
EN

Stack Overflow用户
提问于 2018-06-21 00:39:38
回答 1查看 437关注 0票数 1

尝试使用体系结构和检查点inception_resnet_v2_2016_08_30.ckpt运行Inceptionv2 Tensorflow模型。我的代码是预测每个分类的概率,对于给定的图像。

根据非常棒的博客here,我尝试使用类来构造tensorflow代码。但是我们有错误:

代码语言:javascript
复制
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.

我的错误代码如下。

代码语言:javascript
复制
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()

然而,如果我们不像上面那样使用类构造代码,我们就会成功地运行。下面是运行时没有错误的代码。

代码语言:javascript
复制
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}))

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2018-06-21 03:20:02

装饰器将Inception网络包装到一个以函数命名的变量作用域中,在本例中为prediction。因此,检查点中的变量名不再与图中的变量名匹配。

要验证这一点,可以在装饰器中将tf.variable_scope()更改为tf.name_scope()。在大多数用例中,这也不应该影响程序的其余部分。

如果需要变量作用域,可以向tf.train.Saver()传递一个dict,它将检查点中的变量名称映射到图形中的变量对象。

也可以通过使用tf.python.pywrap_tensorflow. NewCheckpointReader()读取检查点中的变量名来实现自动化,但是我还没有现成的代码示例可以与大家分享。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50953190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档