神经网络训练的时候,我们需要将模型保存下来,方便后面继续训练或者用训练好的模型进行测试。因此,我们需要创建一个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(保存模型&测试单张图片)的更多相关文章

  1. tensorflow训练自己的数据集实现CNN图像分类1

    利用卷积神经网络训练图像数据分为以下几个步骤 读取图片文件 产生用于训练的批次 定义训练的模型(包括初始化参数,卷积.池化层等参数.网络) 训练 1 读取图片文件 def get_files(file ...

  2. 在C#下使用TensorFlow.NET训练自己的数据集

    在C#下使用TensorFlow.NET训练自己的数据集 今天,我结合代码来详细介绍如何使用 SciSharp STACK 的 TensorFlow.NET 来训练CNN模型,该模型主要实现 图像的分 ...

  3. 【Tensorflow系列】使用Inception_resnet_v2训练自己的数据集并用Tensorboard监控

    [写在前面] 用Tensorflow(TF)已实现好的卷积神经网络(CNN)模型来训练自己的数据集,验证目前较成熟模型在不同数据集上的准确度,如Inception_V3, VGG16,Inceptio ...

  4. TensorFlow学习笔记——LeNet-5(训练自己的数据集)

    在之前的TensorFlow学习笔记——图像识别与卷积神经网络(链接:请点击我)中了解了一下经典的卷积神经网络模型LeNet模型.那其实之前学习了别人的代码实现了LeNet网络对MNIST数据集的训练 ...

  5. TensorFlow训练MNIST数据集(1) —— softmax 单层神经网络

    1.MNIST数据集简介 首先通过下面两行代码获取到TensorFlow内置的MNIST数据集: from tensorflow.examples.tutorials.mnist import inp ...

  6. tensorflow中使用mnist数据集训练全连接神经网络-学习笔记

    tensorflow中使用mnist数据集训练全连接神经网络 ——学习曹健老师“人工智能实践:tensorflow笔记”的学习笔记, 感谢曹老师 前期准备:mnist数据集下载,并存入data目录: ...

  7. 【实践】如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统)

    如何利用tensorflow的object_detection api开源框架训练基于自己数据集的模型(Windows10系统) 一.环境配置 1. Python3.7.x(注:我用的是3.7.3.安 ...

  8. Pytorch和CNN图像分类

    Pytorch和CNN图像分类 PyTorch是一个基于Torch的Python开源机器学习库,用于自然语言处理等应用程序.它主要由Facebookd的人工智能小组开发,不仅能够 实现强大的GPU加速 ...

  9. tensorflow文本分类实战——卷积神经网络CNN

    首先说明使用的工具和环境:python3.6.8   tensorflow1.14.0   centos7.0(最好用Ubuntu) 关于环境的搭建只做简单说明,我这边是使用pip搭建了python的 ...

随机推荐

  1. Linq------错误:EntityType: EntitySet 'Products' is based on type 'Product' that has no keys defined.

    解决方法: [Table("bma_products")] public class Product { //加上[Key]即可 [Key] public int pid{get; ...

  2. tcp断开时分几步

    连接时是三次握手 断开时是四次握手,因为它是半关闭造成的

  3. Codeforces Round #186 (Div. 2).D

    纠结的一道dp. 状态转移方程还是比较好想的,优化比较纠结 D. Ilya and Roads time limit per test 3 seconds memory limit per test ...

  4. Objective-C代码学习大纲(2)

    2011-05-11 14:06 佚名 otierney 字号:T | T 本文为台湾出版的<Objective-C学习大纲>的翻译文档,系统介绍了Objective-C代码,很多名词为台 ...

  5. ios 如何对UITableView中的内容进行排序

    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSI ...

  6. java发展历程、常用dos命令与jDK工具使用

    Java菜鸟学习之旅 1.勤敲代码 2.必须将课堂上讲的内容学到位 2.1 学到会用 2.2 在学会之前不要自作主张 2.3 当天课程当天完成 3.能说会道 3.1 善于表达 3.2 学会的都能讲 4 ...

  7. Centos7.2yum安装时候出现db5错误的解决办法

    Centos7.2使用yum安装软件是出现如此错误提示 解决办法 删除 /var/lib/rpm文件夹下面所有以__db开头的文件

  8. Exchange NLB 单播和多播模式比较

    一般来说,在NLB的创建时,单网卡多播,双网卡单播. 双网卡单播时,因为主机之间不能互相通信,将设置内网通讯的网卡,也就是群集设置中的心跳. NLB模式 描述 优点 缺点 单播 网卡MAC会被NLB专 ...

  9. 预见未来丨机器学习:未来十年研究热点 量子机器学习(Quantum ML) 量子计算机利用量子相干和量子纠缠等效应来处理信息

    微软研究院AI头条 https://mp.weixin.qq.com/s/SAz5eiSOLhsdz7nlSJ1xdA 预见未来丨机器学习:未来十年研究热点 机器学习组 微软研究院AI头条 昨天 编者 ...

  10. userAgent font-family

    w view-source:http://you.163.com/ CODE <script type="text/javascript"> (function () ...