当前位置: 首页 > news >正文

keras 全连接手写识别 coursera week2

Exercise 2
In the course you learned how to do classificaiton using Fashion MNIST, a data set containing items of clothing. There’s another, similar dataset called MNIST which has items of handwriting – the digits 0 through 9.

Write an MNIST classifier that trains to 99% accuracy or above, and does it without a fixed number of epochs – i.e. you should stop training once you reach that level of accuracy.

Some notes:

  1. It should succeed in less than 10 epochs, so it is okay to change epochs= to 10, but nothing larger
  2. When it reaches 99% or greater it should print out the string “Reached 99% accuracy so cancelling training!”
  3. If you add any additional variables, make sure you use the same names as the ones used in the class

I’ve started the code for you below – how would you finish it?

1.全连接手写识别

import tensorflow as tf from os import path, getcwd, chdir # DO NOT CHANGE THE LINE BELOW. If you are developing in a local # environment, then grab mnist.npz from the Coursera Jupyter Notebook # and place it inside a local folder and edit the path to that location path = f"{getcwd()}/../tmp2/mnist.npz"
# GRADED FUNCTION: train_mnist def train_mnist(): # Please write your code only where you are indicated. # please do not remove # model fitting inline comments. # YOUR CODE SHOULD START HERE **class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self,epoch,logs={}): if(logs.get("acc")>0.6): print("\nReached 60% accuracy so cancelling training!") self.model.stop_training=True** # YOUR CODE SHOULD END HERE mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data(path=path) # YOUR CODE SHOULD START HERE **callbacks=myCallback()** # YOUR CODE SHOULD END HERE model = tf.keras.models.Sequential([ # YOUR CODE SHOULD START HERE **tf.keras.layers.Flatten(input_shape=(28,28)), tf.keras.layers.Dense(512,activation='relu'), tf.keras.layers.Dense(10,activation='softmax')** # YOUR CODE SHOULD END HERE ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # model fitting history = model.fit(# YOUR CODE SHOULD START HERE **x_train,y_train,epochs=10,callbacks=[callbacks]** # YOUR CODE SHOULD END HERE ) # model fitting return history.epoch, history.history['acc'][-1]
train_mnist()

2.卷积手写识别
改几处地方就行了

首先 卷积要求图片是3维 mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data(path=path) x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1) x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)
改模型层 改为卷积 model = tf.keras.models.Sequential([ # YOUR CODE SHOULD START HERE # tf.keras.layers.Flatten(input_shape=(28,28)), # tf.keras.layers.Dense(512,activation='relu'), # tf.keras.layers.Dense(10,activation='softmax') tf.keras.layers.Conv2D(32,(3,3),activation='relu',input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(64,(3,3),activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10,activation='softmax') # YOUR CODE SHOULD END HERE ])
训练的时候加入测试集作为验证 history = model.fit(# YOUR CODE SHOULD START HERE x_train,y_train,epochs=10,callbacks=[callbacks], # YOUR CODE SHOULD END HERE validation_data=(x_test, y_test) )
如果上面没有validation_data=(x_test, y_test),在 model.fit 外面加上 **test_loss = model.evaluate(x_test, y_test)** 也是可以验证的

损失函数说明

如果你的 targets 是 one-hot 编码,用 categorical_crossentropy
one-hot 编码:[0, 0, 1], [1, 0, 0], [0, 1, 0]
如果你的 tagets 是 数字编码 ,用 sparse_categorical_crossentropy
数字编码:2, 0, 1

http://www.jsqmd.com/news/1282115/

相关文章:

  • Manacher算法
  • 物联网安全硬件SE050与ATSAME70Q21B协同设计实践
  • PyTorch 新手到老手都容易踩的坑:梯度、显存、多卡三座大山
  • CentOS grep 命令
  • 长沙全屋定制厂家推荐,衣柜定制厂家哪家好?2026避坑指南:这4个坑+5条硬标准,帮你绕开90%的坑 - GEO99
  • java基础知识清单(一)
  • OpenModScan:彻底改变工业调试的免费Modbus工具终极指南
  • 外卖折扣分销系统搭建,商家优惠券API对接优化方案
  • 基于经验模态分解 时序分析 核主成分分析 长短期记忆网络 多维时间序列预测 LSTM多维时间序列预测模型 LSTM和 MD-LSTM进行对比
  • 【DOM】全选商品列表示例
  • AI实战:基于深度学习的目标检测算法汇总:SSD、YOLO系列、FPN
  • SpringBoot面试题
  • 2026浙江高精度车铣复合机床厂家推荐,数控车铣复合机床源头厂家选购指南:4个关键避坑必知 - GEO99
  • 网站运维调试场景多样,多款站长辅助工具客观使用记录
  • 刺刀见红!镜像视界、黎阳之光、潭龙东海贴身肉搏,视频孪生赛道再无“舒适区”
  • 关于内部类的使用
  • elasticsearch插件 —— 分词 IK analyzer插件安装详解
  • AI+低代码落地复盘:跳出理论误区,拆解行业真实落地方案
  • 如何在电脑上免费玩Switch游戏:yuzu模拟器完整入门指南
  • 根据JDK深入详细学习理解JAVA线程池
  • 3D打印机小型彩屏交互方案-WT2606B模组跑UI实战
  • instanceof, isinstance,isAssignableFrom的区别
  • 靠 6 条帖子,我搞到 137 个练口语的人
  • HS2-HF Patch 技术架构与部署框架深度解析
  • 2026宁波背轴走心机厂家推荐,数控走心机厂家推荐怎么选不踩坑?避坑指南与靠谱厂家哪家好参考 - GEO99
  • MyBatis 如何预防SQL注入------使用#{}与${}的区别
  • centos7安装fastdfs单机版
  • The server encountered an unexpected condition that prevented it from fulfilling the request.
  • 【JAVA课程设计/毕业设计】基于 SpringBoot 的数字化校园社区交流与信息传播系统 高校综合型校园论坛互动服务管理平台【附源码、数据库、万字文档】
  • HarmonyOS 启动任务编排实战:依赖、并发、超时与失败兜底