当前位置:网站首页>10.CNN应用于手写数字识别
10.CNN应用于手写数字识别
2022-07-07 23:11:00 【booze-J】
代码运行平台为jupyter-notebook,文章中的代码块,也是按照jupyter-notebook中的划分顺序进行书写的,运行文章代码,直接分单元粘入到jupyter-notebook即可。整体代码给出的注释还是挺简单明了的。
1.导入第三方库
import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense,Dropout,Convolution2D,MaxPooling2D,Flatten
from tensorflow.keras.optimizers import Adam
2.加载数据及数据预处理
# 载入数据
(x_train,y_train),(x_test,y_test) = mnist.load_data()
# (60000, 28, 28)
print("x_shape:\n",x_train.shape)
# (60000,) 还未进行one-hot编码 需要后面自己操作
print("y_shape:\n",y_train.shape)
# (60000, 28, 28) -> (60000,28,28,1)=(图片数目,图片高度,图片宽度,图片的通道数) reshape()中参数填入-1的话可以自动计算出参数结果 除以255.0是为了归一化
# 归一化很关键哈,可以大大减少计算量
x_train = x_train.reshape(-1,28,28,1)/255.0
x_test = x_test.reshape(-1,28,28,1)/255.0
# 换one hot格式
y_train = np_utils.to_categorical(y_train,num_classes=10)
y_test = np_utils.to_categorical(y_test,num_classes=10)
3.训练模型
# 定义顺序模型
model = Sequential()
# 第一个卷积层 注意第一层要写输入图片的大小 后面的层可以忽略
# input_shape 输入平面
# filters 卷积核/滤波器个数
# kernel_size 卷积窗口大小
# strides 步长
# padding padding方式 same/valid
# activation 激活函数
model.add(Convolution2D(
input_shape=(28,28,1),
filters=32,
kernel_size=5,
strides=1,
padding="same",
activation="relu"
))
# 第一个池化层
model.add(MaxPooling2D(
pool_size=2,
strides=2,
padding="same"
))
# 第二个池化层
model.add(Convolution2D(filters=64,kernel_size=5,strides=1,padding="same",activation="relu"))
# 第二个池化层
model.add(MaxPooling2D(pool_size=2,strides=2,padding="same"))
# 把第二个池化层的输出扁平化为1维
model.add(Flatten())
# 第一个全连接层
model.add(Dense(units=1024,activation="relu"))
# Dropout 随机选用50%神经元进行训练
model.add(Dropout(0.5))
# 第二个全连接层
model.add(Dense(units=10,activation="softmax"))
# 定义优化器 设置学习率为1e-4
adam = Adam(lr=1e-4)
# 定义优化器,loss function,训练过程中计算准确率
model.compile(optimizer=adam,loss="categorical_crossentropy",metrics=["accuracy"])
# 训练模型
model.fit(x_train,y_train,batch_size=64,epochs=10)
# 评估模型
loss,accuracy=model.evaluate(x_test,y_test)
print("test loss:",loss)
print("test accuracy:",accuracy)
代码运行结果:
代码中需要注意的一些点,在代码注释中也给出了解释和提醒。
注意
- 搭建神经网络的第一层要写输入图片的大小 后面的层可以忽略
边栏推荐
- 1293_ Implementation analysis of xtask resumeall() interface in FreeRTOS
- Kubernetes Static Pod (静态Pod)
- NVIDIA Jetson test installation yolox process record
- 股票开户免费办理佣金最低的券商,手机上开户安全吗
- RPA cloud computer, let RPA out of the box with unlimited computing power?
- Reentrantlock fair lock source code Chapter 0
- 手机上炒股安全么?
- [Yugong series] go teaching course 006 in July 2022 - automatic derivation of types and input and output
- AI遮天传 ML-回归分析入门
- 图像数据预处理
猜你喜欢

SDNU_ACM_ICPC_2022_Summer_Practice(1~2)

【obs】官方是配置USE_GPU_PRIORITY 效果为TRUE的

【愚公系列】2022年7月 Go教学课程 006-自动推导类型和输入输出

Fofa attack and defense challenge record

Reentrantlock fair lock source code Chapter 0

What if the testing process is not perfect and the development is not active?

华为交换机S5735S-L24T4S-QA2无法telnet远程访问

DNS series (I): why does the updated DNS record not take effect?

Invalid V-for traversal element style

他们齐聚 2022 ECUG Con,只为「中国技术力量」
随机推荐
[note] common combined filter circuit
What if the testing process is not perfect and the development is not active?
赞!idea 如何单窗口打开多个项目?
Implementation of adjacency table of SQLite database storage directory structure 2-construction of directory tree
大二级分类产品页权重低,不收录怎么办?
New library online | information data of Chinese journalists
Basic mode of service mesh
[C language] objective questions - knowledge points
Interface test advanced interface script use - apipost (pre / post execution script)
什么是负载均衡?DNS如何实现负载均衡?
玩轉Sonar
股票开户免费办理佣金最低的券商,手机上开户安全吗
攻防演练中沙盘推演的4个阶段
SDNU_ACM_ICPC_2022_Summer_Practice(1~2)
Deep dive kotlin collaboration (the end of 23): sharedflow and stateflow
13.模型的保存和载入
C # generics and performance comparison
QT adds resource files, adds icons for qaction, establishes signal slot functions, and implements
[go record] start go language from scratch -- make an oscilloscope with go language (I) go language foundation
Handwriting a simulated reentrantlock