神经网络模型的保存和读取

保存神经网络的两种方法:

(还是以我之前自建的神经网络模型Gu为例,保存这个神经网络)

gu = Gu()

1. torch.save(gu,"gu_module.pth")

2. torch.save(gu.state_dict(),"gu_module.pth")

import torch
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear


class Gu(nn.Module):
    def __init__(self):
        super(Gu  , self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self,x):
        x = self.model1(x)
        return x;

gu = Gu()
torch.save(gu,"gu_module.pth")

运行后将会在本文件夹下产生此文件:gu_module.pth

你可能感兴趣的:(基于pytorch的深度学习,pytorch,神经网络,深度学习)