经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 大数据/云/AI » TensorFlow » 查看文章
Python通过TensorFlow卷积神经网络实现猫狗识别
来源:jb51  时间:2019/3/15 8:35:21  对本文有异议

这份数据集来源于Kaggle,数据集有12500只猫和12500只狗。在这里简单介绍下整体思路

  1. 处理数据
  2. 设计神经网络
  3. 进行训练测试

1. 数据处理

将图片数据处理为 tf 能够识别的数据格式,并将数据设计批次。

  • 第一步get_files() 方法读取图片,然后根据图片名,添加猫狗 label,然后再将 image和label 放到 数组中,打乱顺序返回
  • 将第一步处理好的图片 和label 数组 转化为 tensorflow 能够识别的格式,然后将图片裁剪和补充进行标准化处理,分批次返回。

新建数据处理文件 ,文件名 input_data.py

  1. import tensorflow as tf
  2. import os
  3. import numpy as np
  4. def get_files(file_dir):
  5. cats = []
  6. label_cats = []
  7. dogs = []
  8. label_dogs = []
  9. for file in os.listdir(file_dir):
  10. name = file.split(sep='.')
  11. if 'cat' in name[0]:
  12. cats.append(file_dir + file)
  13. label_cats.append(0)
  14. else:
  15. if 'dog' in name[0]:
  16. dogs.append(file_dir + file)
  17. label_dogs.append(1)
  18. image_list = np.hstack((cats,dogs))
  19. label_list = np.hstack((label_cats,label_dogs))
  20. # print('There are %d cats\nThere are %d dogs' %(len(cats), len(dogs)))
  21. # 多个种类分别的时候需要把多个种类放在一起,打乱顺序,这里不需要
  22. # 把标签和图片都放倒一个 temp 中 然后打乱顺序,然后取出来
  23. temp = np.array([image_list,label_list])
  24. temp = temp.transpose()
  25. # 打乱顺序
  26. np.random.shuffle(temp)
  27. # 取出第一个元素作为 image 第二个元素作为 label
  28. image_list = list(temp[:,0])
  29. label_list = list(temp[:,1])
  30. label_list = [int(i) for i in label_list]
  31. return image_list,label_list
  32. # 测试 get_files
  33. # imgs , label = get_files('/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/testImg/')
  34. # for i in imgs:
  35. # print("img:",i)
  36. # for i in label:
  37. # print('label:',i)
  38. # 测试 get_files end
  39. # image_W ,image_H 指定图片大小,batch_size 每批读取的个数 ,capacity队列中 最多容纳元素的个数
  40. def get_batch(image,label,image_W,image_H,batch_size,capacity):
  41. # 转换数据为 ts 能识别的格式
  42. image = tf.cast(image,tf.string)
  43. label = tf.cast(label, tf.int32)
  44. # 将image 和 label 放倒队列里
  45. input_queue = tf.train.slice_input_producer([image,label])
  46. label = input_queue[1]
  47. # 读取图片的全部信息
  48. image_contents = tf.read_file(input_queue[0])
  49. # 把图片解码,channels =3 为彩色图片, r,g ,b 黑白图片为 1 ,也可以理解为图片的厚度
  50. image = tf.image.decode_jpeg(image_contents,channels =3)
  51. # 将图片以图片中心进行裁剪或者扩充为 指定的image_W,image_H
  52. image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
  53. # 对数据进行标准化,标准化,就是减去它的均值,除以他的方差
  54. image = tf.image.per_image_standardization(image)
  55. # 生成批次 num_threads 有多少个线程根据电脑配置设置 capacity 队列中 最多容纳图片的个数 tf.train.shuffle_batch 打乱顺序,
  56. image_batch, label_batch = tf.train.batch([image, label],batch_size = batch_size, num_threads = 64, capacity = capacity)
  57. # 重新定义下 label_batch 的形状
  58. label_batch = tf.reshape(label_batch , [batch_size])
  59. # 转化图片
  60. image_batch = tf.cast(image_batch,tf.float32)
  61. return image_batch, label_batch
  62. # test get_batch
  63. # import matplotlib.pyplot as plt
  64. # BATCH_SIZE = 2
  65. # CAPACITY = 256
  66. # IMG_W = 208
  67. # IMG_H = 208
  68. # train_dir = '/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/testImg/'
  69. # image_list, label_list = get_files(train_dir)
  70. # image_batch, label_batch = get_batch(image_list, label_list, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)
  71. # with tf.Session() as sess:
  72. # i = 0
  73. # # Coordinator 和 start_queue_runners 监控 queue 的状态,不停的入队出队
  74. # coord = tf.train.Coordinator()
  75. # threads = tf.train.start_queue_runners(coord=coord)
  76. # # coord.should_stop() 返回 true 时也就是 数据读完了应该调用 coord.request_stop()
  77. # try:
  78. # while not coord.should_stop() and i<1:
  79. # # 测试一个步
  80. # img, label = sess.run([image_batch, label_batch])
  81. # for j in np.arange(BATCH_SIZE):
  82. # print('label: %d' %label[j])
  83. # # 因为是个4D 的数据所以第一个为 索引 其他的为冒号就行了
  84. # plt.imshow(img[j,:,:,:])
  85. # plt.show()
  86. # i+=1
  87. # # 队列中没有数据
  88. # except tf.errors.OutOfRangeError:
  89. # print('done!')
  90. # finally:
  91. # coord.request_stop()
  92. # coord.join(threads)
  93. # sess.close()

