位置: IT常识 - 正文

【Tensorflow深度学习】实现手写字体识别、预测实战(附源码和数据集 超详细)(tensorflow gan)

编辑:rootadmin
【Tensorflow深度学习】实现手写字体识别、预测实战(附源码和数据集 超详细)

推荐整理分享【Tensorflow深度学习】实现手写字体识别、预测实战(附源码和数据集 超详细)(tensorflow gan),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:tensorflowgpu,tensorflow deeplab,tensorflow v1,tensorflow dlib,tensorflow deeplab,tensorflow deeplab,tensorflow deepfm,tensorflow 1,内容如对您有帮助,希望把文章链接给更多的朋友!

需要源码和数据集请点赞关注收藏后评论区留言私信~~~

一、数据集简介

下面用到的数据集基于IAM数据集的英文手写字体自动识别应用,IAM数据库主要包含手写的英文文本,可用于训练和测试手写文本识别以及执行作者的识别和验证,该数据库在ICDAR1999首次发布,并据此开发了基于隐马尔可夫模型的手写句子识别系统,并于ICPR2000发布,IAM包含不受约束的手写文本,以300dpi的分辨率扫描并保存为具有256级灰度的PNG图像,IAM手写数据库目前最新的版本为3.0,其主要结构如下

约700位作家贡献笔迹样本

超过1500页扫描文本

约6000个独立标记的句子

超过一万行独立标记的文本

超过十万个独立标记的空间

展示如下 有许多张手写照片 

 

 

二、实现步骤 1:数据清洗

删除文件中备注说明以及错误结果,统计正确笔迹图形的数量,最后将整理后的数据进行随机无序化处理

2:样本分类

接下来对数据进行分类 按照8:1:1的比例将样本数据集分为三类数据集,分别是训练数据集 验证数据集和测试数据集,针对训练数据集进行训练可以获得模型,而测试数据集主要用于测试模型的有效性

3:实现字符和数字映射

利用Tensorflow库的Keras包的StringLookup函数实现从字符到数字的映射 主要参数说明如下

【Tensorflow深度学习】实现手写字体识别、预测实战(附源码和数据集 超详细)(tensorflow gan)

max_tokens:单词大小的最大值

num_oov_indices:out of vocabulary的大小

mask_token:表示屏蔽输入的大小

oov_token:仅当invert为True时使用 OOV索引的返回值 默认为UNK

4:进行卷积变化 

通过Conv2D函数实现二维卷积变换 主要参数说明如下

filters:整数值 代表输出空间的维度

kernel_size:一个整数或元组列表 指定卷积窗口的高度和宽度

strides:一个整数或元组列表 指定卷积沿高度和宽度的步幅

padding:输出图像的填充方式

activation:激活函数

三、效果展示 

读取部分手写样本的真实文本信息如下

训练结束后 得到训练模型 导入测试手写文本数据 进行手写笔迹预测 部分结果如下

四、结果总结 

观察预测结果可知,基于均值池化以及训练过程预警极值,大部分的英文字符能够得到准确的预测判定,训练的精度持续得到改善,损失值控制在比较合理的区间内,没有发生预测准确度连续多次无法改进的场景,模型稳定性较好

五、代码

部分代码如下 需要全部代码请点赞关注收藏后评论区留言私信~~~

