#导入需要的包
import numpy as np
import paddle as paddle
import paddle.fluid as fluid
from PIL import Image
import matplotlib.pyplot as plt
import os
from paddle.fluid.dygraph import Linear
print("本教程基于Paddle的版本号为:"+paddle.__version__)
from paddle.vision.transforms import Compose, Normalize
transform = Compose([Normalize(mean=[127.5],std=[127.5],data_format='CHW')])
print('下载并加载训练数据')
train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
print('加载完成')
train_data0, train_label_0 = train_dataset[0][0],train_dataset[0][1]
train_data0 = train_data0.reshape([28,28])
plt.figure(figsize=(2,2))
print(plt.imshow(train_data0, cmap=plt.cm.binary))
print('train_data0 的标签为: ' + str(train_label_0))
print(train_dataset[0],type(train_dataset[0]))
# 定义多层感知器
#动态图定义多层感知器
class multilayer_perceptron(paddle.nn.Layer):
def __init__(self):
super(multilayer_perceptron,self).__init__()
self.fc1 = paddle.fluid.dygraph.Linear(input_dim=28*28, output_dim=100, act='relu')
self.fc2 = paddle.fluid.dygraph.Linear(input_dim=100, output_dim=100, act='relu')
self.fc3 = paddle.fluid.dygraph.Linear(input_dim=100, output_dim=10, act='softmax')
def forward(self, input_):
x = fluid.layers.reshape(input_, [input_.shape[0], -1])
x = self.fc1(x)
x = self.fc2(x)
y = self.fc3(x)
return y
from paddle.metric import Accuracy
use_gpu = False
paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
# 用Model封装模型
model = paddle.Model(multilayer_perceptron())
# 定义优化器
optim = paddle.optimizer.Adam(learning_rate=0.001,parameters=model.parameters())
# 配置模型 优化器 损失函数 评估标准
model.prepare(optim,paddle.nn.CrossEntropyLoss(),Accuracy())
# 训练保存并验证模型
model.fit(train_dataset,test_dataset,epochs=10,batch_size=64,save_dir='multilayer_perceptron',verbose=1)
#验证模型
model.evaluate(test_dataset, verbose=1)
#获取测试集的第一个图片
test_data0, test_label_0 = test_dataset[0][0],test_dataset[0][1]
test_data0 = test_data0.reshape([28,28])
plt.figure(figsize=(2,2))
#展示测试集中的第一个图片
print(plt.imshow(test_data0, cmap=plt.cm.binary))
print('test_data0 的标签为: ' + str(test_label_0))
#模型预测
result = model.predict(test_dataset, batch_size=1)
#打印模型预测的结果
print('test_data0 预测的数值为:%d' % np.argsort(result[0][0])[0][-1])
通过对手写识别项目的练习,对深度学习的理解更深一步