2. 设计神经网络

利用卷积神经网路处理,网络结构为

  1. # conv1 卷积层 1
  2. # pooling1_lrn 池化层 1
  3. # conv2 卷积层 2
  4. # pooling2_lrn 池化层 2
  5. # local3 全连接层 1
  6. # local4 全连接层 2
  7. # softmax 全连接层 3

新建神经网络文件 ,文件名 model.py

  1. #coding=utf-8
  2. import tensorflow as tf
  3. def inference(images, batch_size, n_classes):
  4. with tf.variable_scope('conv1') as scope:
  5. # 卷积盒的为 3*3 的卷积盒,图片厚度是3,输出是16个featuremap
  6. weights = tf.get_variable('weights',
  7. shape=[3, 3, 3, 16],
  8. dtype=tf.float32,
  9. initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
  10. biases = tf.get_variable('biases',
  11. shape=[16],
  12. dtype=tf.float32,
  13. initializer=tf.constant_initializer(0.1))
  14. conv = tf.nn.conv2d(images, weights, strides=[1, 1, 1, 1], padding='SAME')
  15. pre_activation = tf.nn.bias_add(conv, biases)
  16. conv1 = tf.nn.relu(pre_activation, name=scope.name)
  17. with tf.variable_scope('pooling1_lrn') as scope:
  18. pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pooling1')
  19. norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
  20. with tf.variable_scope('conv2') as scope:
  21. weights = tf.get_variable('weights',
  22. shape=[3, 3, 16, 16],
  23. dtype=tf.float32,
  24. initializer=tf.truncated_normal_initializer(stddev=0.1, dtype=tf.float32))
  25. biases = tf.get_variable('biases',
  26. shape=[16],
  27. dtype=tf.float32,
  28. initializer=tf.constant_initializer(0.1))
  29. conv = tf.nn.conv2d(norm1, weights, strides=[1, 1, 1, 1], padding='SAME')
  30. pre_activation = tf.nn.bias_add(conv, biases)
  31. conv2 = tf.nn.relu(pre_activation, name='conv2')
  32. # pool2 and norm2
  33. with tf.variable_scope('pooling2_lrn') as scope:
  34. norm2 = tf.nn.lrn(conv2, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')
  35. pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME', name='pooling2')
  36. with tf.variable_scope('local3') as scope:
  37. reshape = tf.reshape(pool2, shape=[batch_size, -1])
  38. dim = reshape.get_shape()[1].value
  39. weights = tf.get_variable('weights',
  40. shape=[dim, 128],
  41. dtype=tf.float32,
  42. initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
  43. biases = tf.get_variable('biases',
  44. shape=[128],
  45. dtype=tf.float32,
  46. initializer=tf.constant_initializer(0.1))
  47. local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)
  48. # local4
  49. with tf.variable_scope('local4') as scope:
  50. weights = tf.get_variable('weights',
  51. shape=[128, 128],
  52. dtype=tf.float32,
  53. initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
  54. biases = tf.get_variable('biases',
  55. shape=[128],
  56. dtype=tf.float32,
  57. initializer=tf.constant_initializer(0.1))
  58. local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name='local4')
  59. # softmax
  60. with tf.variable_scope('softmax_linear') as scope:
  61. weights = tf.get_variable('softmax_linear',
  62. shape=[128, n_classes],
  63. dtype=tf.float32,
  64. initializer=tf.truncated_normal_initializer(stddev=0.005, dtype=tf.float32))
  65. biases = tf.get_variable('biases',
  66. shape=[n_classes],
  67. dtype=tf.float32,
  68. initializer=tf.constant_initializer(0.1))
  69. softmax_linear = tf.add(tf.matmul(local4, weights), biases, name='softmax_linear')
  70. return softmax_linear
  71. def losses(logits, labels):
  72. with tf.variable_scope('loss') as scope:
  73. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits (logits=logits, labels=labels, name='xentropy_per_example')
  74. loss = tf.reduce_mean(cross_entropy, name='loss')
  75. tf.summary.scalar(scope.name + '/loss', loss)
  76. return loss
  77. def trainning(loss, learning_rate):
  78. with tf.name_scope('optimizer'):
  79. optimizer = tf.train.AdamOptimizer(learning_rate= learning_rate)
  80. global_step = tf.Variable(0, name='global_step', trainable=False)
  81. train_op = optimizer.minimize(loss, global_step= global_step)
  82. return train_op
  83. def evaluation(logits, labels):
  84. with tf.variable_scope('accuracy') as scope:
  85. correct = tf.nn.in_top_k(logits, labels, 1)
  86. correct = tf.cast(correct, tf.float16)
  87. accuracy = tf.reduce_mean(correct)
  88. tf.summary.scalar(scope.name + '/accuracy', accuracy)
  89. return accuracy

3. 训练数据,并将训练的模型存储

  1. import os
  2. import numpy as np
  3. import tensorflow as tf
  4. import input_data
  5. import model
  6. N_CLASSES = 2 # 2个输出神经元,[1,0] 或者 [0,1]猫和狗的概率
  7. IMG_W = 208 # 重新定义图片的大小,图片如果过大则训练比较慢
  8. IMG_H = 208
  9. BATCH_SIZE = 32 #每批数据的大小
  10. CAPACITY = 256
  11. MAX_STEP = 15000 # 训练的步数,应当 >= 10000
  12. learning_rate = 0.0001 # 学习率,建议刚开始的 learning_rate <= 0.0001
  13. def run_training():
  14. # 数据集
  15. train_dir = '/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/img/' #My dir--20170727-csq
  16. #logs_train_dir 存放训练模型的过程的数据,在tensorboard 中查看
  17. logs_train_dir = '/Users/yangyibo/GitWork/pythonLean/AI/猫狗识别/saveNet/'
  18. # 获取图片和标签集
  19. train, train_label = input_data.get_files(train_dir)
  20. # 生成批次
  21. train_batch, train_label_batch = input_data.get_batch(train,
  22. train_label,
  23. IMG_W,
  24. IMG_H,
  25. BATCH_SIZE,
  26. CAPACITY)
  27. # 进入模型
  28. train_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)
  29. # 获取 loss
  30. train_loss = model.losses(train_logits, train_label_batch)
  31. # 训练
  32. train_op = model.trainning(train_loss, learning_rate)
  33. # 获取准确率
  34. train__acc = model.evaluation(train_logits, train_label_batch)
  35. # 合并 summary
  36. summary_op = tf.summary.merge_all()
  37. sess = tf.Session()
  38. # 保存summary
  39. train_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)
  40. saver = tf.train.Saver()
  41. sess.run(tf.global_variables_initializer())
  42. coord = tf.train.Coordinator()
  43. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  44. try:
  45. for step in np.arange(MAX_STEP):
  46. if coord.should_stop():
  47. break
  48. _, tra_loss, tra_acc = sess.run([train_op, train_loss, train__acc])
  49. if step % 50 == 0:
  50. print('Step %d, train loss = %.2f, train accuracy = %.2f%%' %(step, tra_loss, tra_acc*100.0))
  51. summary_str = sess.run(summary_op)
  52. train_writer.add_summary(summary_str, step)
  53. if step % 2000 == 0 or (step + 1) == MAX_STEP:
  54. # 每隔2000步保存一下模型,模型保存在 checkpoint_path 中
  55. checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')
  56. saver.save(sess, checkpoint_path, global_step=step)
  57. except tf.errors.OutOfRangeError:
  58. print('Done training -- epoch limit reached')
  59. finally:
  60. coord.request_stop()
  61. coord.join(threads)
  62. sess.close()
  63. # train
  64. run_training()

关于保存的模型怎么使用将在下一篇文章中展示。

TensorFlow 卷积神经网络之使用训练好的模型识别猫狗图片

如果需要训练数据集可以评论留下联系方式。

原文完整代码地址:

https://github.com/527515025/My-TensorFlow-tutorials/tree/master/猫狗识别

欢迎 star 欢迎提问。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对w3xue的支持。如果你想了解更多相关内容请查看下面相关链接

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号