[英]Pytorch issue: torch.load() does not correctly load a saved model from file after closing and reopening Spyder IDE
I followed the most basic code procedure for saving and loading neural network model parameters and it works perfectly fine.我遵循了保存和加载神经网络模型参数的最基本的代码过程,它工作得非常好。 After training the network, it is saved to a specified file in a specified folder in the package using the standard torch.save(model.state_dict(), file) method;
训练完网络后,使用标准的torch.save(model.state_dict(), file)方法将其保存到包中指定文件夹中的指定文件中; when I need to rerun the program to evaluate instead of train, it is loaded using the standard model.load_state_dict(torch.load(file)) method.
当我需要重新运行程序来评估而不是训练时,它使用标准 model.load_state_dict(torch.load(file)) 方法加载。 However, as soon as I close the Spyder IDE application and reopen the IDE and project, the torch.load does not result in the desired saved model.
但是,只要我关闭 Spyder IDE 应用程序并重新打开 IDE 和项目,torch.load 就不会生成所需的保存模型。 Note that I am testing the 'correctness' of the model by feeding inputs and checking the outputs.
请注意,我正在通过提供输入和检查输出来测试模型的“正确性”。 I am not sure if this is a problem with Spyder or with Pytorch, though I'm learning towards Spyder because the loading does work.
我不确定这是否是 Spyder 或 Pytorch 的问题,尽管我正在学习 Spyder,因为加载确实有效。
In short, the program works if I run it consecutively while Spyder is open, but as soon as Spyder closes and reopens, it ceases to work properly.简而言之,如果我在 Spyder 打开时连续运行该程序,该程序就可以工作,但是一旦 Spyder 关闭并重新打开,它就会停止正常工作。 Does anyone have a clue?
有人有线索吗?
It might be due to the fact that the state of your program is known while running the IDE but when closing it the state is lost resulting in the inability to know how to load the model (because the IDE doesnt know what model you are using).这可能是因为在运行 IDE 时程序的状态是已知的,但是当关闭它时状态丢失导致无法知道如何加载模型(因为 IDE 不知道您正在使用什么模型) . To solve this, try defining a new model and loading the parameters to it via
load
like so:要解决这个问题,请尝试定义一个新模型并通过
load
将参数加载到其中,如下所示:
my_model = MyModelClass(parameters).to(device)
checkpoint = torch.load(path)
my_model.load_state_dict(checkpoint)
This way the IDE knows what class is your model and can treat it properly.这样,IDE 就知道您的模型是什么类并且可以正确处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.