This is a very stupid mistake
Take a good look at the error information when debugging
Remind yourself to take good care of error! Remember! Remember!
Pytorch is already very friendly. You only need a simple command to save and load the model
#Save the entire network and parameters torch.save(your_net, 'save_name.pkl') #Loading saved models net = torch.load('save_name.pkl')
Because I’m lazy, I want to save the whole network and load it in the test file?
That’s what happened. Wrong error message, regard ‘net’ as’ net ‘. Error report has no attribute ‘net’? Isn’t this my own variable name?
—————–One hour later (ha ha ha)—————-
Looking back at error, there is no attribute ‘net’, net???
I now understand that if it is not imported into the test file, there will be no net information in the test. I copied the net definition directly into the test.py The trained model is loaded successfully.
But I also have a question. I understand that saving the whole model is not saving its structure? Why import this network again? Questions from python, python, object-oriented programming three dimensional Xiaobai, first save a question, understand and then answer.
Next, try saving only network parameters
#Save only network parameters torch.save(your_net.state_dict(), 'save_name.pkl') #Loading saved models net.load_state_dict(torch.load('save_name.pkl'))
Save network parameters
Redefine the network
Want to die…
After carefully reading the error information, I feel that the saved data may be pure data, not an object (there is no method to operate), or the object does not have a. Copy () method, so there is no way to carry out. Copy (), which must be an error in saving. Then found that save part of the code is wrong, changed to
Print net.state_ Dict and net.state_ Dict (), the former outputs the network structure, while the latter is the network parameter.
Try to answer the previous question. The second method only saves the parameters of the network (including the weight of convolution layer and full connection layer), So it’s OK to define the network first when loading the model, just like defining the network during training. The first way to save the whole network is to save an instance of the network (including all its structures and parameters). Net is an instance of net, so why should we have the definition of class net..
Then continue to doubt, keep the spirit of inquiry..
The above solution to the error problem encountered by the trained model loaded by Python is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developer more.