Paddle icon indicating copy to clipboard operation
Paddle copied to clipboard

在Windows上加载合并模型报错

Open yeyupiaoling opened this issue 7 years ago • 9 comments

环境

  • paddlepaddle 1.2.0
  • Windows 10 专业版
  • Python 3.5

问题

使用报错预测模型接口paddle.fluid.io.save_inference_model保存训练的模型,然后再Windows上通过调用paddle.fluid.io.load_inference_model接口加载模型,然后就报错报错如下:

  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 784, in load_inference_model
    load_persistables(executor, dirname, program, params_filename)
  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 529, in load_persistables
    filename=filename)
  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 395, in load_vars
    filename=filename)
  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 436, in load_vars
    executor.run(load_prog)
  File "C:\Python35\lib\site-packages\paddle\fluid\executor.py", line 472, in run
    self.executor.run(program.desc, scope, 0, True, True)
paddle.fluid.core.EnforceNotMet: Cannot read more from file ./model\params at [E:\dist\Paddle\paddle\fluid\operators\load_combine_op.cc:58]
PaddlePaddle Call Stacks: 
Windows not support stack backtrace yet.

错误信息提示:Windows not support stack backtrace yet. 这个应该是待实现的功能吧?

yeyupiaoling avatar Dec 24 '18 08:12 yeyupiaoling

是,win上暂不支持callback trace,不过这个错误应该是路径问题,./model\params 换成 .\model\params

wopeizl avatar Dec 25 '18 02:12 wopeizl

@wopeizl 路径没有问题的,这个路径也是正常的,修改之后也是同样的错误。 如果使用非合并模型就不会报错。

yeyupiaoling avatar Dec 25 '18 03:12 yeyupiaoling

可以把完整的代码贴一下吗?尽量简单可复现的

wopeizl avatar Dec 25 '18 05:12 wopeizl

@wopeizl 加载模型预测图像:

import paddle.fluid as fluid
from PIL import Image
import config as cfg
import numpy as np

# 获取执行器
place = fluid.CPUPlace()
exe = fluid.Executor(place)

# 从保存的模型文件中获取预测程序、输入数据的名称和分类器
[infer_program, feeded_var_names, target_vars] = fluid.io.load_inference_model(dirname='./model',
                                                                               executor=exe,
                                                                               model_filename='model',
                                                                               params_filename='params')


# 对图片进行预处理
def load_image(path):
    img = Image.open(path)
    # 统一图像大小
    img = img.resize((cfg.READER.CROP_SIZE, cfg.READER.CROP_SIZE), Image.ANTIALIAS)
    # 转换成numpy值
    img = np.array(img).astype(np.float32)
    # 转换成CHW
    img = img.transpose((2, 0, 1))
    # 转换成BGR
    img = img[(2, 1, 0), :, :] / 255.0
    return img


# 添加待预测的图片
infer_data = []
infer_data.append(load_image('./dataset/cucumber/2e10432c-01ea-11e9-a2e1-c8ff285a4318.jpg'))
infer_data.append(load_image('./dataset/apple/58d14a90-01e2-11e9-9470-c8ff285a4318.jpg'))
infer_data = np.array(infer_data)
print(infer_data.shape)

results = exe.run(program=infer_program,
                  feed={feeded_var_names[0]: infer_data},
                  fetch_list=target_vars)
print(results)
lab = np.argsort(results)
print(lab[0])

yeyupiaoling avatar Dec 25 '18 06:12 yeyupiaoling

save_inference_model的时候也指明了model和param名字吗?我这边没有复现,你可以试试跑一下如下测试

import os
import paddle
import paddle.fluid as fluid
import numpy

model_name = 'model'
params_name = 'params'

def net(x, y):
    y_predict = fluid.layers.fc(input=x, size=1, act=None)
    cost = fluid.layers.square_error_cost(input=y_predict, label=y)
    avg_cost = fluid.layers.mean(cost)
    return y_predict, avg_cost


