当前位置: 首页 > 知识库问答 >
问题:

如何重用slim。tensorFlow中的arg_范围?

谭学名
2023-03-14

我正在尝试加载inception\u resnet\u v2\u 2016\u 08\u 30。ckpt归档并进行测试。

代码适用于单个图像(仅输入一次oneFile()函数)。

如果调用oneFile()函数两次,则会出现以下错误:

ValueError:变量接收Resnetv2/Conv2d_1a_3x3/权重已存在,不允许。您的意思是在VarScope中设置reuse=True吗?最初定义为:

我找到了共享变量的相关解决方案

如果tf。变量范围遇到同样的问题,可以调用范围。重用变量()以解决此问题。

但是我找不到超薄的。arg_scopeversion以重用该作用域。

def oneFile(filepath):
imgPath = filepath
testImage_string = tf.gfile.FastGFile(imgPath, 'rb').read()
testImage = tf.image.decode_jpeg(testImage_string, channels=3)
processed_image = inception_preprocessing.preprocess_image(testImage, image_size, image_size, is_training=False)
processed_images = tf.expand_dims(processed_image, 0)


# Create the model, use the default arg scope to configure the batch norm parameters.
with slim.arg_scope(inception_resnet_v2_arg_scope()):
    #logits, end_points = inception_resnet_v2(images, num_classes = dataset.num_classes, is_training = False)
    logits, _ = inception_resnet_v2(processed_images, num_classes=16, is_training=False)

probabilities = tf.nn.softmax(logits)

init_fn = slim.assign_from_checkpoint_fn(
    checkpoint_file,
    slim.get_model_variables(model_name))


with tf.Session() as sess:
    init_fn(sess)

    np_image, probabilities = sess.run([processed_images, probabilities])
    probabilities = probabilities[0, 0:]
    sorted_inds = [i[0] for i in sorted(enumerate(-probabilities), key=lambda x: x[1])]
    #print(probabilities)
    print(probabilities.argmax(axis=0))
    #names = imagenet.create_readable_names_for_imagenet_labels()
    #for i in range(15):
    #    index = sorted_inds[i]
    #    print((probabilities[index], names[index]))

def main():
for image_file in os.listdir(dataset_dir):
    try:
        image_type = imghdr.what(os.path.join(dataset_dir, image_file))
        if not image_type:
            continue
    except IsADirectoryError:
        continue

    #image = Image.open(os.path.join(dataset_dir, image_file))
    filepath = os.path.join(dataset_dir, image_file)

    oneFile(filepath)

inception_resnet_v2_arg_scope

def inception_resnet_v2_arg_scope(weight_decay=0.00004,
                                  batch_norm_decay=0.9997,
                                  batch_norm_epsilon=0.001):
  """Yields the scope with the default parameters for inception_resnet_v2.

  Args:
    weight_decay: the weight decay for weights variables.
    batch_norm_decay: decay for the moving average of batch_norm momentums.
    batch_norm_epsilon: small float added to variance to avoid dividing by zero.

  Returns:
    a arg_scope with the parameters needed for inception_resnet_v2.
  """
  # Set weight_decay for weights in conv2d and fully_connected layers.
  with slim.arg_scope([slim.conv2d, slim.fully_connected],
                      weights_regularizer=slim.l2_regularizer(weight_decay),
                      biases_regularizer=slim.l2_regularizer(weight_decay)):

    batch_norm_params = {
        'decay': batch_norm_decay,
        'epsilon': batch_norm_epsilon,
    }
    # Set activation_fn and parameters for batch_norm.
    with slim.arg_scope([slim.conv2d], activation_fn=tf.nn.relu,
                        normalizer_fn=slim.batch_norm,
                        normalizer_params=batch_norm_params) as scope:

      return scope

完整错误消息:

