字符识别(一)
数字识别
对于数字的识别。Python3.7+Tensorflow+MNIST数据集
(如果想完全看懂代码需要有一定基础,篇幅有限缺少了很多基础知识,但是代码已经完善,可以使用)
MNIST数据集
1、组成:数字0-9 ,60000张训练图,10000张测试图
2、原先可如下直接导入,但是我运行时出错,选择下载后使用
from tensorflow.examples.tutorials.mnist import input_data
TensorFlow
1、TensorFlow™是一个基于数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief
2、这里使用TensorFlow或许有人觉得没有使用Keras方便,的确,但是TensorFlow一定程度上可以让你窥视数据的变化。并且后续的英文字符识别也是使用TensorFlow。
多的不科普了,直接代码
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import os
def num():
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'#尝试限制日志文件输出,但是貌似没用,运行一片飘红
tf.set_random_seed(1)
np.random.seed(1)
BATCH_SIZE = 50
LR = 0.001
mnist = input_data.read_data_sets('./mnist', one_hot=True)
test_x = mnist.test.images[:2000]
test_y = mnist.test.labels[:2000]
def weight_variable(shape): # 初始化权重,初始化为接近0的很小的正值
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape): # 初始化偏置
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W): # 卷积和池化,使用卷积步长为1(stride size),0边距(padding size)池化用简单传统的2x2大小的模板做max pooling
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
tf_x = tf.placeholder(tf.float32, [None, 28 * 28],name='input')/255
x_image = tf.reshape(tf_x, [-1, 28, 28, 1]) # 最后一维代表通道数目,如果是rgb则为3
tf_y = tf.placeholder("float", [None, 10])
# 第一层卷积层
W_conv1 = weight_variable([5, 5, 1, 16])
b_conv1 = bias_variable([16])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
# 第二层 卷积层
W_conv2 = weight_variable([5, 5, 16, 32])
b_conv2 = bias_variable([32])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
flat = tf.reshape(h_pool2, [-1, 7*7*32])
output = tf.layers.dense(flat, 10,name='output') # output layer
loss = tf.compat.v1.losses.softmax_cross_entropy(onehot_labels=tf_y, logits=output) # compute cost
train_op = tf.compat.v1.train.AdamOptimizer(LR).minimize(loss)
accuracy = tf.compat.v1.metrics.accuracy( labels=tf.argmax(tf_y, axis=1), predictions=tf.argmax(output, axis=1),)[1]
with tf.Session() as sess:
saver = tf.train.Saver()
init_op = tf.group(tf.compat.v1.global_variables_initializer(), tf.local_variables_initializer()) # the local var is for accuracy_op
sess.run(init_op) # initialize var in graph
saver.restore(sess, 'my_net/save_net.ckpt')
for step in range(3000):
b_x, b_y = mnist.train.next_batch(BATCH_SIZE)
_, loss_ = sess.run([train_op, loss], {tf_x: b_x, tf_y: b_y})
if step % 50 == 0:
accuracy_, flat_representation = sess.run([accuracy, flat], {tf_x: test_x, tf_y: test_y})
print('Step:', step, '| train loss: %.4f' % loss_, '| test accuracy: %.4f' % accuracy_)
save_path = saver.save(sess, 'my_net/save_net.ckpt')
num()
代码使用指导:
1、如果报错显示MNIST导入相关错误,建议下载MNIST数据集,四个后缀为gz的文件,下载后装入文件夹,文件夹重命名为MNIST,放入与代码同个文件夹内
2、注意以下这句代码是调用已经训练好的数据,第一次训练的时候注释掉。
saver.restore(sess, 'my_net/save_net.ckpt')
小结
1、如有MNIST资源需求,或有疑问请留言
2、下篇内容是将上次识别定位的字符截取并识别出来,本次只是训练网络还未使用,无法展现可视化效果。
3、如觉得有帮助,还望收藏与关注,谢谢。