[PaddlePaddle/Paddle]自定义模型paddle.Model训练出的结果paddle.model.predict预测结果是正确, paddle.load、paddle.model.save等动态图静态图下预测结果都错误,希望直接aistudio看结果

2024-03-22 210 views
4
请提出你的问题 Please ask your question

自定义模型paddle.Model训练, 动态图:paddle.Model.load然后paddle.model.predict预测结果是正确,paddle.load然后set_state_dict然后eval()然后前向计算结果错误, 静态图:使用paddle.load然后paddle.jit.to_static然后paddle.jit.save然后预测paddle.inference.create_predictor结果错误 静态图:使用paddle.model.save('inference', False)然后paddle.inference.create_predictor(paddle.inference.Config('inference.pdmodel', 'inference.pdiparams'))结果错误 希望高手大侠可以直接运行我的aistudio项目看结果,这样效率更高

代码如下:

import paddle as pp

class Net(pp.nn.Layer): ... @pp.jit.to_static() def forward(self, x): ... model = pp.Model(Net(), inputs=x, labels=y) model.fit( save_dir="output/" ) model = pp.Model(Net(), inputs=x) model.load("output/final") model.prepare() model.save('inference', False) results = model.predict() #results:1234结果正确 config = paddle_infer.Config('inference.pdmodel', 'inference.pdiparams') predictor = paddle_infer.create_predictor(config) predictor.run() #results:9876结果错误

我修改为如下方式,结果还是不一致,原来能正确识别,导出静态后精度只有10%

n=Net(is_infer=True) para_state_dict = pp.load("/home/aistudio/output/final.pdparams") n.set_state_dict(para_state_dict)

model = pp.jit.to_static( n, input_spec=[input_define] ) pp.jit.save(model, 'model')

以下动态图输出结果与pp.jit.to_static输出结果一致都是精度不准确的结果。只有在model = pp.Model(Net(), inputs=x, labels=y) 精度才是准确的 n=Net(is_infer=True) para_state_dict = pp.load("/home/aistudio/output/final.pdparams") n.set_state_dict(para_state_dict) n.eval() img_name=r'/home/aistudio/sample_img/8205.jpg' path=r'/home/aistudio/sample_img' for root, dirs, files in os.walk(path): for f in files: img_name = os.path.join(root, f) img = Image.open(img_name) x = np.array(img, dtype="float32").reshape((1,IMAGE_SHAPE_C, IMAGE_SHAPE_H, IMAGE_SHAPE_W)) x=pp.to_tensor(x, dtype='float32') out = n(x) print(f,out)

以下是aistudio地址 https://aistudio.baidu.com/aistudio/projectdetail/4067637?contributionType=1

回答

2

我修改为如下方式,结果还是不一致,原来能正确识别,导出静态后精度只有10%

n=Net(is_infer=True) para_state_dict = pp.load("/home/aistudio/output/final.pdparams") n.set_state_dict(para_state_dict)

model = pp.jit.to_static( n, input_spec=[input_define] ) pp.jit.save(model, 'model')

3

@liuyang77887 n.set_state_dict(para_state_dict) 之后在动态图下预测结果正确吗?

7

以下输出结果与pp.jit.to_static输出结果一致都是精度不准确的结果。只有在model = pp.Model(Net(), inputs=x, labels=y) 精度才是准确的 n=Net(is_infer=True) para_state_dict = pp.load("/home/aistudio/output/final.pdparams") n.set_state_dict(para_state_dict) n.eval() img_name=r'/home/aistudio/sample_img/8205.jpg' path=r'/home/aistudio/sample_img' for root, dirs, files in os.walk(path): for f in files: img_name = os.path.join(root, f) img = Image.open(img_name) x = np.array(img, dtype="float32").reshape((1,IMAGE_SHAPE_C, IMAGE_SHAPE_H, IMAGE_SHAPE_W)) x=pp.to_tensor(x, dtype='float32') out = n(x) print(f,out)

5

@liuyang77886 请检查下final.pdparams权重是否正确吧,根据你的描述,加载这一份权重预测的结果都不正确?

