深度学习入门-05 基于keras实现手写图像识别

1.引入库

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
# 构建模型库
from tensorflow.keras.models import Sequential
# 相关的网络层
from tensorflow.keras.layers import Dense,Dropout,Activation,BatchNormalization
# 导入辅助工具包
from tensorflow.keras import utils
# 正则化
from tensorflow.keras import regularizers
# 数据集
from tensorflow.keras.datasets import mnist

2.加载数据

(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train)
# 显示数据
plt.figure()
# 显示x_train中索引为1的图片
plt.imshow(x_train[1], cmap='gray')
print(y_train[1])

3.数据处理

# 数据维度的调整
x_train = x_train.reshape(60000,784)
x_test = x_test.reshape(10000,784)
# 数据类型调整
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# 归一化
x_train = x_train/255
x_test = x_test/255
# 将目标值转换成热编码的形式  分成10类 0-9
y_train = utils.to_categorical(y_train, 10)
print(y_train)
y_test = utils.to_categorical(y_test, 10)
print(y_test)

4.构建网络

# 搭建神经网络模型
model = Sequential()
# 全连接层:2个隐层,一个输出层
# 第一个隐层: 512个神经元
model.add(Dense(512,activation='relu',input_shape=(784,)))
model.add(BatchNormalization())
model.add(Dropout(0.2))
# 第二个隐层 同时加入批标准化和DropOut防止过拟合
model.add(Dense(512,activation='relu',kernel_regularizer=regularizers.l2(0.01)))
model.add(BatchNormalization())
model.add(Dropout(0.2))
# 输出层
model.add(Dense(10,activation='softmax'))
# 显示网络框架
model.summary()
## 或者以下方式显示网络框架
# utils.plot_model(model)

5.模型编译

# 损失函数,优化器,评价指标
model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer='Adam',
               metrics = tf.keras.metrics.Accuracy())

6.模型训练

# 使用fit,指定训练集,epochs,batch_size,val,verbose
history = model.fit(x_train, y_train,epochs=4,batch_size=128,validation_data=(x_test,y_test),verbose=1)

7.显示训练结果

print(history.history)
# 绘制图像
# 损失函数
plt.figure()
plt.plot(history.history['loss'], label='train')
plt.plot(history.history['val_loss'],label='val')
plt.legend()
plt.grid()
# 准确率
plt.figure()
plt.plot(history.history['accuracy'], label='train')
plt.plot(history.history['val_accuracy'],label='val')
plt.legend()
plt.grid()

8.模型测试

score = model.evaluate(x_test, y_test, verbose=1)

9.模型保存

model.save('model_mnist.h5')
# 模型加载
# 加载
loadmodel = tf.keras.models.load_model('model_mnist.h5')
loadmodel.evaluate(x_test, y_test, verbose=1)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不止三岁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值