# _*_ coding.utf-s _*_
# 开发人员:Mark
# 开发时间:2021/10/14 17:54
# 文件名: 手写数字识别.py
import paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import os
import numpy as np
import matplotlib.pyplot as plt
#读取训练集
train_dataset = paddle.vision.datasets.MNIST(maode='trin')
# train_data0 = np.array(train_dataset[0][0])
# train_label_0 = np.array(train_dataset[0][1])
#
# # 显示第一batch的第一个图像
# import matplotlib.pyplot as plt
# plt.figure("Image") # 图像窗口名称
# plt.figure(figsize=(2,2))
# plt.imshow(train_data0, cmap=plt.cm.binary)
# plt.axis('on') # 关掉坐标轴为 off
# plt.title('image') # 图像题目
# plt.show()
#
# print("图像数据形状和对应数据为:", train_data0.shape)
# print("图像标签形状和对应数据为:", train_label_0.shape, train_label_0)
# print("\n打印第一个batch的第一个图像,对应标签数字为{}".format(train_label_0))
class Mnist(paddle.nn.Layer):
def __init__(self):
super(Mnist,self).__init__() #super 继承类
#定义全连接层,输出为1维
self.fc = paddle.nn.Linear(in_features=784,out_features=1)
#定义前向计算过程
def forward(self,inputs):
outputs = self.fc(inputs)
return outputs
#图像归一化将[0,255]范围内数据归一化到[0,1]
def norm_img(img):
#验证输入的数据格式是否正确,img的shape是[batch_size,28,28]
assert len(img.shape) ==3
batch_size,img_h,img_w = img.shape[0],img.shape[1],img.shape[2]
#归一化图像数据
img = img /255
#将图片形式reshape为[batch_size,img_h * img_w
img = paddle.reshape(img,[batch_size,img_h *img_w])
return img
import paddle
#确保从Mnist中加载的图像数据是np.ndarray类型
paddle.vision.set_image_backend('cv2')
#网络结构
model = Mnist()
#搭建训练配置,优化算法
def train(model):
model.train() ######
train_loader = paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),
batch_size=16,
shuffle=True)
#优化器,梯度下降SDG
opt = paddle.optimizer.SGD(learning_rate=0.001,parameters=model.parameters()
)
EPOCH_NUM = 10
for epoch in range(EPOCH_NUM):
for batch_id ,data in enumerate(train_loader()):
images = norm_img(data[0]).astype('float32')
labels = data[1].astype('float32')
#前向计算的过程
predicts = model(images)
#计算损失
loss = F.square_error_cost(predicts,labels)
avg_loss = paddle.mean(loss)
#训练了1000次打印当前损失loss
if batch_id % 1000 == 0:
print("epoch_id:{},batch_id:{},loss is:{}".format(epoch,batch_id,avg_loss.numpy()))
#后向传播,更新参数
avg_loss.backward()
opt.step()
opt.clear_grad()
train(model)
paddle.save(model.state_dict(),'/mnist.pdparam')
# 导入图像读取第三方库
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
img_path = './work/example_0.jpg'
# 读取原始图像并显示
im = Image.open('./work/example_0.jpg')
plt.imshow(im)
plt.show()
# 将原始图像转为灰度图
im = im.convert('L')
print('原始图像shape: ', np.array(im).shape)
# 使用Image.ANTIALIAS方式采样原始图片
im = im.resize((28, 28), Image.ANTIALIAS)
plt.imshow(im)
plt.show()
print("采样后图片shape: ", np.array(im).shape)
手写数字识别的开始
最新推荐文章于 2024-05-21 16:52:47 发布