1

paddle.Model.load结果是正确,paddle.load结果错误 paddle.Model.load结果是正确,paddle.load结果错误 paddle.Model.load结果是正确,paddle.load结果错误

4

@liuyang77886 Model.load之后,然后动转静的模型预测结果正确吗?

8

@yghstill 能不能帮我看看aistudio啊

1

@liuyang77886 跑过你的AIStudio,你的前处理没有对齐,请仔细确认对齐下输出预处理部分:

1. paddle.load接口测试:
n=Net(is_infer=True)
# 加载训练好的参数模型
para_state_dict = pp.load("/home/aistudio/output/final.pdparams")
n.set_state_dict(para_state_dict)

# 实例化推理模型
model = pp.Model(n, inputs=input_define)

# 设置运行环境
model.prepare()

# 加载预测Reader
infer_reader = InferReader(INFER_DATA_PATH)
###########debug###########
for data in infer_reader:
    print(data.shape, data.sum())
##########################
img_names = infer_reader.get_names()
results = model.predict(infer_reader, batch_size=BATCH_SIZE)
index = 0
print("results映射表为:", results)
# 创建Label映射表,如果为其它数据集,需要保证每个数字有对应符号,例如{1: "A", 2: "B", ...}
label_dict = dict([(i, str(i)) for i in range(11)])
print("Label映射表为:", label_dict)

ctc_decoder = CTCDecoder(label_dict, blank=10)
for text_batch in results[0]:
    for prob in text_batch:
        out = ctc_decoder.decoder(prob)
        print(f"文件名:{img_names[index]},推理结果为:{out}")
        index += 1

输出:

(3, 30, 70) 4468.9844
(3, 30, 70) 4280.6436
(3, 30, 70) 4341.8433
Predict begin...
step 1/1 [==============================] - 5ms/step
Predict samples: 3
results映射表为: [(array([[ 0, 10,  3, 10, 10,  0, 10,  0],
       [ 8, 10,  2, 10, 10,  0, 10,  5],
       [ 3, 10,  4, 10, 10,  6, 10,  3]], dtype=int64),)]
Label映射表为: {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10'}
文件名:0300.jpg,推理结果为:0300
文件名:8205.jpg,推理结果为:8205
文件名:3463.jpg,推理结果为:3463
2. 你的代码测试:
n=Net(is_infer=True)
para_state_dict = pp.load("/home/aistudio/output/final.pdparams")
n.set_state_dict(para_state_dict)
n.eval()
img_name=r'/home/aistudio/sample_img/8205.jpg'
path=r'/home/aistudio/sample_img'
for root, dirs, files in os.walk(path):
    for f in files:
        img_name = os.path.join(root, f) 
        img = Image.open(img_name)
        x = np.array(img, dtype="float32").reshape((1,IMAGE_SHAPE_C, IMAGE_SHAPE_H, IMAGE_SHAPE_W))
        x=pp.to_tensor(x, dtype='float32')
        print('[ygh]x', x.shape, x.sum())
        out = n(x) 
        print(f,out)

结果:

[ygh]x [1, 3, 30, 70] Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
       [1139591.])
0300.jpg Tensor(shape=[1, 8], dtype=int64, place=CUDAPlace(0), stop_gradient=False,
       [[0 , 10, 3 , 10, 10, 0 , 10, 0 ]])
[ygh]x [1, 3, 30, 70] Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
       [1091564.])
8205.jpg Tensor(shape=[1, 8], dtype=int64, place=CUDAPlace(0), stop_gradient=False,
       [[6 , 10, 0 , 10, 10, 0 , 10, 10]])
[ygh]x [1, 3, 30, 70] Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
       [1107170.])
3463.jpg Tensor(shape=[1, 8], dtype=int64, place=CUDAPlace(0), stop_gradient=False,
       [[0 , 10, 10, 10, 10, 10, 10, 2 ]])

对data求sum,正确的是4468.9844...,你的代码处理完为1139591,相差很大,判断为数据预处理未对齐,请对齐后再尝试。

4

感谢,解决