./data/test/齿/1/7070.jpgTraceback(最近一次调用最后一次):File"testing.py",第111行,在main()File"testing.py"中,第106行,在main cal(processed_images)File"testing.py",第67行,在cal logits中,_=inception_resnet_v2(processed_images,num_classes=16,is_training=False)文件"/笔记本/transfer_learning_tutorial/inception_resnet_v2.py",第123行,inception_resnet_v2范围='Conv2d_1a_3x3')文件"/usr/本地/lib/python3.5/dist-包/tenorflow/contrib/框架/python/ops/arg_scope.py",第181行,在func_with_args返回func(*args,**current_args)File"/usr/本地/lib/python3.5/dist-包/tenstorflow/contrib/层/python/层/layers.py",第918行,在卷积输出=layer.apply(输入)File"/usr/local/lib/python3.5/dist-包/tensorflow/python/层/base.py",第320行,在应用返回self.call(输入,**kwargs)文件"/usr/local/lib/python3.5/dist-包/tensorflow/python/层/base.py",第286行,在调用self.build(input_shapes[0])File"/usr/local/lib/python3.5/dist-pack/tensorflow/python/层/convolutional.py",第138行,在构建dtype=self.dtype)File"/usr/local/lib/python3.5/dist-pack/tensorflow/python/ops/variable_scope.py",第1049行,get_variableuse_resource=use_resource,custom_getter=custom_getter)File"/usr/local/lib/python3.5/dist-包/tenorflow/python/ops/variable_scope.py",第948行,get_variableuse_resource=use_resource,custom_getter=custom_getter)File"/usr/local/lib/python3.5/dist-包/tenorflow/python/ops/variable_scope.py",第349行,get_variablevalidate_shape=validate_shape,use_resource=use_resource)File"/usr/local/lib/python3.5/dist-包/tensorflow/python/ops/variable_scope.py",第1389行,wrapped_custom_getter*args,**kwargs)File"/usr/local/lib/python3.5/dist-包/tensorflow/python/layers/base.py",第275行,在variable_gettervariable_getter=functools.partial(getter,**kwargs))文件/usr/本地/lib/python3.5/dist-包/tenstorflow/python/层/base. py,第228行,在_add_variable可训练=可训练和自训练)文件/usr/本地/lib/python3.5/dist-packages/tensorflow/contrib/layers/python/layers/layers.py",行1334,在layer_variable_getter返回_model_variable_getter(getter,*args,**kwargs)文件"/usr/本地/lib/python3.5/dist-包/Tenorflow/contrib/层/python/层/layers. py",行1326,在_model_variable_gettercustom_getter=getter,use_resource=use_resource)文件"/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py",第181行,在func_with_args返回func(*args,**current_args)File"/usr/loce/lib/python3.5/dist-包/Tenorflow/contrib/框架/python/ops/变量. py",第262行,在model_variableuse_resource=use_resource)File"/usr/loce/lib/python3.5/dist-packages/tensorflow/contrib/framework/python/ops/arg_scope.py",第181行,在func_with_args返回func(*args,**current_args)File"/usr/place/lib/python3.5/dist-包/Tenorflow/contrib/框架/python/ops/变量. py",第217行,变量use_resource=use_resource)File"/usr/loc/lib/python3.5/dist-包/Tenorflow/python/ops/variable_scope. py",第341行,在_true_getteruse_resource=use_resource)File"/usr/loce/lib/python3.5/dist-包/tenorflow/python/ops/variable_scope. py",第653行,在_get_single_variable名称中,""。加入(回溯。format_list(tb))))值错误:变量InceptionResnetV2/Conv2d_1a_3x3/权重已经存在,不允许。您的意思是在VarScope中设置reuse=True吗?最初定义为:

文件“/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/framework/python/ops/variables.py”,变量use\u-resource=use\u-resource)文件“/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/framework/python/ops/arg\u-scope.py”中的第217行,带有参数的函数返回函数(*args,**当前参数)文件第181行“/usr/local/lib/python3。5/dist包/tensorflow/contrib/framework/python/ops/variables。py“,第262行,在模型_变量use_resource=use_resource中)

共有2个答案

林龙野
2023-03-14

我猜您在图中为多个变量指定了相同的范围。当tensorflow在同一范围内发现多个变量(与下一个映像或下一批无关)时,就会发生此错误。创建图形时,应仅考虑一个图像或批次。如果第一批或第一幅图像一切正常,tensorflow将负责下一次迭代,包括范围界定。

因此,请检查模型文件中的所有作用域。我敢肯定你用过两次同一个名字。

濮阳弘扬
2023-03-14

好像是tf。在处理oneFile()函数中的每个图像之前重置\u default\u graph()将解决此问题,因为我在一个非常类似的示例代码中遇到了相同的问题。我的理解是,一旦你将图像输入到神经网络(NN),由于TensorFlow使用的可变范围概念,在你将NN应用到另一个图像之前,需要被告知变量可以重用。

 类似资料:
  • 我有一个问题,在子域上使用路由器超薄。路由器本身工作,我可以调用它,它不会导致任何错误,但斯利姆只是读取"/"路由。 文件夹 www --- .htacccess ---index.php ---其他东西 ---子域 --- --- .htaccess --- --- index.php --- --- 其他东西 www/。htaccess: 重写引擎在 重写条件%{REQUEST_FILENAM

  • 对于初始模型,我主要遵循这一点。比方说,我想在每个训练循环上打印批次中使用的图像数据,即我想在“微调不同标签集上的模型”中打印每个训练迭代的“images”变量值代码,既然会话实际上是在slim中创建的,我该如何做呢。训练训练功能,因此我无法进行sess。在没有SES的情况下运行([图像])?

  • 问题内容: 我想要一段代码,如果它不存在,则在范围内创建一个变量,如果它已经存在,则访问该变量。我需要它是 相同的 代码,因为它将被多次调用。 但是,Tensorflow需要我指定是要创建还是重用该变量,如下所示: 我怎样才能弄清楚是自动创建还是重用它?即,我希望以上两个代码块 相同, 并运行程序。 问题答案: 创建新变量且未声明形状时,或在变量创建过程中违反重用时,将引发A。因此,您可以尝试以下

  • 在TensorFlow中执行批量规格化的正确方法是什么?(即,我不想计算连续均值和方差)。我当前的实现基于tf。nn。batch\u normalization(批次规格化),其中x是具有形状的卷积层的输出。[批次大小、宽度、高度、通道数]。我想在通道方面执行批处理规范。 但这种实施的结果非常糟糕。与tensorflow比较。承包商。苗条的batch\u norm显示其票价较低(同样糟糕的培训表现

  • 下面的Docker图像有什么不同? null 哪个尺寸更小,可以在Spring Boot项目中使用?

  • 问题内容: Python中确定两个范围中的哪些值重叠的最佳方法是什么? 例如: 给定一个范围x,迭代另一个范围y并输出两个范围共享的所有值的最佳方法是什么?先谢谢您的帮助。 编辑: 作为后续,我意识到我还需要知道x是否与y重叠。我正在寻找一种方法来遍历范围列表,并做一些范围重叠的其他事情。是否有简单的True / False语句来完成此操作? 问题答案: 尝试设置交集: 请注意,接受任何可迭代的参