tensorflow训练自己的数据集实现CNN图像分类2(保存模型&测试单张图片)
神经网络训练的时候,我们需要将模型保存下来,方便后面继续训练或者用训练好的模型进行测试。因此,我们需要创建一个saver保存模型。
def run_training():
data_dir = 'C:/Users/wk/Desktop/bky/dataSet/'
log_dir = 'C:/Users/wk/Desktop/bky/log/'
image,label = inputData.get_files(data_dir)
image_batches,label_batches = inputData.get_batches(image,label,32,32,16,20)
print(image_batches.shape)
p = model.mmodel(image_batches,16)
cost = model.loss(p,label_batches)
train_op = model.training(cost,0.001)
acc = model.get_accuracy(p,label_batches) sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
saver = tf.train.Saver()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess = sess,coord = coord) try:
for step in np.arange(1000):
print(step)
if coord.should_stop():
break
_,train_acc,train_loss = sess.run([train_op,acc,cost])
print("loss:{} accuracy:{}".format(train_loss,train_acc))
if step % 100 == 0:
check = os.path.join(log_dir,"model.ckpt")
saver.save(sess,check,global_step = step)
except tf.errors.OutOfRangeError:
print("Done!!!")
finally:
coord.request_stop()
coord.join(threads)
sess.close()
训练好的模型信息会记录在checkpoint文件中,大致如下:
model_checkpoint_path: "C:/Users/wk/Desktop/bky/log/model.ckpt-100"
all_model_checkpoint_paths: "C:/Users/wk/Desktop/bky/log/model.ckpt-0"
all_model_checkpoint_paths: "C:/Users/wk/Desktop/bky/log/model.ckpt-100"
其余还会生成一些文件,分别记录了模型参数等信息,后边测试的时候程序会读取checkpoint文件去加载这些真正的数据文件
构建好神经网络进行训练完成后,如果用之前的代码直接进行测试,会报shape不符合的错误,大致是卷积层的输入与图像的shape不一致,这是因为上篇的代码,将weights和biases定义在了模型的外面,调用模型的时候,出现valueError的错误。
因此,我们需要将参数定义在模型里面,加载训练好的模型参数时,训练好的参数才能够真正初始化模型。重写模型函数如下
def mmodel(images,batch_size):
with tf.variable_scope('conv1') as scope:
weights = tf.get_variable('weights',
shape = [3,3,3, 16],
dtype = tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[16],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
conv = tf.nn.conv2d(images, weights, strides=[1,1,1,1], padding='SAME')
pre_activation = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(pre_activation, name= scope.name)
with tf.variable_scope('pooling1_lrn') as scope:
pool1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1],strides=[1,2,2,1],
padding='SAME', name='pooling1')
norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001/9.0,
beta=0.75,name='norm1')
with tf.variable_scope('conv2') as scope:
weights = tf.get_variable('weights',
shape=[3,3,16,128],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.1,dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[128],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
conv = tf.nn.conv2d(norm1, weights, strides=[1,1,1,1],padding='SAME')
pre_activation = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(pre_activation, name='conv2')
with tf.variable_scope('pooling2_lrn') as scope:
norm2 = tf.nn.lrn(conv2, depth_radius=4, bias=1.0, alpha=0.001/9.0,
beta=0.75,name='norm2')
pool2 = tf.nn.max_pool(norm2, ksize=[1,2,2,1], strides=[1,1,1,1],
padding='SAME',name='pooling2')
with tf.variable_scope('local3') as scope:
reshape = tf.reshape(pool2, shape=[batch_size, -1])
dim = reshape.get_shape()[1].value
weights = tf.get_variable('weights',
shape=[dim,4096],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[4096],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)
with tf.variable_scope('softmax_linear') as scope:
weights = tf.get_variable('softmax_linear',
shape=[4096, 2],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.005,dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[2],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
softmax_linear = tf.add(tf.matmul(local3, weights), biases, name='softmax_linear')
return softmax_linear
测试训练好的模型
首先获取一张测试图像
def get_one_image(img_dir):
image = Image.open(img_dir)
plt.imshow(image)
image = image.resize([32, 32])
image_arr = np.array(image)
return image_arr
加载模型,计算测试结果
def test(test_file):
log_dir = 'C:/Users/wk/Desktop/bky/log/'
image_arr = get_one_image(test_file) with tf.Graph().as_default():
image = tf.cast(image_arr, tf.float32)
image = tf.image.per_image_standardization(image)
image = tf.reshape(image, [1,32, 32, 3])
print(image.shape)
p = model.mmodel(image,1)
logits = tf.nn.softmax(p)
x = tf.placeholder(tf.float32,shape = [32,32,3])
saver = tf.train.Saver()
with tf.Session() as sess:
ckpt = tf.train.get_checkpoint_state(log_dir)
if ckpt and ckpt.model_checkpoint_path:
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
saver.restore(sess, ckpt.model_checkpoint_path)
print('Loading success)
else:
print('No checkpoint')
prediction = sess.run(logits, feed_dict={x: image_arr})
max_index = np.argmax(prediction)
print(max_index)
前面主要是将测试图片标准化为网络的输入图像,15-19是加载模型文件,然后将图像输入到模型里即可
tensorflow训练自己的数据集实现CNN图像分类2(保存模型&测试单张图片)的更多相关文章
- tensorflow训练自己的数据集实现CNN图像分类1
利用卷积神经网络训练图像数据分为以下几个步骤 读取图片文件 产生用于训练的批次 定义训练的模型(包括初始化参数,卷积.池化层等参数.网络) 训练 1 读取图片文件 def get_files(file ...
- 在C#下使用TensorFlow.NET训练自己的数据集
在C#下使用TensorFlow.NET训练自己的数据集 今天,我结合代码来详细介绍如何使用 SciSharp STACK 的 TensorFlow.NET 来训练CNN模型,该模型主要实现 图像的分 ...
- 【Tensorflow系列】使用Inception_resnet_v2训练自己的数据集并用Tensorboard监控
[写在前面] 用Tensorflow(TF)已实现好的卷积神经网络(CNN)模型来训练自己的数据集,验证目前较成熟模型在不同数据集上的准确度,如Inception_V3, VGG16,Inceptio ...
- TensorFlow学习笔记——LeNet-5(训练自己的数据集)
在之前的TensorFlow学习笔记——图像识别与卷积神经网络(链接:请点击我)中了解了一下经典的卷积神经网络模型LeNet模型.那其实之前学习了别人的代码实现了LeNet网络对MNIST数据集的训练 ...
- TensorFlow训练MNIST数据集(1) —— softmax 单层神经网络
1.MNIST数据集简介 首先通过下面两行代码获取到TensorFlow内置的MNIST数据集: from tensorflow.examples.tutorials.mnist import inp ...
- tensorflow中使用mnist数据集训练全连接神经网络-学习笔记
tensorflow中使用mnist数据集训练全连接神经网络 ——学习曹健老师“人工智能实践:tensorflow笔记”的学习笔记, 感谢曹老师 前期准备:mnist数据集下载,并存入data目录: ...
- 【实践】如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统)
如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统) 一.环境配置 1. Python3.7.x(注:我用的是3.7.3.安 ...
- Pytorch和CNN图像分类
Pytorch和CNN图像分类 PyTorch是一个基于Torch的Python开源机器学习库,用于自然语言处理等应用程序.它主要由Facebookd的人工智能小组开发,不仅能够 实现强大的GPU加速 ...
- tensorflow文本分类实战——卷积神经网络CNN
首先说明使用的工具和环境:python3.6.8 tensorflow1.14.0 centos7.0(最好用Ubuntu) 关于环境的搭建只做简单说明,我这边是使用pip搭建了python的 ...
随机推荐
- 当苹果因为UIDevice、udid、uniqueIdentifier而把我们的应用拒之门外invalid binary的时候,呕心沥血解决方法啊
本文转载至 http://blog.csdn.net/macmini/article/details/16341669 当我们辛辛苦苦把应用或者游戏做好的时候,满怀激动地把应用提交上去给苹果大大,谁知 ...
- 《C++ Primer Plus》学习笔记 第1章 预备知识
第一章 预备知识C++在C语言的基础上添加了对"面向对象编程"的支持和对"泛型编程"的支持.类 —— 面向对象模板 —— 泛型编程1.1 C++简介1.2 C+ ...
- fopen()函数文件模板中w,w+,a,a+的区别
"w" 写入方式打开,将文件指针指向文件头并将文件大小截为零.如果文件不存在则尝试创建之. "w+" 读写方式打开,将文件指针指向文件头并将文件大小截为零.如果 ...
- python的其他安全隐患
零.绪论 python这里以python2.7为研究对象,对应的我们会简要说明一下python3,其他指与反序列化无关的安全隐患问题. 一.标准输入输出: 1.首先,我们来看下标准输入输出 impor ...
- visual studio 常识
去掉 引用提示 文本编辑器=>所有语言=>codelens
- 【BZOJ1217】[HNOI2003]消防局的设立 树形DP
[BZOJ1217][HNOI2003]消防局的设立 Description 2020年,人类在火星上建立了一个庞大的基地群,总共有n个基地.起初为了节约材料,人类只修建了n-1条道路来连接这些基地, ...
- jquery使用replaceWith替换元素,但是替换的位置不对应的问题
$("#itemList").replaceWith(htmlContent); 注: $("#itemList")处应为tr元素,如果是span元素或者div ...
- centos免密登录
本文是为了docker-machine增加现有虚拟机服务器为节点而做 docker-machine create -d generic --generic-ip-address=192.168.102 ...
- JSTL-标准标签库
JSTL1.2中的标签库可以分成5类区域 核心:uri="http://java.sun.com/jsp/jstl/core" prefix=“c” XML: ...
- Code Forces 21 A(模拟)
A. Jabber ID time limit per test 0.5 second memory limit per test 256 megabytes input standard input ...