最近测试Alexnet模型时遇到了一个问题:训练完成后想对多个图片进行检测,但是模型在计算出第一个图片后,再计算第二个就会出错(模型训练及测试代码参见:https://github.com/stephen-v/tensorflow_alexnet_classify):

OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key conv1_1/bias not found in checkpoint

参考网上说的,增加tf.reset_default_graph()(tf.reset_default_graph函数用于清除默认图形堆栈并重置全局默认图形)但是仍会出错,最后发现是定义Alexnet网络中的with tf.name_scope(‘xxx’) as scope 导致的。将with…as…结构删除后,再加上tf.reset_default_graph(),重新训练后再批量测试图片就没有问题了。

原来的Alexnet 模型代码部分示例代码:

import tensorflow as tfdef alexnet(x, keep_prob, num_classes):# conv1with tf.name_scope('conv1') as scope:kernel = tf.Variable(tf.truncated_normal([11, 11, 3, 96], dtype=tf.float32,stddev=1e-1), name='weights')conv = tf.nn.conv2d(x, kernel, [1, 4, 4, 1], padding='SAME')biases = tf.Variable(tf.constant(0.0, shape=[96], dtype=tf.float32),trainable=True, name='biases')bias = tf.nn.bias_add(conv, biases)conv1 = tf.nn.relu(bias, name=scope)# lrn1with tf.name_scope('lrn1') as scope:lrn1 = tf.nn.local_response_normalization(conv1,alpha=1e-4,beta=0.75,depth_radius=2,bias=2.0)# pool1with tf.name_scope('pool1') as scope:pool1 = tf.nn.max_pool(lrn1, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1],padding='VALID')# 后面的省略...

修改后的代码为(把所有with tf.name_scope(‘xxx’) as scope去掉):

import tensorflow as tfdef alexnet(x, keep_prob, num_classes):# conv1kernel = tf.Variable(tf.truncated_normal([11, 11, 3, 96], dtype=tf.float32,stddev=1e-1), name='weights')conv = tf.nn.conv2d(x, kernel, [1, 4, 4, 1], padding='SAME')biases = tf.Variable(tf.constant(0.0, shape=[96], dtype=tf.float32),trainable=True, name='biases')bias = tf.nn.bias_add(conv, biases)conv1 = tf.nn.relu(bias, name = 'conv1')# lrn1# with tf.name_scope('lrn1') as scope:lrn1 = tf.nn.local_response_normalization(conv1,alpha=1e-4,beta=0.75,depth_radius=2,bias=2.0)# pool1# with tf.name_scope('pool1') as scope:pool1 = tf.nn.max_pool(lrn1, ksize=[1, 3, 3, 1],strides=[1, 2, 2, 1],padding='VALID')# 后面的省略...

批量测试代码为:

import tensorflow as tf
from alexnet import alexnet
import matplotlib.pyplot as plt
from os import walk, path
VGG_MEAN = tf.constant([123.68, 116.779, 103.939], dtype=tf.float32)class_name = ['dog', 'cat']def test_image(path_image, num_class):img_string = tf.read_file(path_image)img_decoded = tf.image.decode_png(img_string, channels=3)img_resized = tf.image.resize_images(img_decoded, [224, 224])# img_centered = tf.subtract(img_resized, VGG_MEAN)img_resized = tf.reshape(img_resized, shape=[1, 224, 224, 3])# img_bgr = img_centered[:, :, ::-1]fc8 = alexnet(img_resized, 1, num_class)score = tf.nn.softmax(fc8)max = tf.argmax(score, 1)saver = tf.train.Saver()with tf.Session() as sess:sess.run(tf.global_variables_initializer())saver.restore(sess, "./checkpoints/model_epoch80.ckpt")print(sess.run(fc8))prob = sess.run(max)[0]output = class_name[prob]plt.imshow(img_decoded.eval())plt.title("Class:" + class_name[prob])plt.show(2)def get_path_prex(rootdir):data_path = []prefixs = []for root, dirs, files in walk(rootdir, topdown=True):for name in files:pre, ending = path.splitext(name)if ending != ".jpg" and ending != ".png":continueelse:data_path.append(path.join(root, name))prefixs.append(pre)return data_path, prefixsimg_path, prefix = get_path_prex('./Datasets/dog_cat/test/')
cnt_fire = 0
for i in range(len(img_path)):tf.reset_default_graph() #这个要加上,每次测试前要重新建立图output = test_image(img_path[i], num_class=2)

其中tf.reset_default_graph()是必须要增加的。

总结
      (1)由于训练代码中含有with tf.name_scope(‘xxx’) as scope去掉,导致直接增加tf.reset_default_graph()也仍报上述错误(参考:https://blog.csdn.net/LeeGe666/article/details/85806790)
      (2)将代码中的with tf.name_scope(‘xxx’) as scope去掉后重新训练模型,并且在测试代码中增加tf.reset_default_graph() 错误解决。

参考链接:

  • https://blog.csdn.net/bc521bc/article/details/84038471
  • tf.name_scope()”有什么用:https://www.jianshu.com/p/635d95b34e14
  • tf.reset_default_graph()函数:https://blog.csdn.net/duanlianvip/article/details/98626111

批量图片验证模型错误: OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key conv1_1/bias not found相关推荐

  1. 【tensorflow】OP_REQUIRES failed at variable_ops.cc:104 Already exists: Resource

    如下代码片段 outputs = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(units=half_depth, use_bias=False, ...

  2. OP_REQUIRES failed at conv_ops.cc:386 : Resource exhausted: OOM when allocating tensor with shape..

    tensorflow-gpu验证准确率是报错如上: 解决办法: 1. 加入os.environ['CUDA_VISIBLE_DEVICES']='2' 强制使用CPU验证-----慢 2.'batch ...

  3. python 验证模型_Python中的模型验证

    python 验证模型 This is a memo to share what I have learnt in Model Validation (using Python), capturing ...

  4. 快速实践大规模轻量级图片分类模型:飞桨识图 PP-ShiTu

    快速实践大规模图片分类模型:飞桨识图 PP-ShiTu 飞桨识图PP-ShiTu是轻量级图像识别系统,集成了目标检测.特征学习.图像检索等模块,广泛适用于各类图像识别任务.CPU上0.2s即可完成在1 ...

  5. windows错误:Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work.

    windows错误:Failed to import pydot. You must install pydot and graphviz for `pydotprint` to work. 文章目录 ...

  6. 不需要任何依赖的图片加载错误处理的工具类load-image.js

    需求的诞生: 先简单介绍一下业务场景,我们的项目是一个微博舆情分析系统,可以根据用户设置的关键字监测相关微博舆情,并进行实时推送.监测范围涵盖境内和境外微博平台(境内:新浪.腾讯,境外:twitter ...

  7. 乱序图片 极验_极验验证吴渊:传统图片验证方式已经无效了!

    吴渊,极意网络CEO 黑五月频发的宕机门告诉我们:数据安全,所有创业者都应该关注! 让我们来听听IDG资本的两位投资人大佬的深刻分析,以及5家创业公司CEO/CTO大拿的深切呼吁吧!--这里不止有干货 ...

  8. laravel中图片验证码以及错误处理

    有基础的大牛可以去官网查看具体步骤 1.安装验证码扩展包 composer require mews/captcha 2.自动生成配置文件 php artisan vendor:publish 仔细选 ...

  9. vue中纯前端实现滑动图片验证的方式

    Hello,大家好呀~ 众所周知,滑动图片验证一直是各类网站登录和注册的一种校验方式,是用来防止有人恶意使用脚本批量进行操作从而设置的一种安全保护方式. 一般而言,这种滑动图片验证是可以通过后端配合完 ...

  10. SSM框架下实现验证码图片验证功能(源码)

    SSM框架下实现验证码图片验证功能 背景图片资源路径 https://download.csdn.net/download/hero_qhz/10322064 一.首先,在pom里面加上需要用的资源j ...

最新文章

  1. 魔性“合成大西瓜”背后,我用 350 行代码解开了碰撞之谜!
  2. 【设计模式】代理模式 ( 动态代理 | 模拟 Java 虚拟机生成对应的 代理对象 类 )
  3. [BZOJ 1124][POI 2008] 枪战 Maf
  4. Opencv学习笔记之OpenCV介绍
  5. HALCON示例程序color_fuses_lut_trans.hdev通过颜色对保险丝进行分类
  6. 基于 Blazui 的 Blazor 后台管理模板 BlazAdmin 正式尝鲜
  7. camunda流程定义表无数据_[Python04] 学习snakemake,三步轻松搭建生信流程!
  8. java接收二进制数据_java-从套接字读取二进制数据
  9. 这样做,免费从Oracle同步数据
  10. 【英语学习】【Level 07】U06 First Time L2 A good food experience
  11. 跟KingDZ学HTML5之八 HTML5之Web Save
  12. mysqli_connect参数的写法以及如何设置特定端口
  13. C#笔记20:多线程之线程同步中的信号量AutoResetEvent和ManualResetEvent
  14. linux驱动怎么判断定时器正在运行,Linux设备驱动编程之定时器
  15. 笔记总结-相机标定(Camera calibration)原理、步骤
  16. 2008 r2 server sql 中文版补丁_sql server 2008 r2 64位补丁包-sql server 2008 r2 64位sp3补丁 简体中文版 - 河东下载站...
  17. glassfish插件_安装和使用Glassfish
  18. CSS设置字间距、行间距、首行缩进
  19. adb 出现多个设备情况操作解决
  20. 三维管廊大规模实时渲染方案

热门文章

  1. java isprime函数_Java8函数式编程入门
  2. 项目范围管理(重点)-真题答案与解析
  3. 数字孪生 工业互联网 IIoT 解决方案
  4. 完全理解android事件分发机制
  5. 手机电脑浏览器抓取京东Cookies教程
  6. ec12编码器电路图_光电编码器的电路原理图详解
  7. 手摸手教你搭个脚手架
  8. 物联网技术,主要应用在哪些领域?
  9. 把mysql一个表的部分或全部数据复制追加到另一个表的方法
  10. Python3.9安装Cartopy使用报错:DLL load failed while importing trace