from tensorflow.keras.layers.experimental.preprocessing import StringLookupfrom tensorflow import kerasimport matplotlib.pyplot as pltimport tensorflow as tfimport numpy as npimport osplt.rcParams['font.family'] = ['Microsoft YaHei']np.random.seed(0)tf.random.set_seed(0)# ## 切分数据# In[ ]:corpus_read = open("data/words.txt", "r").readlines()corpus = []length_corpus=0for word in corpus_read: if lit(" ")[1] == "ok"): corpus.append(word)np.random.shuffle(corpus)length_corpus=len(corpus)print(length_corpus)corpus[400:405]# 划分数据,按照 80:10:10 比例分配给训练:有效:测试 数据# In[ ]:train_flag = int(0.8 * len(corpus))test_flag = int(0.9 * len(corpus))train_data = corpus[:train_flag]validation_data = corpus[train_flag:test_flag]test_data = corpus[test_flag:]train_data_len=len(train_data)validation_data_len=len(validation_data)test_data_len=len(test_data)print("训练样本大小:", train_data_len)print("验证样本大小:", validation_data_len)print("测试样本大小:",test_data_len )# In[ ]:image_direct = "data\images"def retrieve_image_info(data): image_location = [] sample = [] for (i, corpus_row) in enumerate(data): corpus_strip = corpus_row.strip() corpus_strip = corpus_strip.split(" ") image_name = corpus_strip[0] leve1 = image_name.split("-")[0] leve2 = image_name.split("-")[1] image_location_detail = os.path.join( image_direct, leve1, leve1 + "-" + leve2, image_name + ".png" ) if os.path.getsize(image_location_detail) >0 : image_location.append(image_location_detail) sample.append(corpus_row.split("\n")[0]) print("手写图像路径:",image_location[0],"手写文本信息:",sample[0]) return image_location, sampletrain_image, train_tag = retrieve_image_info(train_data)validation_image, validation_tag = retrieve_image_info(validation_data)test_image, test_tag = retrieve_image_info(test_data)# In[ ]:# 查找训练数据词汇最大长度train_tag_extract = []vocab = set()max_len = 0for tag in train_tag: tag = tag.split(" ")[-1].strip() for i in tag: vocab.add(i) max_len = max(max_len, len(tag)) train_tag_extract.append(tag)print("最大长度: ", max_len)print("单词大小: ", len(vocab))print("单词内容: ", vocab)train_tag_extract[40:45]# In[ ]:print(train_tag[50:54])print(validation_tag[10:14])print(test_tag[80:84])def extract_tag_info(tags): extract_tag = [] for tag in tags: tag = tag.split(" ")[-1].strip() extract_tag.append(tag) return extract_tagtrain_tag_tune = extract_tag_info(train_tag)validation_tag_tune = extract_tag_info(validation_tag)test_tag_tune = extract_tag_info(test_tag)print(train_tag_tune[50:54])print(validation_tag_tune[10:14])print(test_tag_tune[80:84])# In[ ]:AUTOTUNE = tf.data.AUTOTUNE# 映射单词到数字string_to_no = StringLookup(vocabulary=list(vocab), invert=False)# 映射数字到单词no_map_string = StringLookup( vocabulary=string_to_no.get_vocabulary(), invert=True)# In[ ]:def distortion_free_resize(image, img_size): w, h = img_size image = tf.image.resize(image, size=(h, w), preserve_aspect_ratio=True, antialias=False, name=None) # 计算填充区域大小 pad_height = h - tf.shape(image)[0] pad_width = w - tf.shape(image)[1] if pad_height % 2 != 0: height = pad_height // 2 pad_height_top = height + 1 pad_height_bottom = height else: pad_height_top = pad_height_bottom = pad_height // 2 if pad_width % 2 != 0: width = pad_width // 2 pad_width_left = width + 1 pad_width_right = width else: pad_width_left = pad_width_right = pad_width // 2 image = tf.pad( image, paddings=[ [pad_height_top, pad_height_bottom], [pad_width_left, pad_width_right], [0, 0], ], ) image = tf.transpose(image, perm=[1, 0, 2]) image = tf.image.flip_left_right(image) return image# In[ ]:batch_size = 64padding_token = 99image_width = 128image_height = 32def preprocess_image(image_path, img_size=(image_width, image_height)): image = tf.io.read_file(image_path) image = tf.image.decode_png(image, 1) image = distortion_free_resize(image, img_size) image = tf.cast(image, tf.float32) / 255.0 return imagedef vectorize_tag(tag): tag = string_to_no(tf.strings.unicode_split(tag, input_encoding="UTF-8")) length = tf.shape(tag)[0] pad_amount = max_len - length tag = tf.pad(tag, paddings=[[0, pad_amount]], constant_values=padding_token) return tagdef process_images_tags(image_path, tag): image = preprocess_image(image_path) tag = vectorize_tag(tag) return {"image": image, "tag": tag}def prepare_dataset(image_paths, tags): dataset = tf.data.Dataset.from_tensor_slices((image_paths, tags)).map( process_images_tags, num_parallel_calls=AUTOTUNE ) return dataset.batch(batch_size).cache().prefetch(AUTOTUNE)# In[ ]:train_final = prepare_dataset(train_image, train_tag_extract )validation_final = prepare_dataset(validation_image, validation_tag_tune )test_final = prepare_dataset(test_image, test_tag_tune )print(train_final.take(1))print(train_final)# In[ ]:plt.rcParams['font.family'] = ['Microsoft YaHei']for data in train_final.take(1): images, tags = data["image"], data["tag"] _, ax = plt.subplots(4, 4, figsize=(15, 8)) for i in range(16): img = images[i] img = tf.image.flip_left_right(img) img = tf.transpose(img, perm=[1, 0, 2]) img = (img * 255.0).numpy().clip(0, 255).astype(np.uint8) img = img[:, :, 0] tag = tags[i] indices = tf.gather(tag, tf.where(tf.math.not_equal(tag, padding_token))) tag = tf.strings.reduce_join(no_map_string(indices)) tag = tag.numpy().decode("utf-8") ax[i // 4, i % 4].imshow(img) ax[i // 4, i % 4].set_title(u"真实文本:%s"%tag) ax[i // 4, i % 4].axis("on")plt.show()# In[ ]:class CTCLoss(keras.layers.Layer): def call(self, y_true, y_pred): batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64") input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64") tag_length = tf.cast(tf.shape(y_true)[1], dtype="int64") input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64") tag_length = tag_length * tf.ones(shape=(batch_len, 1), dtype="int64") loss = keras.backend.ctc_batch_cost(y_true, y_pred, input_length, tag_length) self.add_loss(loss) return lossdef generate_model(): # Inputs to the model input_img = keras.Input(shape=(image_width, image_height, 1), name="image") tags = keras.layers.Input(name="tag", shape=(None,)) # First conv block. t = keras.layers.Conv2D( filters=32, kernel_size=(3, 3), activation="relu", kernel_initializer="he_normal", padding="same", name="ConvolutionLayer1")(input_img) t = keras.layers.AveragePooling2D((2, 2), name="AveragePooling_one")(t) # Second conv block. t = keras.layers.Conv2D( filters=64, kernel_size=(3, 3), activation="relu", kernel_initializer="he_normal", padding="same", name="ConvolutionLayer2")(t) t = keras.layers.AveragePooling2D((2, 2), name="AveragePooling_two")(t) #re_shape = (t,[(image_width // 4), -1]) #tf.dtypes.cast(t, tf.int32) re_shape = ((image_width // 4), (image_height // 4) * 64) t = keras.layers.Reshape(target_shape=re_shape, name="reshape")(t) t = keras.layers.Dense(64, activation="relu", name="denseone",use_bias=False, kernel_initializer='glorot_uniform', bias_initializer='zeros')(t) t = keras.layers.Dropout(0.4)(t) # RNNs. t = keras.layers.Bidirectional( keras.layers.LSTM(128, return_sequences=True, dropout=0.4) )(t) t = keras.layers.Bidirectional( keras.layers.LSTM(64, return_sequences=True, dropout=0.4) )(t) t = keras.layers.Dense( len(string_to_no.get_vocabulary())+2, activation="softmax", name="densetwo" )(t) # Add CTC layer for calculating CTC loss at each step. output = CTCLoss(name="ctc_loss")(tags, t) # Define the model. model = keras.models.Model( inputs=[input_img, tags], outputs=output, name="handwriting" ) # Optimizer. # Compile the model and return. model.compile(optimizer=keras.optimizers.Adam()) return model# Get the model.model = generate_model()model.summary()# In[ ]:validation_images = []validation_tags = []for batch in validation_final: validation_images.append(batch["image"]) validation_tags.append(batch["tag"])# In[ ]:#epochs = 20 model = generate_model()prediction_model = keras.models.Model( model.get_layer(name="image").input, model.get_layer(name="densetwo").output)#edit_distance_callback = EarlyStoppingAtLoss()epochs = 60early_stopping_patience = 10# Add early stoppingearly_stopping = keras.callbacks.EarlyStopping( monitor="val_loss", patience=early_stopping_patience, restore_best_weights=True)# Train the model.history = model.fit( train_final, validation_data=validation_final, epochs=60,callbacks=[early_stopping])# ## Inference# In[ ]:plt.rcParams['font.family'] = ['Microsoft YaHei']# A utility function to decode the output of the network.def handwriting_prediction(pred): input_len = np.ones(pred.shape[0]) * pred.shape[1] = [] for j in results: j = tf.gather(j, tf.where(tf.math.not_equal(j, -1))) j = tf.strings.reduce_join(no_map_string(j)).numpy().decode("utf-8") output_text.append(j) return output_text# Let's check results on some test samples.for test in test_final.take(1): test_images = test["image"] _, ax = plt.subplots(4, 4, figsize=(15, 8)) predit = prediction_model.predict(test_images) predit_text = handwriting_prediction(predit) for k in range(16): img = test_images[k] img = tf.image.flip_left_right(img) img = tf.transpose(img, perm=[1, 0, 2]) img = (img * 255.0).numpy().clip(0, 255).astype(np.uint8) img = img[:, :, 0] title = f"预测结果: {predit_text[k]}"# In[ ]:

