【TensorFlow2.0】训练LeNet进行Mnist手写体数字识别并测试自己的图片

1、load_model_test.py

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

mnist=tf.keras.datasets.mnist

(x_train,y_train),(x_test,y_test)=mnist.load_data()

# print(x_train.shape,y_train.shape)
# print(x_test.shape,y_test.shape)

print(x_train.shape,x_test.shape)
x_train= np.pad(x_train,((0,0),(2,2),(2,2)),'constant',constant_values=0) #28*28-》32*32
x_test= np.pad(x_test,((0,0),(2,2),(2,2)),'constant',constant_values=0) #28*28-》32*32
print(x_train.shape,x_test.shape)

#数据集格式转换
x_train=x_train.astype('float32')
x_train=x_train.astype('float32')

x_train=x_train/255#归一化
x_test=x_test/255#归一化


x_train=x_train.reshape(x_train.shape[0],32,32,1)
x_test=x_test.reshape(x_test.shape[0],32,32,1)
print(x_train.shape,x_test.shape)

#模型实例化
model=tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters=6,kernel_size=(5,5),padding='valid',activation=tf.nn.relu,input_shape=(32,32,1)),
    tf.keras.layers.AveragePooling2D(pool_size=(2,2),strides=(2,2),padding='same'),
    tf.keras.layers.Conv2D(filters=16,kernel_size=(5,5),padding='valid',activation=tf.nn.relu,input_shape=(32,32,1)),
    tf.keras.layers.AveragePooling2D(pool_size=(2,2),strides=(2,2),padding='same'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(units=120,activation=tf.nn.relu),
    tf.keras.layers.Dense(units=84,activation=tf.nn.relu),
    tf.keras.layers.Dense(units=10,activation=tf.nn.softmax),
    ])
model.summary()


#第二部分 模型训练
num_epochs=1#训练次数
batch_size=64#每个批次喂多少张图片
lr=0.001#学习率

#优化器
adam_optimizer=tf.keras.optimizers.Adam(lr)

model.compile(
    optimizer=adam_optimizer,
    loss=tf.keras.losses.sparse_categorical_crossentropy,
    metrics=['accuracy']
)

import datetime
start_time=datetime.datetime.now()

model.fit(
    x=x_train,
    y=y_train,
    batch_size=batch_size,
    epochs=num_epochs
)
end_time=datetime.datetime.now()
time_cost=end_time-start_time
print('time_cost: ',time_cost)

#保存模型
# model.save_weights('./check_points/my_check_point')
model.save('./model/leNet_model.h5')
print(model.evaluate(x_test,y_test))



image_index=0

# 预测
pred=model.predict(x_test[image_index].reshape(1,32,32,1))
print(pred.argmax())

# 显示
plt.imshow(x_test[image_index].reshape(32,32))
plt.show()

2、mnist_model_load.py

import tensorflow as tf
mnist=tf.keras.datasets.mnist
import matplotlib.pyplot as plt
import matplotlib as m
import numpy as np
import cv2

# np.set_printoptions(threshold=np.inf)

#加载模型
model=tf.keras.models.load_model('./model/leNet_model.h5')

#图片预处理
img=cv2.imread('7.jpg')
print(img.shape)
plt.imshow(img)
plt.show()

#灰度图
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
print(img.shape)
plt.imshow(img,cmap='Greys')
plt.show()

#取反
img=cv2.bitwise_not(img)
plt.imshow(img,cmap='Greys')
plt.show()

print('二值化前:',img.shape)
print('二值化前:',img)
#纯黑 纯白 二值化
img[img<=100]=0
img[img>=140]=255
plt.imshow(img,cmap='Greys')
plt.show()
print('二值化后:',img.shape)
print('二值化后:',img)

#尺寸
img=cv2.resize(img,(32,32))
print('尺寸:',img.shape)
print('尺寸',img)

#归一化
img=img/255
print('归一化:',img.shape)
print('归一化:',img)#0和1组成



#预测
pred=model.predict(img.reshape(1,32,32,1))
print('prediction Number: ',pred.argmax())

#打印图片信息
plt.imshow(img)
plt.show()

#读取mnist数据集
(x_train,y_train),(x_test,y_test)=mnist.load_data()


# print(x_train.shape,y_train.shape)
# print(x_test.shape,y_test.shape)

print(x_train.shape,x_test.shape)
x_train= np.pad(x_train,((0,0),(2,2),(2,2)),'constant',constant_values=0) #28*28-》32*32
x_test= np.pad(x_test,((0,0),(2,2),(2,2)),'constant',constant_values=0) #28*28-》32*32
print(x_train.shape,x_test.shape)

#数据集格式转换
x_train=x_train.astype('float32')
x_train=x_train.astype('float32')

x_train=x_train/255#归一化
x_test=x_test/255#归一化


x_train=x_train.reshape(x_train.shape[0],32,32,1)
x_test=x_test.reshape(x_test.shape[0],32,32,1)
print(x_train.shape,x_test.shape)

print(x_test[0].reshape(32,32))





3、结果

 

 

 

 

 

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tech沉思录

点赞加投币,感谢您的资瓷~

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

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

打赏作者

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

抵扣说明:

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

余额充值