paddlepaddle手写体识别

代码如下:

import paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# train_dataset = paddle.vision.datasets.MNIST(mode='train')
# train_data0 = np.array(train_dataset[0][0])
# train_label_0 = np.array(train_dataset[0][1])
# plt.figure("Image")
# plt.figure(figsize=(2,2))
# plt.imshow(train_data0, cmap = plt.cm.binary)
# plt.axis('on')
# plt.title('image')
# plt.show()
#
# print("图像数据形状和对应的数据为:",train_data0.shape)
# print("图像的标签形状和对应的数据为:", train_label_0.shape, train_data0)
# print("\n打印第一个batch的第一个图像,对应标签数字为{}".format(train_label_0))


class MNIST(paddle.nn.Layer):
    def __init__(self):
        super(MNIST, self).__init__()
        self.fc = paddle.nn.Linear(in_features=784, out_features=1)
    def forward(self, inputs):
        outputs = self.fc(inputs)
        return outputs

model = MNIST()

def train(model):
    model.train()
    train_loader = paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),
                                        batch_size=16,
                                        shuffle=True)
    opt = paddle.optimizer.SGD(learning_rate=0.001, parameters=model.parameters())


def norm_img(img):
    assert len(img.shape) == 3
    batch_size, img_h, img_w = img.shape[0], img.shape[1], img.shape[2]
    img = img / 255
    img = paddle.reshape(img, [batch_size, img_h * img_w])
    return img


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)
    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)
            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.pdparams')


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)
im = im.resize((28, 28), Image.ANTIALIAS)
plt.imshow(im)
plt.show()
print("采样后图片shape: ", np.array(im).shape)

def load_image(img_path):
    im = Image.open(img_path).convert('L')
    im = im.resize((28, 28), Image.ANTIALIAS)
    im = np.array(im).reshape(1, -1).astype(np.float32)
    im = 1 - im / 255
    return im


model = MNIST()
params_file_path = 'mnist.pdparams'
img_path = './work/example_0.jpg'
param_dict = paddle.load(params_file_path)
model.load_dict(param_dict)
model.eval()
tensor_img = load_image(img_path)
result = model(paddle.to_tensor(tensor_img))
print('result',result)
print("本次预测的数字是", result.numpy().astype('int32'))

输出结果:

  import imp
epoch_id: 0, batch_id: 0, loss is: [19.691336]
epoch_id: 0, batch_id: 1000, loss is: [4.8562613]
epoch_id: 0, batch_id: 2000, loss is: [3.5893354]
epoch_id: 0, batch_id: 3000, loss is: [3.6005962]
epoch_id: 1, batch_id: 0, loss is: [7.029731]
epoch_id: 1, batch_id: 1000, loss is: [6.2418976]
epoch_id: 1, batch_id: 2000, loss is: [2.5513744]
epoch_id: 1, batch_id: 3000, loss is: [1.754514]
epoch_id: 2, batch_id: 0, loss is: [4.9103928]
epoch_id: 2, batch_id: 1000, loss is: [5.4251204]
epoch_id: 2, batch_id: 2000, loss is: [4.564935]
epoch_id: 2, batch_id: 3000, loss is: [2.9991786]
epoch_id: 3, batch_id: 0, loss is: [2.1028972]
epoch_id: 3, batch_id: 1000, loss is: [2.3331792]
epoch_id: 3, batch_id: 2000, loss is: [4.2814217]
epoch_id: 3, batch_id: 3000, loss is: [3.112694]
epoch_id: 4, batch_id: 0, loss is: [3.1716564]
epoch_id: 4, batch_id: 1000, loss is: [3.0454333]
epoch_id: 4, batch_id: 2000, loss is: [2.6289668]
epoch_id: 4, batch_id: 3000, loss is: [1.4390972]
epoch_id: 5, batch_id: 0, loss is: [6.6636868]
epoch_id: 5, batch_id: 1000, loss is: [3.5302186]
epoch_id: 5, batch_id: 2000, loss is: [3.886701]
epoch_id: 5, batch_id: 3000, loss is: [2.966082]
epoch_id: 6, batch_id: 0, loss is: [6.234954]
epoch_id: 6, batch_id: 1000, loss is: [5.239113]
epoch_id: 6, batch_id: 2000, loss is: [4.291875]
epoch_id: 6, batch_id: 3000, loss is: [2.9170785]
epoch_id: 7, batch_id: 0, loss is: [2.8740573]
epoch_id: 7, batch_id: 1000, loss is: [1.9314649]
epoch_id: 7, batch_id: 2000, loss is: [7.5295153]
epoch_id: 7, batch_id: 3000, loss is: [1.8619927]
epoch_id: 8, batch_id: 0, loss is: [2.6857028]
epoch_id: 8, batch_id: 1000, loss is: [3.0323493]
epoch_id: 8, batch_id: 2000, loss is: [3.6132627]
epoch_id: 8, batch_id: 3000, loss is: [3.0137868]
epoch_id: 9, batch_id: 0, loss is: [4.07297]
epoch_id: 9, batch_id: 1000, loss is: [4.682923]
epoch_id: 9, batch_id: 2000, loss is: [4.087107]
epoch_id: 9, batch_id: 3000, loss is: [3.667269]

result Tensor(shape=[1, 1], dtype=float32, place=CPUPlace, stop_gradient=False,
       [[1.11405170]])
本次预测的数字是 [[1]]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白榆的白

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

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

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

打赏作者

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

抵扣说明:

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

余额充值