创作不易 觉得有帮助请点赞关注收藏~~~

本文链接地址:https://www.jiuchutong.com/zhishi/299085.html 转载请保留说明!

上一篇:无人驾驶学习笔记-LeGO-LOAM 算法源码学习总结(无人驾驶基础知识)

下一篇:开源代码 | FMCW-MIMO雷达仿真MATLAB(开源代码网站github)

  • 微信营销推广方法12种(微信营销推广方法和手段有哪些)

    微信营销推广方法12种(微信营销推广方法和手段有哪些)

  • 企业怎样利用微信来树立自己的个人品牌(公司如何用好企业微信)

    企业怎样利用微信来树立自己的个人品牌(公司如何用好企业微信)

  • 软文写作及网络营销推广重要环节(1.网络软文的写作要求主要有哪些?)

    软文写作及网络营销推广重要环节(1.网络软文的写作要求主要有哪些?)

  • 华为mate30和华为p30的区别(华为mate30和华为nova10哪个好)

    华为mate30和华为p30的区别(华为mate30和华为nova10哪个好)

  • 网易云私信红色感叹号(网易云私信红色圆箭头怎么弄)

    网易云私信红色感叹号(网易云私信红色圆箭头怎么弄)

  • b站直播中心在哪(b站直播中心在哪电脑)

    b站直播中心在哪(b站直播中心在哪电脑)

  • 临时文件可以清理吗(临时文件清除任务可以禁用吗)

    临时文件可以清理吗(临时文件清除任务可以禁用吗)

  • airpods通透模式和关闭区别

    airpods通透模式和关闭区别

  • 72伏充电器能充60伏吗(72伏充电器能充68伏的电动车不)

    72伏充电器能充60伏吗(72伏充电器能充68伏的电动车不)

  • 计算机病毒可能破坏硬件吗(计算机病毒可能造成的危害有哪些()? A.破坏数据)

    计算机病毒可能破坏硬件吗(计算机病毒可能造成的危害有哪些()? A.破坏数据)

  • ftn-b19是什么型号(ftn—b19价格)

    ftn-b19是什么型号(ftn—b19价格)

  • 自己的淘宝密码在哪里能知道?(淘宝记住密码)

    自己的淘宝密码在哪里能知道?(淘宝记住密码)

  • qq可以设置自动上下线吗(qq可以设置自动拒绝qq电话吗)

    qq可以设置自动上下线吗(qq可以设置自动拒绝qq电话吗)

  • 微信群只有群主才能@所有人吗(微信群只有群主才能拉人吗)

    微信群只有群主才能@所有人吗(微信群只有群主才能拉人吗)

  • 为什么手机取卡的地方不弹出来(为什么手机取卡的地方拔不出来)

    为什么手机取卡的地方不弹出来(为什么手机取卡的地方拔不出来)

  • 华为p30和荣耀20pro拍照对比(华为p30和荣耀20pro对比)

    华为p30和荣耀20pro拍照对比(华为p30和荣耀20pro对比)

  • win10自带杀毒软件叫啥(win10自带杀毒软件)

    win10自带杀毒软件叫啥(win10自带杀毒软件)

  • 拼多多怎么注册开店(拼多多怎么注册自己的网店)

    拼多多怎么注册开店(拼多多怎么注册自己的网店)

  • icould内存满了怎么办(icloud储存空间满了怎么办)

    icould内存满了怎么办(icloud储存空间满了怎么办)

  • iwatch3能测血压么(iwatch3能测血压吗)

    iwatch3能测血压么(iwatch3能测血压吗)

  • 不让看朋友圈显示什么(不让看朋友圈显示什么样子)

    不让看朋友圈显示什么(不让看朋友圈显示什么样子)

  • vivoz3x返回键在哪里(vivoz3i手机怎么调出返回键)

    vivoz3x返回键在哪里(vivoz3i手机怎么调出返回键)

  • 苹果手机隐藏软件怎么弄出来(苹果手机隐藏软件怎么显示出来)

    苹果手机隐藏软件怎么弄出来(苹果手机隐藏软件怎么显示出来)

  • slog2和slog3的区别(slog2和slog3什么场景)

    slog2和slog3的区别(slog2和slog3什么场景)

  • bln-al40是什么型号(bln-al40价格)

    bln-al40是什么型号(bln-al40价格)

  • 电脑右下角弹窗广告无法关闭(电脑右下角弹窗广告怎么彻底清除)

    电脑右下角弹窗广告无法关闭(电脑右下角弹窗广告怎么彻底清除)

  • 一般纳税人增值税税率
  • 商业写字楼
  • 汇算清缴需补税
  • 汽车运输企业付给车主的运费算成本吗
  • 小规模超过10万是全额交税吗
  • 会计信息不采集,证书会失效吗
  • 企业内部转账应注意什么
  • 个税按照计提申报怎么调整
  • 有什么法规依据法律规定
  • 员工全额承担社保账务怎么做?
  • 库存商品赠送给客户要开票吗
  • 复印的原始凭证可以作为记账依据吗
  • 刚成立的外贸公司做小规模纳税人好不好
  • 实收资本没到账,一直挂其他应收款,有啥影响
  • 个体户能不能去注销
  • 异地工程要预缴环境税款吗
  • 增值税普通发票和普通发票的区别怎么交税
  • 股权变更印花税双方都要交吗
  • 上个月开的增值税发票这个月可以作废吗
  • 药企会计租金进项税不能抵扣
  • 电脑变成代码打不开怎么办
  • 建筑业开票内容
  • 转口贸易是否缴增值税
  • 预收培训费怎么确认增值税
  • 货物运输业的增值税税率
  • 孕妇能吃桂圆吗有什么好处
  • win10蓝牙怎么开ldac
  • 公司注册小规模有什么要求
  • 农产品进项税额转出会计分录
  • 浏览器下载量排名第一的是
  • vue app打包
  • 利用的拼音
  • php生成二维码海报
  • php 跨域
  • 如何用java写接口
  • 日用品可以开专票吗
  • js添加方法
  • laravel分页
  • 如何计算公司需增加的营运资金
  • pyqt5 pycharm
  • css中字符间距怎么设置
  • 串口发送字节数据的数据格式是什么
  • 启动mysql的语句
  • 材料短缺计入成本吗
  • 零申报一定要有员工吗
  • 税务登记是需要原件还是复印件
  • sqlserver2008r2数据库导出教程
  • sqlserver2008数据库可疑
  • 如何确认固定资产的减值
  • 以前年度多缴纳房产税,可以递延次年度使用么
  • 固定资产接受捐赠的条件
  • 暂估和冲暂估分录
  • 其他债权投资的公允价值变动计入什么科目
  • 什么是全面预算控制?全面预算控制的作用有哪些?
  • 电影院租金一般多少为合理
  • 营改增行业销售额的确定
  • 一般哪些收据可以抵扣
  • 应税劳务会计分录
  • 普票不开明细可以不
  • 新成立公司年初余额
  • 什么是来料加工和进料加工
  • 以管理员的身份运行是什么意思win10
  • linux系统的
  • 虚拟内存扩大有什么好处
  • windows8.1关机在哪
  • win7如何打开命令窗口
  • win7 设置
  • 安卓百分百
  • Android 执行油猴脚本
  • ercp后淀粉酶为什么升高
  • http状态码一览表
  • bat脚本如何运行
  • linux删除文件语句
  • android基础入门教程
  • ListView中EditText焦点问题
  • jquery 动态添加列表元素
  • 用jquery实现全选全不选反选
  • 如何用python编写一个程序
  • 江苏省国税电子税务局官网发票验
  • 如何下载建设工程消防验收备案表格下载
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设