Pytorch模型文件`*.pt`与`*.pth` 的保存与加载

1.*.pt文件

.pt文件保存的是模型的全部,在加载时可以直接赋值给新变量model = torch.load("filename.pt")

具体操作:

  • (1). 模型的保存
torch.save(model,"Path/filename.pt")
  • (2). 模型的加载
model = torch.load("filename.pt")

注意:torch.load()的参数使用字符串参数。

2. .pth文件

.pth保存的是模型参数,通过字符字典进行保存,在加载该类文件时应该先实例化一个具体的模型,然后对新建立的空模型,进行参数赋予。

具体操作:

  • (1). 模型的保存
torch.save(model.state_dict(), PATH)
  • (2). 模型的加载
model = nn.Module() # 这里要先实例化模型
model.load_state_dict(torch.load("filename.pth"))

操作实例

  1. 首先定义一个模型作为例子
# Define model
class TheModelClass(nn.Module):
    # 类的初始化
    def __init__(self):
        # 继承父类 nn.Module 的属性和方法
        super(TheModelClass, self).__init__()
        # Inputs_channel, Outputs_channel, kernel_size
        self.conv1 = nn.Conv2d(3, 6, 5)
        # 最大池化层,池化核的大小
        self.pool = nn.MaxPool2d(2, 2)
        # 卷积层,池化层,卷积层
        self.conv2 = nn.Conv2d(6, 16, 5)
        # 最后接一个线性全连接层
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 卷积作用后,使用relu进行非线性化,最后使用池化操作进行特征个数,参数量的降低
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

# Initialize model
model = TheModelClass()

# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)

# Print model's state_dict
print("Model's state_dict:")
for param_tensor in model.state_dict():
    print(param_tensor, "\t", model.state_dict()[param_tensor].size())

# Print optimizer's state_dict
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
    print(var_name, "\t", optimizer.state_dict()[var_name])

2. 现在开始进行模型的保存与加载

PATH = "/home/深度学习/model"
#  第一种模型保存和加载方式
torch.save(model.state_dict(), PATH+"/TheModuleClass.pth")
model = TheModelClass()
model.load_state_dict(torch.load("/home/深度学习/model/TheModuleClass.pth"))

for param_tensor in model.state_dict():
    print(f"{param_tensor}<<<{model.state_dict()[param_tensor].size()}")
print(model)

# 输出结果
'''
conv1.weight<<<torch.Size([6, 3, 5, 5])
conv1.bias<<<torch.Size([6])
conv2.weight<<<torch.Size([16, 6, 5, 5])
conv2.bias<<<torch.Size([16])
fc1.weight<<<torch.Size([120, 400])
fc1.bias<<<torch.Size([120])
fc2.weight<<<torch.Size([84, 120])
fc2.bias<<<torch.Size([84])
fc3.weight<<<torch.Size([10, 84])
fc3.bias<<<torch.Size([10])
TheModelClass(
  (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
'''
#  第二种模型保存和加载方式

torch.save(model, PATH + "/the_module_class.pt")
model = torch.load(PATH + "/the_module_class.pt")

for param_tensor in model.state_dict():
    print(f"{param_tensor} <<< {model.state_dict()[param_tensor].size()}")
print(model)

#  输出结果
'''
conv1.weight<<<torch.Size([6, 3, 5, 5])
conv1.bias<<<torch.Size([6])
conv2.weight<<<torch.Size([16, 6, 5, 5])
conv2.bias<<<torch.Size([16])
fc1.weight<<<torch.Size([120, 400])
fc1.bias<<<torch.Size([120])
fc2.weight<<<torch.Size([84, 120])
fc2.bias<<<torch.Size([84])
fc3.weight<<<torch.Size([10, 84])
fc3.bias<<<torch.Size([10])
TheModelClass(
  (conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
  (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
'''

总结

  • 这里推荐使用第二种方法,因为保存和加载文件简单,而且生成的二进制文件区分程度高。
  • torch.save() 保存模型的参数,为以后模型推理核模型恢复提供了更加方便更加灵活的方法。
  • 一定要在模型评估时, 关闭批量规范化和丢弃法, 仅仅在模型训练时有用,模型推理时一定要关闭(所谓模型推理,指是使用模型进行的实际应用)
  • 加载.pth 要先实例化,再进行参数的承接。
posted @ 2024-07-19 10:09  华小电  阅读(2)  评论(0编辑  收藏  举报