Lenet车牌号字符识别+保存模型
# 部分函数请参考前一篇或后一篇文章
import tensorflow as tf
import tfrecords2array
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
def lenet(char_classes):
y_train = []
x_train = []
y_test = []
x_test = []
for char_class in char_classes:
train_data = tfrecords2array.tfrecord2array(
r"./data_tfrecords/" + char_class + "_tfrecords/train.tfrecords")
test_data = tfrecords2array.tfrecord2array(
r"./data_tfrecords/" + char_class + "_tfrecords/test.tfrecords")
y_train.append(train_data[0])
x_train.append(train_data[1])
y_test.append(test_data[0])
x_test.append(test_data[1])
for i in [y_train, x_train, y_test, x_test]:
for j in i:
print(j.shape)
y_train = np.vstack(y_train)
x_train = np.vstack(x_train)
y_test = np.vstack(y_test)
x_test = np.vstack(x_test)
class_num = y_test.shape[-1]
print("x_train.shape=" + str(x_train.shape))
print("x_test.shape=" + str(x_test.shape))
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, class_num])
# 把x更改为4维张量,第1维代表样本数量,第2维和第3维代表图像长宽, 第4维代表图像通道数, 1表示黑白
x_image = tf.reshape(x, [-1, 28, 28, 1])
# 第一层:卷积层
conv1_weights = tf.get_variable(
"conv1_weights",
[5, 5, 1, 32],
initializer=tf.truncated_normal_initializer(stddev=0.1))
# 过滤器大小为5*5, 当前层深度为1, 过滤器的深度为32
conv1_biases = tf.get_variable("conv1_biases", [32],
initializer=tf.constant_initializer(0.0))
conv1 = tf.nn.conv2d(x_image, conv1_weights, strides=[1, 1, 1, 1],
padding='SAME')
# 移动步长为1, 使用全0填充
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases)) # 激活函数Relu去线性化
# 第二层:最大池化层
# 池化层过滤器的大小为2*2, 移动步长为2,使用全0填充
pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],
padding='SAME')
# 第三层:卷积层
conv2_weights = tf.get_variable(
"conv2_weights",
[5, 5, 32, 64],
initializer=tf.truncated_normal_initializer(stddev=0.1))
# 过滤器大小为5*5, 当前层深度为32, 过滤器的深度为64
conv2_biases = tf.get_variable(
"conv2_biases", [64], initializer=tf.constant_initializer(0.0))
conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1],
padding='SAME')
# 移动步长为1, 使用全0填充
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))
# 第四层:最大池化层
# 池化层过滤器的大小为2*2, 移动步长为2,使用全0填充
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],
padding='SAME')
# 第五层:全连接层
fc1_weights = tf.get_variable("fc1_weights", [7 * 7 * 64, 1024],
initializer=tf.truncated_normal_initializer(
stddev=0.1))
# 7*7*64=3136把前一层的输出变成特征向量
fc1_biases = tf.get_variable(
"fc1_biases", [1024], initializer=tf.constant_initializer(0.1))
pool2_vector = tf.reshape(pool2, [-1, 7 * 7 * 64])
fc1 = tf.nn.relu(tf.matmul(pool2_vector, fc1_weights) + fc1_biases)
# 为了减少过拟合,加入Dropout层
keep_prob = tf.placeholder(tf.float32)
fc1_dropout = tf.nn.dropout(fc1, keep_prob)
# 第六层:全连接层
fc2_weights = tf.get_variable("fc2_weights", [1024, class_num],
initializer=tf.truncated_normal_initializer(
stddev=0.1))
# 神经元节点数1024, 分类节点10
fc2_biases = tf.get_variable(
"fc2_biases", [class_num], initializer=tf.constant_initializer(0.1))
fc2 = tf.matmul(fc1_dropout, fc2_weights) + fc2_biases
# 第七层:输出层
# softmax
y_conv = tf.nn.softmax(fc2)
# 定义交叉熵损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),
reduction_indices=[1]))
# 选择优化器,并让优化器最小化损失函数/收敛, 反向传播
train_step = tf.train.AdamOptimizer(1e-5).minimize(cross_entropy)
# tf.argmax()返回的是某一维度上其数据最大所在的索引值,在这里即代表预测值和真实值
# 判断预测值y和真实值y_中最大数的索引是否一致,y的值为1-class_num概率
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
# 用平均值来统计测试准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 开始训练
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
acc_train_train = []
acc_train_test = []
batch_size = 64
epoch_train = 50001 # restricted by the hardware in my computer
print("Training steps=" + str(epoch_train))
for i in range(epoch_train):
if (i*batch_size % x_train.shape[0]) > ((i + 1)*batch_size %
x_train.shape[0]):
x_data_train = np.vstack(
(x_train[i*batch_size % x_train.shape[0]:],
x_train[:(i+1)*batch_size % x_train.shape[0]]))
y_data_train = np.vstack(
(y_train[i*batch_size % y_train.shape[0]:],
y_train[:(i+1)*batch_size % y_train.shape[0]]))
x_data_test = np.vstack(
(x_test[i*batch_size % x_test.shape[0]:],
x_test[:(i+1)*batch_size % x_test.shape[0]]))
y_data_test = np.vstack(
(y_test[i*batch_size % y_test.shape[0]:],
y_test[:(i+1)*batch_size % y_test.shape[0]]))
else:
x_data_train = x_train[
i*batch_size % x_train.shape[0]:
(i+1)*batch_size % x_train.shape[0]]
y_data_train = y_train[
i*batch_size % y_train.shape[0]:
(i+1)*batch_size % y_train.shape[0]]
x_data_test = x_test[
i*batch_size % x_test.shape[0]:
(i+1)*batch_size % x_test.shape[0]]
y_data_test = y_test[
i*batch_size % y_test.shape[0]:
(i+1)*batch_size % y_test.shape[0]]
if i % 640 == 0:
train_accuracy = accuracy.eval(
feed_dict={x: x_data_train, y_: y_data_train, keep_prob: 1.0})
test_accuracy = accuracy.eval(
feed_dict={x: x_data_test, y_: y_data_test, keep_prob: 1.0})
print("step {}, training accuracy={}, testing accuracy={}".format(
i, train_accuracy, test_accuracy))
acc_train_train.append(train_accuracy)
acc_train_test.append(test_accuracy)
train_step.run(feed_dict={
x: x_data_train, y_: y_data_train, keep_prob: 0.5})
print("saving model...")
save_path = saver.save(sess, "./my_model/model.ckpt")
print("save model:{0} Finished".format(save_path))
batch_size_test = 64
epoch_test = y_test.shape[0] // batch_size_test + 1
acc_test = 0
for i in range(epoch_test):
if (i*batch_size_test % x_test.shape[0]) > ((i + 1)*batch_size_test %
x_test.shape[0]):
x_data_test = np.vstack((
x_test[i*batch_size_test % x_train.shape[0]:],
x_test[:(i+1)*batch_size_test % x_test.shape[0]]))
y_data_test = np.vstack((
y_test[i*batch_size_test % y_test.shape[0]:],
y_test[:(i+1)*batch_size_test % y_test.shape[0]]))
else:
x_data_test = x_test[
i*batch_size_test % x_test.shape[0]:
(i+1)*batch_size_test % x_test.shape[0]]
y_data_test = y_test[
i*batch_size_test % y_test.shape[0]:
(i+1)*batch_size_test % y_test.shape[0]]
# plt.imshow(x_data_test[0].reshape(28, 28), cmap="gray")
# plt.show()
# Calculate batch loss and accuracy
c = accuracy.eval(feed_dict={
x: x_data_test, y_: y_data_test, keep_prob: 1.0})
acc_test += c / epoch_test
print("{}-th test accuracy={}".format(i, acc_test))
print("At last, test accuracy={}".format(acc_test))
print("Finish!")
return acc_train_train, acc_train_test, acc_test
def plot_acc(acc_train_train, acc_train_test, acc_test):
plt.figure(1)
p1, p2 = plt.plot(list(range(len(acc_train_train))),
acc_train_train, 'r>',
list(range(len(acc_train_test))),
acc_train_test, 'b-')
plt.legend(handles=[p1, p2], labels=["training_acc", "testing_acc"])
plt.title("Accuracies During Training")
plt.show()
def main():
# integers: 4679
# alphabets: 9796
# Chinese_letters: 3974
# training_set : testing_set == 4 : 1
train_lst = ['alphabets', 'integers', 'alphabets',
'Chinese_letters', 'integers']
acc_train_train, acc_train_test, acc_test = lenet(train_lst)
plot_acc(acc_train_train, acc_train_test, acc_test)
if __name__ == '__main__':
main()
Lenet车牌号字符识别+保存模型的更多相关文章
- vue实战 - 车牌号校验和银行校验
在看这篇文章之前,我建议大伙可以去把项目demo拉到本地看看.如果觉得写得不好,可以一起提提issues,一起维护.或者大伙有刚需,可以留言,后期会不断完善. 使用方法: git clone http ...
- iOS手机号,身份证,车牌号正则表达式
1.手机号判断,根据维基百科2016年6月修订的段号判断 是否是手机号 /** 手机号码 13[0-9],14[5|7|9],15[0-3],15[5-9],17[0|1|3|5|6|8],18[0- ...
- Android OpenCV集成摄像头图片动态识别车牌号
最近两天开发一个使用OpenCV集成的一个识别车牌号的项目,困难重重,总结一下相关经验,以及开发注意事项: 一.开发环境: Android Studio 个人版本 3.1.4 NDK下载:14b CM ...
- 基于TensorFlow的车牌号识别系统
简介 过去几周我一直在涉足深度学习领域,尤其是卷积神经网络模型.最近,谷歌围绕街景多位数字识别技术发布了一篇不错的paper.该文章描述了一个用于提取街景门牌号的单个端到端神经网络系统.然后,作者阐述 ...
- 【代码笔记】iOS-验证手机号,邮箱,车牌号是否合法
一,代码. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ...
- 按要求编写Java应用程序。 (1)创建一个叫做机动车的类: 属性:车牌号(String),车速(int),载重量(double) 功能:加速(车速自增)、减速(车速自减)、修改车牌号,查询车的载重量。 编写两个构造方法:一个没有形参,在方法中将车牌号设置“XX1234”,速 度设置为100,载重量设置为100;另一个能为对象的所有属性赋值; (2)创建主类: 在主类中创建两个机动车对象。 创建第
package com.hanqi.test; public class jidongche { private String chepaihao;//车牌号 private int speed;// ...
- Android中手机号、车牌号正则表达式
手机号 手机号的号段说明转载自:国内手机号码的正则表达式|蜗牛的积累 手机名称有GSM:表示只支持中国联通或者中国移动2G号段(130.131.132.134.135.136.137.138.139. ...
- 车牌号对应归属地及城市JSON带简码
车牌号对应归属地及城市JSON带简码 car_city.json [ { "code": "冀A", "city": "石家庄&q ...
- (1)创建一个叫做机动车的类: 属性:车牌号(String),车速(int),载重量(double) 功能:加速(车速自增)、减速(车速自减)、修改车牌号,查询车的载重量。 编写两个构造方法:一个没有形参,在方法中将车牌号设置“XX1234”,速 度设置为100,载重量设置为100;另一个能为对象的所有属性赋值; (2)创建主类: 在主类中创建两个机动车对象。
package a; public class Jidongche { private String chepaihao; private int chesu; private double zaiz ...
随机推荐
- Kubernetes 存储简介
存储分类结构图 半持久化存储 1.EmptyDir EmptyDir是一个空目录,生命周期和所属的 Pod 是完全一致的,EmptyDir的用处是,可以在同一 Pod 内的不同容器之间共享工作过程中产 ...
- Java int和integer有什么区别 (mybatis踩坑)
不要在实体类中使用int 我们都知道Integer是int的包装类,而int是基本数据类型.所以Integer类型的变量会初始化为null,int类型则会被初始化为0 . 所以在下面的动态拼接例子中: ...
- JavaScript与多线程的不解之缘!
前言 对于前端开发者来说,多线程是一个比较陌生的话题.因为JavaScript是单线程语言.也就是说,所有任务只能在一个线程上完成,一次只能做一件事.前面的任务没做完,后面的任务只能等着. UI渲染与 ...
- CF460C Present
写在前面 由于菜,写树状数组写挂了. 于是想出了一种不像线段树或树状数组+二分答案那样显然,但是依旧不难想,复杂度比较优秀,代码难度低的做法. 算法思路 外部二分答案,不多解释,稍证明一下单调性: 若 ...
- Java面试题及解析
面试题 解析 1 2 3 Join Sleep-线程睡眠 Yiedld-线程让步 sleep与yield方法区别 isAlive 终止线程 面试题 1.下列单词属于java访问修饰符的有(A,B, C ...
- dedecms织梦的安全问题解决办法
很多新手用户在使用织梦CMS程序过程中,难免会碰到挂马中毒现象,所以事先我们要对网站及服务器安全做好预防备份处理. 织梦作为国内第一大开源免费CMS程序,无疑是很多HACK研究的对象,在本身不安全的互 ...
- Flutter--Dart基础语法(四)异步
前言 Flutter 是 Google 开源的 UI 工具包,帮助开发者通过一套代码库高效构建多平台精美应用,Flutter 开源.免费,拥有宽松的开源协议,支持移动.Web.桌面和嵌入式平台. Fl ...
- 【noi 2.6_2000】&【poj 2127】 最长公共子上升序列 (DP+打印路径)
由于noi OJ上没有Special Judge,所以我是没有在这上面AC的.但是在POJ上A了. 题意如标题. 解法:f[i][j]表示a串前i个和b串前j个且包含b[j]的最长公共上升子序列长度 ...
- Codeforces Gym-102219 2019 ICPC Malaysia National J. Kitchen Plates (暴力,拓扑排序)
题意:给你5个\(A,B,C,D,E\)大小关系式,升序输出它们,如果所给的大小矛盾,输出\(impossible\). 题意:当时第一眼想到的就是连边然后排序,很明显是拓扑排序(然而我不会qwq,之 ...
- centos 7下设置.net core项目开机自启动
1.在etc/systemd/system下创建xxx.service文件 例如:vi /etc/systemd/system/ubif.service2.编辑 ubif.service内容如下: [ ...