深度学习笔记-使用tensorflow实现数字识别

使用tensorflow实现数字识别

1.由于数据集为灰度图,这里实现的仅是进行简单的扁平化处理
2.实验所用数据集为tensorflow自带的数据集,只需有网即可自动下载
3.完整代码以及注释

import matplotlib.pyplot as plt
import tensorflow as tf
import os
import numpy as np
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train, x_test =x_train/255.0, x_test/255.0 #图像归一化处理

"""
1.调用网格结构,往里面搭建神经网络
2.因为图片是一个二维矩阵,使我们进行前向传播难以进行,所有使用Flatten对图片进行扁平化处理,得到由图片展开的一维向量
3.设置隐藏层,使用relu激活函数,relu激活函数的优点是在大于0的定义域内不存在由于链式法则而导致的梯度消失问题
4.在数字输出中,存在10种输出,所以将输出设置为10,使用softmax激活函数将输出区间压缩在0-1内,符合概率分布(因为我们输出的是一个图片对应为每个数字的概率

"""
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
])

"""
设置优化器和损失函数
"""

model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics='sparse_categorical_accuracy')


"""
保存模型
"""
checkpoint_save_path = "./checkpoint/mnist.ckpt"

if os.path.exists(checkpoint_save_path+'.index'):
    print('-------------load data------------')
    model.load_weights(checkpoint_save_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,save_weights_only=True,save_best_only=True)

"""
开始训练
"""
history =model.fit(x_train,y_train,epochs=5,validation_data=(x_test,y_test),validation_freq=1,callbacks=[cp_callback])

model.summary()

#参数提取
print(model.trainable_variables)
file = open('./weigths.txt','w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()

#可视化训练情况
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']

loss = history.history['loss']

val_loss = history.history['val_loss']

plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.title('Training and Validation Accuracy')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()

#应用测试,测试test[0]
print("数字为:")
print(np.argmax(model.predict(x_test[0].reshape(1,28,28,1))))

实验效果:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值