手写数字识别-paddle版
平台
https://www.paddlepaddle.org.cn/
环境变量
# 路径
data_dir = '../data'
model_dir = 'inference_model'
base_dir = '{}/{}'.format(data_dir, model_dir)
# 模型名称
model_name = 'minist'
model_file = '{}/{}'.format(base_dir, model_name)
model_dynamic_file = '{}/{}/{}'.format(data_dir,'dynamic_model', model_name)
加载模型,并推理
import paddle
import numpy as np
# 引用 paddle inference 预测库
import paddle.inference as paddle_infer
from paddle.vision.transforms import Normalize
def main():
# 归一化函数,对[0-255]数据进行归一化,这样好处理
transform = Normalize(mean=[127.5], std=[127.5], data_format='CHW')
test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
# 设置输入
fake_input = np.asarray(test_dataset[1][0]).reshape([1,1,28,28])
# print(fake_input)
# 设置Config
config = set_config()
# 创建Predictor
predictor = paddle_infer.create_predictor(config)
# 获取输入的名称
input_names = predictor.get_input_names()
input_tensor = predictor.get_input_handle(input_names[0])
# 设置输入
# fake_input = np.random.randn(1,784).astype("float32")
input_tensor.copy_from_cpu(fake_input)
# 运行predictor
predictor.run()
# 获取输出
output_names = predictor.get_output_names()
output_tensor = predictor.get_output_handle(output_names[0])
output_data = output_tensor.copy_to_cpu() # numpy.ndarray类型
print("输出的形状如下: ")
print(output_data.shape)
print(output_data.argmax())
def set_config():
pdmodel_file = '{}.pdmodel'.format(model_file)
pdiparams_file = '{}.pdiparams'.format(model_file)
print('模型: {}'.format(pdmodel_file))
config = paddle_infer.Config(pdmodel_file, pdiparams_file)
config.disable_gpu()
return config
if __name__ == "__main__":
main()
可视化图片
import paddle
# 可视化图片
from matplotlib import pyplot as plt
test_dataset = paddle.vision.datasets.MNIST(mode='test')
# 从测试集中取出一张图片
img, label = test_dataset[1]
print(img)
plt.imshow(img)
plt.show()