import paddle
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import paddle.nn.functional as F
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 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'))
lables = data[1].astype('float32')
predicts = model(images)
loss = F.square_error_cost(predicts, lables)
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 = 'example_0.jpg'
im = Image.open('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_img(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 / 25
return im
model = MNIST()
params_file_path = 'mnist.pdparams'
img_path = 'example_0.jpg'
param_dict = paddle.load(params_file_path)
model.load_dict(param_dict)
model.eval()
tensor_img = load_img(img_path)
result = model(paddle.to_tensor(tensor_img))
print('result', result)
print("本次预测结果为:", result.numpy().astype("int32"))
运行结果:
D:\anndconda\envs\paddle_gpu\python.exe “C:/Users/Brother DA/Desktop/电磁场理论rcn/pp/HWR/Hwr.py”
W1019 20:12:36.522939 19408 device_context.cc:404] Please NOTE: device: 0, GPU Compute Capability: 7.5, Driver API Version: 11.5, Runtime API Version: 10.2
W1019 20:12:36.529965 19408 device_context.cc:422] device: 0, cuDNN Version: 7.6.
epoch_id: 0, batch_id: 0, loss is: [26.84817]
epoch_id: 0, batch_id: 1000, loss is: [18.708328]
epoch_id: 0, batch_id: 2000, loss is: [18.206642]
epoch_id: 0, batch_id: 3000, loss is: [23.027702]
epoch_id: 1, batch_id: 0, loss is: [20.303207]
epoch_id: 1, batch_id: 1000, loss is: [11.99618]
epoch_id: 1, batch_id: 2000, loss is: [18.19603]
epoch_id: 1, batch_id: 3000, loss is: [8.489115]
epoch_id: 2, batch_id: 0, loss is: [15.74844]
epoch_id: 2, batch_id: 1000, loss is: [11.178358]
epoch_id: 2, batch_id: 2000, loss is: [10.636837]
epoch_id: 2, batch_id: 3000, loss is: [8.759826]
epoch_id: 3, batch_id: 0, loss is: [7.7979918]
epoch_id: 3, batch_id: 1000, loss is: [10.254571]
epoch_id: 3, batch_id: 2000, loss is: [11.796951]
epoch_id: 3, batch_id: 3000, loss is: [7.0109634]
epoch_id: 4, batch_id: 0, loss is: [10.475475]
epoch_id: 4, batch_id: 1000, loss is: [7.537572]
epoch_id: 4, batch_id: 2000, loss is: [10.147574]
epoch_id: 4, batch_id: 3000, loss is: [13.772131]
epoch_id: 5, batch_id: 0, loss is: [13.535334]
epoch_id: 5, batch_id: 1000, loss is: [3.9194648]
epoch_id: 5, batch_id: 2000, loss is: [8.524084]
epoch_id: 5, batch_id: 3000, loss is: [9.984186]
epoch_id: 6, batch_id: 0, loss is: [12.189134]
epoch_id: 6, batch_id: 1000, loss is: [6.66195]
epoch_id: 6, batch_id: 2000, loss is: [5.2205167]
epoch_id: 6, batch_id: 3000, loss is: [4.7870035]
epoch_id: 7, batch_id: 0, loss is: [5.111581]
epoch_id: 7, batch_id: 1000, loss is: [8.6006565]
epoch_id: 7, batch_id: 2000, loss is: [8.151041]
epoch_id: 7, batch_id: 3000, loss is: [9.43359]
epoch_id: 8, batch_id: 0, loss is: [8.163991]
epoch_id: 8, batch_id: 1000, loss is: [7.3730354]
epoch_id: 8, batch_id: 2000, loss is: [8.755945]
epoch_id: 8, batch_id: 3000, loss is: [13.405254]
epoch_id: 9, batch_id: 0, loss is: [7.022579]
epoch_id: 9, batch_id: 1000, loss is: [7.3355527]
epoch_id: 9, batch_id: 2000, loss is: [10.492103]
epoch_id: 9, batch_id: 3000, loss is: [8.992606]
原始图像shape: (28, 28)
采样后的图片shape: (28, 28)
result Tensor(shape=[1, 1], dtype=float32, place=CUDAPlace(0), stop_gradient=False,
[[-73.15663910]])
本次预测结果为: [[-73]]
进程已结束,退出代码0