train_model.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import tensorflow as tf
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. import time
  7. from PIL import Image
  8. import random
  9. import os
  10. from cnnlib.network import CNN
  11. from log_ware import LogWare
  12. log_inst = LogWare()
  13. logger = log_inst.get_logger()
  14. class TrainError(Exception):
  15. pass
  16. class TrainModel(CNN):
  17. def __init__(self, train_img_path, verify_img_path, char_set, model_save_dir, cycle_stop, acc_stop, cycle_save,
  18. image_suffix, train_batch_size, test_batch_size, verify=False):
  19. # 训练相关参数
  20. self.cycle_stop = cycle_stop
  21. self.acc_stop = acc_stop
  22. self.cycle_save = cycle_save
  23. self.train_batch_size = train_batch_size
  24. self.test_batch_size = test_batch_size
  25. self.image_suffix = image_suffix
  26. char_set = [str(i) for i in char_set]
  27. # 打乱文件顺序+校验图片格式
  28. self.train_img_path = train_img_path
  29. self.train_images_list = os.listdir(train_img_path)
  30. # 校验格式
  31. if verify:
  32. self.confirm_image_suffix()
  33. # 打乱文件顺序
  34. random.seed(time.time())
  35. random.shuffle(self.train_images_list)
  36. # 验证集文件
  37. self.verify_img_path = verify_img_path
  38. self.verify_images_list = os.listdir(verify_img_path)
  39. # 获得图片宽高和字符长度基本信息
  40. label, captcha_array = self.gen_captcha_text_image(train_img_path, self.train_images_list[0])
  41. captcha_shape = captcha_array.shape
  42. captcha_shape_len = len(captcha_shape)
  43. if captcha_shape_len == 3:
  44. image_height, image_width, channel = captcha_shape
  45. self.channel = channel
  46. elif captcha_shape_len == 2:
  47. image_height, image_width = captcha_shape
  48. else:
  49. raise TrainError("图片转换为矩阵时出错,请检查图片格式")
  50. # 初始化变量
  51. super(TrainModel, self).__init__(image_height, image_width, len(label), char_set, model_save_dir)
  52. # 相关信息打印
  53. logger.debug("-->图片尺寸: %s X %s", image_height, image_width)
  54. logger.debug("-->验证码长度: %s", self.max_captcha)
  55. logger.debug("-->验证码共%s类 %s", self.char_set_len, char_set)
  56. logger.debug("-->使用测试集为 %s", train_img_path)
  57. logger.debug("-->使验证集为 %s", verify_img_path)
  58. # test model input and output
  59. logger.debug(">>> Start model test")
  60. batch_x, batch_y = self.get_batch(0, size=100)
  61. logger.debug(">>> input batch images shape: %s", batch_x.shape)
  62. logger.debug(">>> input batch labels shape: %s", batch_y.shape)
  63. @staticmethod
  64. def gen_captcha_text_image(img_path, img_name):
  65. """
  66. 返回一个验证码的array形式和对应的字符串标签
  67. :return:tuple (str, numpy.array)
  68. """
  69. # 标签
  70. label = img_name.split("_")[0]
  71. # 文件
  72. img_file = os.path.join(img_path, img_name)
  73. captcha_image = Image.open(img_file)
  74. captcha_array = np.array(captcha_image) # 向量化
  75. return label, captcha_array
  76. def get_batch(self, n, size=128):
  77. batch_x = np.zeros([size, self.image_height * self.image_width]) # 初始化
  78. batch_y = np.zeros([size, self.max_captcha * self.char_set_len]) # 初始化
  79. max_batch = int(len(self.train_images_list) / size)
  80. # print("max_batch: %s", max_batch)
  81. if max_batch - 1 < 0:
  82. raise TrainError("训练集图片数量需要大于每批次训练的图片数量")
  83. if n > max_batch - 1:
  84. n = n % max_batch
  85. s = n * size
  86. e = (n + 1) * size
  87. this_batch = self.train_images_list[s:e]
  88. # print("%s:%s", s, e))
  89. for i, img_name in enumerate(this_batch):
  90. label, image_array = self.gen_captcha_text_image(self.train_img_path, img_name)
  91. image_array = self.convert2gray(image_array) # 灰度化图片
  92. batch_x[i, :] = image_array.flatten() / 255 # flatten 转为一维
  93. batch_y[i, :] = self.text2vec(label) # 生成 oneHot
  94. return batch_x, batch_y
  95. def get_verify_batch(self, size=100):
  96. batch_x = np.zeros([size, self.image_height * self.image_width]) # 初始化
  97. batch_y = np.zeros([size, self.max_captcha * self.char_set_len]) # 初始化
  98. verify_images = []
  99. for i in range(size):
  100. verify_images.append(random.choice(self.verify_images_list))
  101. for i, img_name in enumerate(verify_images):
  102. label, image_array = self.gen_captcha_text_image(self.verify_img_path, img_name)
  103. image_array = self.convert2gray(image_array) # 灰度化图片
  104. batch_x[i, :] = image_array.flatten() / 255 # flatten 转为一维
  105. batch_y[i, :] = self.text2vec(label) # 生成 oneHot
  106. return batch_x, batch_y
  107. def confirm_image_suffix(self):
  108. # 在训练前校验所有文件格式
  109. print("开始校验所有图片后缀")
  110. for index, img_name in enumerate(self.train_images_list):
  111. print("%s image pass", index)
  112. if not img_name.endswith(self.image_suffix):
  113. raise TrainError('confirm images suffix:you request [.{}] file but get file [{}]'
  114. .format(self.image_suffix, img_name))
  115. logger.debug("所有图片格式校验通过")
  116. def train_cnn(self):
  117. y_predict = self.model()
  118. logger.debug(">>> input batch predict shape: %s", y_predict.shape)
  119. logger.debug(">>> End model test")
  120. # 计算概率 损失
  121. with tf.name_scope('cost'):
  122. cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_predict, labels=self.Y))
  123. # 梯度下降
  124. with tf.name_scope('train'):
  125. optimizer = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost)
  126. # 计算准确率
  127. predict = tf.reshape(y_predict, [-1, self.max_captcha, self.char_set_len]) # 预测结果
  128. max_idx_p = tf.argmax(predict, 2) # 预测结果
  129. max_idx_l = tf.argmax(tf.reshape(self.Y, [-1, self.max_captcha, self.char_set_len]), 2) # 标签
  130. # 计算准确率
  131. correct_pred = tf.equal(max_idx_p, max_idx_l)
  132. with tf.name_scope('char_acc'):
  133. accuracy_char_count = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  134. with tf.name_scope('image_acc'):
  135. accuracy_image_count = tf.reduce_mean(tf.reduce_min(tf.cast(correct_pred, tf.float32), axis=1))
  136. # 模型保存对象
  137. saver = tf.train.Saver()
  138. with tf.Session() as sess:
  139. init = tf.global_variables_initializer()
  140. sess.run(init)
  141. # 恢复模型
  142. if os.path.exists(self.model_save_dir):
  143. try:
  144. saver.restore(sess, self.model_save_dir)
  145. # 判断捕获model文件夹中没有模型文件的错误
  146. except ValueError:
  147. logger.debug("model文件夹为空,将创建新模型")
  148. else:
  149. pass
  150. # 写入日志
  151. temp_log_dir = log_inst.get_log_dir()
  152. sess_log_dir = os.path.join(temp_log_dir, 'train_sess')
  153. # 是否存在目录,不存在就创建
  154. mkdir_with_lambda = lambda x: os.makedirs(x) if not os.path.exists(x) else True
  155. mkdir_with_lambda(sess_log_dir)
  156. tf.summary.FileWriter(sess_log_dir, sess.graph)
  157. step = 1
  158. for i in range(self.cycle_stop):
  159. batch_x, batch_y = self.get_batch(i, size=self.train_batch_size)
  160. # 梯度下降训练
  161. _, cost_ = sess.run([optimizer, cost],
  162. feed_dict={self.X: batch_x, self.Y: batch_y, self.keep_prob: 0.75})
  163. if step % 10 == 0:
  164. # 基于训练集的测试
  165. batch_x_test, batch_y_test = self.get_batch(i, size=self.train_batch_size)
  166. acc_char = sess.run(accuracy_char_count,
  167. feed_dict={self.X: batch_x_test, self.Y: batch_y_test, self.keep_prob: 1.})
  168. acc_image = sess.run(accuracy_image_count,
  169. feed_dict={self.X: batch_x_test, self.Y: batch_y_test, self.keep_prob: 1.})
  170. print("第{}次训练 >>> ".format(step))
  171. print("[训练集] 字符准确率为 {:.5f} 图片准确率为 {:.5f} >>> loss {:.10f}".format(acc_char, acc_image, cost_))
  172. # with open("loss_train.csv", "a+") as f:
  173. # f.write("{},{},{},{}\n".format(step, acc_char, acc_image, cost_))
  174. # 基于验证集的测试
  175. batch_x_verify, batch_y_verify = self.get_verify_batch(size=self.test_batch_size)
  176. acc_char = sess.run(accuracy_char_count,
  177. feed_dict={self.X: batch_x_verify, self.Y: batch_y_verify, self.keep_prob: 1.})
  178. acc_image = sess.run(accuracy_image_count,
  179. feed_dict={self.X: batch_x_verify, self.Y: batch_y_verify, self.keep_prob: 1.})
  180. print("[验证集] 字符准确率为 {:.5f} 图片准确率为 {:.5f} >>> loss {:.10f}".format(acc_char, acc_image, cost_))
  181. # with open("loss_test.csv", "a+") as f:
  182. # f.write("{}, {},{},{}\n".format(step, acc_char, acc_image, cost_))
  183. # 准确率达到99%后保存并停止
  184. if acc_image > self.acc_stop:
  185. saver.save(sess, self.model_save_dir)
  186. logger.debug("验证集准确率达到%s,保存模型成功", str(self.acc_stop * 100) + "%")
  187. break
  188. # 每训练500轮就保存一次
  189. if i % self.cycle_save == 0:
  190. saver.save(sess, self.model_save_dir)
  191. print("定时保存模型成功")
  192. step += 1
  193. saver.save(sess, self.model_save_dir)
  194. def recognize_captcha(self):
  195. label, captcha_array = self.gen_captcha_text_image(self.train_img_path, random.choice(self.train_images_list))
  196. f = plt.figure()
  197. ax = f.add_subplot(111)
  198. ax.text(0.1, 0.9, "origin:" + label, ha='center', va='center', transform=ax.transAxes)
  199. plt.imshow(captcha_array)
  200. # 预测图片
  201. image = self.convert2gray(captcha_array)
  202. image = image.flatten() / 255
  203. y_predict = self.model()
  204. saver = tf.train.Saver()
  205. with tf.Session() as sess:
  206. saver.restore(sess, self.model_save_dir)
  207. predict = tf.argmax(tf.reshape(y_predict, [-1, self.max_captcha, self.char_set_len]), 2)
  208. text_list = sess.run(predict, feed_dict={self.X: [image], self.keep_prob: 1.})
  209. predict_text = text_list[0].tolist()
  210. logger.debug("正确: %s 预测: %s", label, predict_text)
  211. # 显示图片和预测结果
  212. p_text = ""
  213. for p in predict_text:
  214. p_text += str(self.char_set[p])
  215. logger.debug("p_text: %s", p_text)
  216. plt.text(20, 1, 'predict:{}'.format(p_text))
  217. plt.show()
  218. def main():
  219. with open("conf/sample_config.json", "r") as f:
  220. sample_conf = json.load(f)
  221. train_image_dir = sample_conf["train_image_dir"]
  222. verify_image_dir = sample_conf["test_image_dir"]
  223. model_save_dir = sample_conf["model_save_dir"]
  224. cycle_stop = sample_conf["cycle_stop"]
  225. acc_stop = sample_conf["acc_stop"]
  226. cycle_save = sample_conf["cycle_save"]
  227. enable_gpu = sample_conf["enable_gpu"]
  228. image_suffix = sample_conf['image_suffix']
  229. use_labels_json_file = sample_conf['use_labels_json_file']
  230. train_batch_size = sample_conf['train_batch_size']
  231. test_batch_size = sample_conf['test_batch_size']
  232. if use_labels_json_file:
  233. with open("tools/labels.json", "r") as f:
  234. char_set = f.read().strip()
  235. else:
  236. char_set = sample_conf["char_set"]
  237. if not enable_gpu:
  238. # 设置以下环境变量可开启CPU识别
  239. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  240. os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  241. tm = TrainModel(train_image_dir, verify_image_dir, char_set, model_save_dir, cycle_stop, acc_stop, cycle_save,
  242. image_suffix, train_batch_size, test_batch_size, verify=False)
  243. tm.train_cnn() # 开始训练模型
  244. # tm.recognize_captcha() # 识别图片示例
  245. if __name__ == '__main__':
  246. main()