Python UnpicklingError:遇到加载持久id指令,但未指定持久加载函数

Python UnpicklingError:遇到加载持久id指令,但未指定持久加载函数,python,serialization,deep-learning,pytorch,pickle,Python,Serialization,Deep Learning,Pytorch,Pickle,我试图运行一个名为api.py的python文件。在这个文件中,我正在加载使用PyTorch构建和训练的深度学习模型的pickle文件 在api.py中,下面给出的函数是最重要的函数 def load_model_weights(model_architecture, weights_path): if os.path.isfile(weights_path): cherrypy.log("CHERRYPYLOG Loading model from: {}"

我试图运行一个名为
api.py
的python文件。在这个文件中,我正在加载使用PyTorch构建和训练的深度学习模型的pickle文件

api.py
中,下面给出的函数是最重要的函数

def load_model_weights(model_architecture, weights_path):
  if os.path.isfile(weights_path):
      cherrypy.log("CHERRYPYLOG Loading model from: {}".format(weights_path))
      model_architecture.load_state_dict(torch.load(weights_path))
  else:
      raise ValueError("Path not found {}".format(weights_path))

        
def load_recommender(vector_dim, hidden, activation, dropout, weights_path):

    rencoder_api = model.AutoEncoder(layer_sizes=[vector_dim] + [int(l) for l in hidden.split(',')],
                               nl_type=activation,
                               is_constrained=False,
                               dp_drop_prob=dropout,
                               last_layer_activations=False)
    load_model_weights(rencoder_api, weights_path) 
    rencoder_api.eval()
    rencoder_api = rencoder_api.cuda()
    return rencoder_api
目录结构

After searching through PyTorch documentation, I ended up saving the model in the ONNX format and later loaded that ONNX model into PyTorch model and used it for inference.

import onnx
from onnx2pytorch import ConvertModel


def load_model_weights(model_architecture, weights_path):
    if os.path.isfile("model.onnx"):
        cherrypy.log("CHERRYPYLOG Loading model from: {}".format(weights_path))
        onnx_model = onnx.load("model.onnx")
        pytorch_model = ConvertModel(onnx_model)
        ## model_architecture.load_state_dict(torch.load(weights_path))
    else:
        raise ValueError("Path not found {}".format(weights_path))

        
def load_recommender(vector_dim, hidden, activation, dropout, weights_path):

    rencoder_api = model.AutoEncoder(layer_sizes=[vector_dim] + [int(l) for l in hidden.split(',')],
                               nl_type=activation,
                               is_constrained=False,
                               dp_drop_prob=dropout,
                               last_layer_activations=False)
    load_model_weights(rencoder_api, weights_path) 
    rencoder_api.eval()
    rencoder_api = rencoder_api.cuda()
    return rencoder_api

在搜索PyTorch文档后,我最终以以下格式保存了该模型,然后将该ONNX模型加载到PyTorch模型中并用于推理

一些有用的资源: