本文为参考http://i.youku.com/deeplearning101 这位大神的视频所写的一些笔记
这是一个简单的二分类问题,目的就是区别猫和狗的图片,数据集在这链接:http://pan.baidu.com/s/1dFd8kmt 密码:psor
首先编写一个input_data.py这个文件,目的就是返回
input_data.py
#coding=utf-8
import tensorflow as tf
import numpy as np
import os
# file_dir = '/home/hjxu/PycharmProjects/tf_examples/dog_cat/data/train/'
# 获取文件路径和标签
def get_files(file_dir):
# file_dir: 文件夹路径
# return: 乱序后的图片和标签
cats = []
label_cats = []
dogs = []
label_dogs = []
# 载入数据路径并写入标签值
for file in os.listdir(file_dir):
name = file.split('.')
if name[0] == 'cat':
cats.append(file_dir + file)
label_cats.append(0)
else:
dogs.append(file_dir + file)
label_dogs.append(1)
print("There are %d cats\nThere are %d dogs" % (len(cats), len(dogs)))
# 打乱文件顺序
image_list = np.hstack((cats, dogs))
label_list = np.hstack((label_cats, label_dogs))
temp = np.array([image_list, label_list])
temp = temp.transpose() # 转置
np.random.shuffle(temp)
image_list = list(temp[:, 0])
label_list = list(temp[:, 1])
label_list = [int(i) for i in label_list]
return image_list, label_list
# img_list,label_list = get_files(file_dir)
# 生成相同大小的批次
def get_batch(image, label, image_W, image_H, batch_size, capacity):
# image, label: 要生成batch的图像和标签list
# image_W, image_H: 图片的宽高
# batch_size: 每个batch有多少张图片
# capacity: 队列容量
# return: 图像和标签的batch
# 将python.list类型转换成tf能够识别的格式
image = tf.cast(image, tf.string)
label = tf.cast(label, tf.int32)
# 生成队列
input_queue = tf.train.slice_input_producer([image, label])
image_contents = tf.read_file(input_queue[0])
label = input_queue[1]
image = tf.image.decode_jpeg(image_contents, channels=3)
# 统一图片大小
# 视频方法
# image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
# 我的方法
image = tf.image.resize_images(image, [image_H, image_W], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
image = tf.cast(image, tf.float32)
# image = tf.image.per_image_standardization(image) # 标准化数据
image_batch, label_batch = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=64, # 线程
capacity=capacity)
# 这行多余?
# label_batch = tf.reshape(label_batch, [batch_size])
return image_batch, label_batch
# import matplotlib.pyplot as plt
#
# BATCH_SIZE = 2
# CAPACITY = 256
# IMG_W = 208
# IMG_H = 208
#
#
# image_list, label_list = get_files(file_dir)
# image_batch, label_batch = get_batch(image_list, label_list, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)
#
# with tf.Session() as sess:
# i = 0
# coord = tf.train.Coordinator()
# threads = tf.train.start_queue_runners(coord=coord)
# try:
# while not coord.should_stop() and i < 5:
# img, label = sess.run([image_batch, label_batch])
#
# for j in np.arange(BATCH_SIZE):
# print("label: %d" % label[j])
# plt.imshow(img[j, :, :, :])
# plt.show()
# i += 1
# except tf.errors.OutOfRangeError:
# print("done!")
# finally:
# coord.request_stop()
# coord.join(threads)
函数get_files(file_dir)
的功能是获取给定路径file_dir
下的所有的训练数据(包括图片和标签),以list
的形式返回。
由于训练数据前12500张是猫,后12500张是狗,如果直接按这个顺序训练,训练效果可能会受影响(我自己猜的),所以需要将顺序打乱,至于是读取数据的时候乱序还是训练的时候乱序可以自己选择(视频里说在这里乱序速度比较快)。因为图片和标签是一一对应的,所以要整合到一起乱序。
这里先用np.hstack()
方法将猫和狗图片和标签整合到一起,得到image_list
和label_list
,hstack((a,b))
的功能是将a和b以水平的方式连接,比如原来cats
和dogs
是长度为12500的向量,执行了hstack(cats, dogs)
后,image_list
的长度为25000,同理label_list
的长度也为25000。接着将一一对应的image_list
和label_list
再合并一次。temp
的大小是2×25000,经过转置(变成25000×2),然后使用np.random.shuffle()
方法进行乱序。
最后从temp中分别取出乱序后的image_list
和label_list
列向量,作为函数的返回值。这里要注意,因为label_list
里面的数据类型是字符串类型,所以加上label_list = [int(i) for i in label_list]
这么一行将其转为int类型。
model.py
#coding=utf-8
import tensorflow as tf
def inference(images, batch_size, n_classes):
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, 3, 3, 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, 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(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')
# pool2 and norm2
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, 3, 3, 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, 128],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[128],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)
# local4
with tf.variable_scope('local4') as scope:
weights = tf.get_variable('weights',
shape=[128, 128],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[128],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name='local4')
# softmax
with tf.variable_scope('softmax_linear') as scope:
weights = tf.get_variable('softmax_linear',
shape=[128, n_classes],
dtype=tf.float32,
initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
biases = tf.get_variable('biases',
shape=[n_classes],
dtype=tf.float32,
initializer=tf.constant_initializer(0.1))
softmax_linear = tf.add(tf.matmul(local4, weights), biases, name='softmax_linear')
return softmax_linear
def losses(logits, labels):
with tf.variable_scope('loss') as scope:
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits \
(logits=logits, labels=labels, name='xentropy_per_example')
loss = tf.reduce_mean(cross_entropy, name='loss')
tf.summary.scalar(scope.name + '/loss', loss)
return loss
def trainning(loss, learning_rate):
with tf.name_scope('optimizer'):
optimizer = tf.train.AdamOptimizer(learning_rate= learning_rate)
global_step = tf.Variable(0, name='global_step', trainable=False)
train_op = optimizer.minimize(loss, global_step= global_step)
return train_op
def evaluation(logits, labels):
with tf.variable_scope('accuracy') as scope:
correct = tf.nn.in_top_k(logits, labels, 1)
correct = tf.cast(correct, tf.float16)
accuracy = tf.reduce_mean(correct)
tf.summary.scalar(scope.name + '/accuracy', accuracy)
return accuracy
函数get_batch()
用于将图片分批次,因为一次性将所有25000张图片载入内存不现实也不必要,所以将图片分成不同批次进行训练。这里传入的image
和label
参数就是函数get_files()
返回的image_list
和label_list
,是Python中的list类型,所以需要将其转为TensorFlow可以识别的tensor
格式。
这里使用队列来获取数据,因为队列操作牵扯到线程,我自己对这块也不懂,,所以只从大体上理解了一下,想要系统学习可以去官方文档看看,这里引用了一张图解释。
我认为大体上可以这么理解:每次训练时,从队列中取一个batch送到网络进行训练,然后又有新的图片从训练库中注入队列,这样循环往复。队列相当于起到了训练库到网络模型间数据管道的作用,训练数据通过队列送入网络。(我也不确定这么理解对不对,欢迎指正)
继续看程序,我们使用slice_input_producer()
来建立一个队列,将image
和label
放入一个list中当做参数传给该函数。然后从队列中取得image
和label
,要注意,用read_file()
读取图片之后,要按照图片格式进行解码。本例程中训练数据是jpg格式的,所以使用decode_jpeg()
解码器,如果是其他格式,就要用其他解码器,具体可以从官方API中查询。注意decode出来的数据类型是uint8
,之后模型卷积层里面conv2d()
要求输入数据为float32
类型,所以如果删掉标准化步骤之后需要进行类型转换。
因为训练库中图片大小是不一样的,所以还需要将图片裁剪成相同大小(img_W
和img_H
)。视频中是用resize_image_with_crop_or_pad()
方法来裁剪图片,这种方法是从图像中心向四周裁剪,如果图片超过规定尺寸,最后只会剩中间区域的一部分,可能一只狗只剩下躯干,头都不见了,用这样的图片训练结果肯定会受到影响。所以这里我稍微改动了一下,使用resize_images()
对图像进行缩放,而不是裁剪,采用NEAREST_NEIGHBOR
插值方法(其他几种插值方法出来的结果图像是花的,具体原因不知道)。
缩放之后视频中还进行了per_image_standardization (标准化)
步骤,但加了这步之后,得到的图片是花的,虽然各个通道单独提出来是正常的,三通道一起就不对了,删了标准化这步结果正常,所以这里把标准化步骤注释掉了。
然后用tf.train.batch()
方法获取batch,还有一种方法是tf.train.shuffle_batch()
,因为之前我们已经乱序过了,这里用普通的batch()
就好。视频中获取batch后还对label进行了一下reshape()操作,在我看来这步是多余的,从batch()
方法中获取的大小已经符合我们的要求了,注释掉也没什么影响,能正常获取图片。
最后将得到的image_batch
和label_batch
返回。image_batch
是一个4D的tensor,[batch, width, height, channels],label_batch
是一个1D的tensor,[batch]。
可以用下面的代码测试获取图片是否成功,因为之前将图片转为float32了,因此这里imshow()出来的图片色彩会有点奇怪,因为本来imshow()是显示uint8类型的数据(灰度值在uint8类型下是0~255,转为float32后会超出这个范围,所以色彩有点奇怪),不过这不影响后面模型的训练。
training.py
#coding=utf-8
import os
import numpy as np
import tensorflow as tf
import input_data
import model
N_CLASSES = 2 #猫和狗
IMG_W = 208 # resize图像,太大的话训练时间久
IMG_H = 208
BATCH_SIZE = 16
CAPACITY = 2000
MAX_STEP = 10000 # 一般大于10K
learning_rate = 0.0001 # 一般小于0.0001
train_dir = '/home/hjxu/PycharmProjects/tf_examples/dog_cat/data/train/'
logs_train_dir = '/home/hjxu/PycharmProjects/tf_examples/dog_cat/log/train/'
train, train_label = input_data.get_files(train_dir)
train_batch,train_label_batch=input_data.get_batch(train,
train_label,
IMG_W,
IMG_H,
BATCH_SIZE,
CAPACITY)
train_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)
train_loss = model.losses(train_logits, train_label_batch)
train_op = model.trainning(train_loss, learning_rate)
train__acc = model.evaluation(train_logits, train_label_batch)
summary_op = tf.summary.merge_all() #这个是log汇总记录
#产生一个会话
sess = tf.Session()
#产生一个writer来写log文件
train_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)
#产生一个saver来存储训练好的模型
saver = tf.train.Saver()
#所有节点初始化
sess.run(tf.global_variables_initializer())
#队列监控
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
#执行MAX_STEP步的训练,一步一个batch
for step in np.arange(MAX_STEP):
if coord.should_stop():
break
#启动以下操作节点,有个疑问,为什么train_logits在这里没有开启?
_, tra_loss, tra_acc = sess.run([train_op, train_loss, train__acc])
#每隔50步打印一次当前的loss以及acc,同时记录log,写入writer
if step % 50 == 0:
print('Step %d, train loss = %.2f, train accuracy = %.2f%%' %(step, tra_loss, tra_acc*100.0))
summary_str = sess.run(summary_op)
train_writer.add_summary(summary_str, step)
#每隔2000步,保存一次训练好的模型
if step % 2000 == 0 or (step + 1) == MAX_STEP:
checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')
saver.save(sess, checkpoint_path, global_step=step)
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
coord.request_stop()
这时候会在logs文件夹生产一些文件,我们可以用tensorboard来显示,下一篇博客记下tensorboard的简单使用
参考博客http://blog.csdn.net/qq_16137569/article/details/72802387
http://blog.csdn.net/xinyu3307/article/details/74943033