[Error resolution]_pickle.PicklingError: Can't pickle <class '__main__.Net'>: attribute lookup Net on __main__ f

Today, after running the model in Windows operating system, I wanted to save the model, but I encountered the following error:

 I'm really puzzled!

This is an error about pickle, so I searched for information about pickle on the Internet:

Pickle provides a simple persistence function that stores objects on disk as files.

But in the windows operating system, the process uses the socket object, and the socket object cannot be serialized. (In contrast, processes in the linux operating system use fork objects, so they can be serialized)

Solution:

Cut (or copy + comment)     the code with the network structure definition in another python script file, and then import the network into the original file by from..import.

    Little chestnut:

The definition of the Net network in my test01 file is as follows, and the above-mentioned error occurred.

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_output):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, 100)
        self.predict = torch.nn.Linear(100, n_output)
    def forward(self, x):
        out = self.hidden(x)
        out = torch.relu(out)
        out = self.predict(out)
        return out

Cut this piece of code into a new python file: NetWork, and then import it into test01 through the following code:

from NetWork import Net

Then you can save the model smoothly!

Guess you like

Origin blog.csdn.net/m0_64007201/article/details/127677630