def train(save_dirname):
    print('start train ....')
    x = fluid.layers.data(name='x', shape=[13], dtype='float32')
    y = fluid.layers.data(name='y', shape=[1], dtype='float32')
    y_predict, avg_cost = net(x, y)
    sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
    sgd_optimizer.minimize(avg_cost)
    train_reader = paddle.batch(
        paddle.reader.shuffle(paddle.dataset.uci_housing.train(), buf_size=500),
        batch_size=20)
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)

    def train_loop(main_program):
        feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
        exe.run(fluid.default_startup_program())

        PASS_NUM = 1000
        for pass_id in range(PASS_NUM):
            total_loss_pass = 0
            for data in train_reader():
                avg_loss_value, = exe.run(
                    main_program, feed=feeder.feed(data), fetch_list=[avg_cost])
                total_loss_pass += avg_loss_value
                if avg_loss_value < 5.0:
                    if save_dirname is not None:
                        fluid.io.save_inference_model(
                            save_dirname, ['x'], [y_predict], exe, None, model_name, params_name)
                    return
            print("Pass %d, total avg cost = %f" % (pass_id, total_loss_pass))

    train_loop(fluid.default_main_program())


def infer(save_dirname=None):
    print('start infer ....')
    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        [inference_program, feed_target_names, fetch_targets] = (
            fluid.io.load_inference_model(save_dirname, exe, model_name, params_name))
        test_reader = paddle.batch(paddle.dataset.uci_housing.test(), batch_size=20)

        test_data = test_reader().next()
        test_feat = numpy.array(map(lambda x: x[0], test_data)).astype("float32")
        test_label = numpy.array(map(lambda x: x[1], test_data)).astype("float32")

        results = exe.run(inference_program,
                          feed={feed_target_names[0]: numpy.array(test_feat)},
                          fetch_list=fetch_targets)
        print("infer results: ", results[0])
        print("ground truth: ", test_label)


if __name__ == "__main__":
    save_dirname = "fit_a_line.inference.model"
    if os.name != 'nt':
        train(save_dirname)

    infer(save_dirname)

wopeizl avatar Dec 25 '18 08:12 wopeizl

@wopeizl 你这个是可以正常加载模型的,可能是使用的网络不一样,我的是mobilenet v1 还有,我的是在Ubuntu上使用GPU训练,然后再Windows上使用CPU预测的。

yeyupiaoling avatar Dec 25 '18 08:12 yeyupiaoling

@wopeizl 路径是正常的,我故意搞不正确路径,报错是不一样的,如:

  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 436, in load_vars
    executor.run(load_prog)
  File "C:\Python35\lib\site-packages\paddle\fluid\executor.py", line 472, in run
    self.executor.run(program.desc, scope, 0, True, True)
paddle.fluid.core.EnforceNotMet: Cannot open file model\paramsd for load_combine op at [E:\dist\Paddle\paddle\fluid\operators\load_combine_op.cc:38]
PaddlePaddle Call Stacks: 
Windows not support stack backtrace yet.

路径正确是报这个错误:

  File "C:\Python35\lib\site-packages\paddle\fluid\io.py", line 436, in load_vars
    executor.run(load_prog)
  File "C:\Python35\lib\site-packages\paddle\fluid\executor.py", line 472, in run
    self.executor.run(program.desc, scope, 0, True, True)
paddle.fluid.core.EnforceNotMet: Cannot read more from file model\params at [E:\dist\Paddle\paddle\fluid\operators\load_combine_op.cc:58]
PaddlePaddle Call Stacks: 
Windows not support stack backtrace yet.

yeyupiaoling avatar Dec 29 '18 06:12 yeyupiaoling

确认了win下save/load op有问题,谢谢指出,我们会出一个fix

wopeizl avatar Dec 29 '18 06:12 wopeizl

https://github.com/PaddlePaddle/Paddle/pull/15112

wopeizl avatar Jan 03 '19 10:01 wopeizl