Tensorflow制作并用CNN训练自己的数据集
2018-03-14 16:46
483 查看
本人初学Tensorflow,在学习完用MNIST数据集训练简单的MLP、自编码器、CNN后,想着自己能不能做一个数据集,并用卷积神经网络训练,所以在网上查了一下资料,发现可以使用标准的TFrecords格式。但是,遇到了问题,制作好的TFrecords的数据集,运行的时候报错,网上没有找到相关的方法。后来我自己找了个方法解决了。如果有人有更好的方法,可以交流一下。
tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签。代码如下:
读取代码单独作为一个文件,起名为ReadMyOwnData.py代码如下:
1. 准备数据
我准备的是猫和狗两个类别的图片,分别存放在D盘train_data文件夹下,如下图:数据集存放.png2. 制作tfrecords文件
代码起名为make_own_data.pytfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签。代码如下:
# -*- coding: utf-8 -*- """ @author: caokai """ import os import tensorflow as tf from PIL import Image import matplotlib.pyplot as plt import numpy as np cwd='D:/train_data/' classes={'dog','cat'} #人为设定2类 writer= tf.python_io.TFRecordWriter("dog_and_cat_train.tfrecords") #要生成的文件 for index,name in enumerate(classes): class_path=cwd+name+'/' for img_name in os.listdir(class_path): img_path=class_path+img_name #每一个图片的地址 img=Image.open(img_path) img= img.resize((128,128)) img_raw=img.tobytes()#将图片转化为二进制格式 example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])) })) #example对象对label和image数据进行封装 writer.write(example.SerializeToString()) #序列化为字符串 writer.close()这样就‘狗’和‘猫’的图片打上了两类数据0和1,并且文件储存为dog_and_cat_train.tfrecords,你会发现自己的python代码所在的文件夹里有了这个文件。
3. 读取tfrecords文件
将图片和标签读出,图片reshape为128x128x3。读取代码单独作为一个文件,起名为ReadMyOwnData.py代码如下:
# -*- coding: utf-8 -*- """ tensorflow : read my own dataset @author: caokai """ import tensorflow as tf def read_and_decode(filename): # 读入dog_train.tfrecords filename_queue = tf.train.string_input_producer([filename])#生成一个queue队列 reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue)#返回文件名和文件 features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), })#将image数据和label取出来 img = tf.decode_raw(features['img_raw'], tf.uint8) img = tf.reshape(img, [128, 128, 3]) #reshape为128*128的3通道图片 img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 #在流中抛出img张量 label = tf.cast(features['label'], tf.int32) #在流中抛出label张量 return img, label
4. 使用卷积神经网络训练
这一部分Python代码起名为dog_and_cat_train.py4.1 定义好卷积神经网络的结构
要把我们读取文件的ReadMyOwnData导入,这边权重初始化使用的是tf.truncated_normal,两次卷积操作,两次最大池化,激活函数ReLU,全连接层,最后y_conv是softmax输出的二类问题。损失函数用交叉熵,优化算法Adam。卷积部分代码如下:# -*- coding: utf-8 -*- """ @author: caokai """ import tensorflow as tf import numpy as np import ReadMyOwnData batch_size = 50 #initial weights def weight_variable(shape): initial = tf.truncated_normal(shape, stddev = 0.1) return tf.Variable(initial) #initial bias def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) #convolution layer def conv2d(x,W): return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME') #max_pool layer def max_pool_4x4(x): return tf.nn.max_pool(x, ksize=[1,4,4,1], strides=[1,4,4,1], padding='SAME') x = tf.placeholder(tf.float32, [batch_size,128,128,3]) y_ = tf.placeholder(tf.float32, [batch_size,1]) #first convolution and max_pool layer W_conv1 = weight_variable([5,5,3,32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1) h_pool1 = max_pool_4x4(h_conv1) #second convolution and max_pool layer W_conv2 = weight_variable([5,5,32,64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_4x4(h_conv2) #变成全连接层,用一个MLP处理 reshape = tf.reshape(h_pool2,[batch_size, -1]) dim = reshape.get_shape()[1].value W_fc1 = weight_variable([dim, 1024]) b_fc1 = bias_variable([1024]) h_fc1 = tf.nn.relu(tf.matmul(reshape, W_fc1) + b_fc1) #dropout keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024,2]) b_fc2 = bias_variable([2]) y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) #损失函数及优化算法 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
4.2 训练
从自己的数据集中读取数据,并初始化训练image, label = ReadMyOwnData.read_and_decode("dog_and_cat_train.tfrecords") sess = tf.InteractiveSession() tf.global_variables_initializer().run() coord=tf.train.Coordinator() threads= tf.train.start_queue_runners(coord=coord)在feed数据进行训练时,尝试网上其他文章,遇到如下错误:
Cannot feed value of shape (128, 128, 3) for Tensor u'Placeholder_12:0', which has shape '(50, 128, 128, 3)'或者如下错误:
TypeError:The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, or numpy ndarrays.我尝试了一下,代码写成下面这样可以通过:
example = np.zeros((batch_size,128,128,3)) l = np.zeros((batch_size,1)) try: for i in range(20): for epoch in range(batch_size): example[epoch], l[epoch] = sess.run([image,label])#在会话中取出image和label train_step.run(feed_dict={x: example, y_: l, keep_prob: 0.5}) print(accuracy.eval(feed_dict={x: example, y_: l, keep_prob: 0.5})) #eval函数类似于重新run一遍,验证,同时修正 except tf.errors.OutOfRangeError: print('done!') finally: coord.request_stop() coord.join(threads)如果有更好更高效的读入tfrecords数据集并训练CNN的方法,可以交流一下。
相关文章推荐
- 仿照VOC2007制作自己的数据集,并在Caffe上训练Faster-RCNN
- Faster RCNN 训练自己的数据集(Matlab,python版本)及制作VOC2007格式数据集
- windows faster r-cnn制作自己的数据集并训练
- tensorflow训练自己的数据集实现CNN图像分类2(保存模型&测试单张图片)
- tensorflow训练自己的数据集实现CNN图像分类1
- 详解tensorflow训练自己的数据集实现CNN图像分类
- 使用自己的图片训练CNN分类器-TensorFlow
- Fast RCNN训练自己的数据集 (2修改读写接口)
- Caffe学习笔记3——制作并训练自己的数据集
- Tensorflow 用自己图片制作数据集 仿cifar10(二)
- Fast RCNN 训练自己的数据集✨✨✨✨✨
- Fast RCNN 训练自己的数据集(3训练和检测)
- YOLO模型训练自己数据-VOC格式数据集制作-ubuntu c++文件夹内图片批量读取与重命名
- Fast RCNN 训练自己数据集 (1编译配置)
- FCN制作自己的数据集、训练和测试全流程
- TensorFlow Object Detection API教程——利用自己制作的数据集进行训练预测和测试
- Fast RCNN 训练自己的数据集(3训练和检测)
- Fast RCNN 训练自己数据集 (1编译配置)
- Tensorflow框架下Faster-RCNN实践(一)——Faster-RCNN所需数据集制作(附代码)
- Fast RCNN 训练自己数据集 (2修改数据读取接口)