当前位置:   article > 正文

Pytorch如何保存训练好的模型_pytorch保存训练好的模型

pytorch保存训练好的模型

0.为什么要保存和加载模型

用数据对模型进行训练后得到了比较理想的模型,但在实际应用的时候不可能每次都先进行训练然后再使用,所以就得先将之前训练好的模型保存下来,然后在需要用到的时候加载一下直接使用。模型的本质是一堆用某种结构存储起来的参数,所以在保存的时候有两种方式,一种方式是直接将整个模型保存下来,之后直接加载整个模型,但这样会比较耗内存;另一种是只保存模型的参数,之后用到的时候再创建一个同样结构的新模型,然后把所保存的参数导入新模型。

1.两种情况的实现方法

(1)只保存模型参数字典(推荐)

  1. # 保存:
  2. torch.save(model.state_dict(), mymodel.pth)#只保存模型权重参数,不保存模型结构
  3. # 调用:
  4. model = My_model(*args, **kwargs) #这里需要重新模型结构,My_model
  5. model.load_state_dict(torch.load(mymodel.pth))#这里根据模型结构,调用存储的模型参数
  6. model.eval()

(2)保存整个模型

  1. # 保存:
  2. torch.save(model, mymodel.pth) #保存整个model的状态
  3. # 调用:
  4. model=torch.load(mymodel.pth) #这里已经不需要重构模型结构了,直接load就可以
  5. model.eval()

3.只保存模型参数的情况(例子)

        pytorch会把模型的参数放在一个字典里面,而我们所要做的就是将这个字典保存,然后再调用。
比如说设计一个单层LSTM的网络,然后进行训练,训练完之后将模型的参数字典进行保存,保存为同文件夹下面的rnn.pkl(或者pth文件或者pt文件)文件:

我们经常会看到后缀名为.pt, .pth, .pkl的pytorch模型文件,这几种模型文件在格式上有什么区别吗?其实它们并不是在格式上有区别,只是后缀不同而已(仅此而已),在用torch.save()函数保存模型文件时,各人有不同的喜好,有些人喜欢用.pt后缀,有些人喜欢用.pth或.pkl.用相同的torch.save()语句保存出来的模型文件没有什么不同。

在pytorch官方的文档/代码里,有用.pt的,也有用.pth的。一般惯例是使用.pth,但是官方文档里貌似.pt更多,而且官方也不是很在意固定用一种。

 

  1. class LSTM(nn.Module):
  2. def __init__(self, input_size, hidden_size, num_layers):
  3. super(LSTM, self).__init__()
  4. self.hidden_size = hidden_size
  5. self.num_layers = num_layers
  6. self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
  7. self.fc = nn.Linear(hidden_size, 1)
  8. def forward(self, x):
  9. # Set initial states
  10. h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
  11. # 2 for bidirection
  12. c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
  13. # Forward propagate LSTM
  14. out, _ = self.lstm(x, (h0, c0))
  15. # out: tensor of shape (batch_size, seq_length, hidden_size*2)
  16. out = self.fc(out)
  17. return out
  18. rnn = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)
  19. # optimize all cnn parameters
  20. optimizer = torch.optim.Adam(rnn.parameters(), lr=0.001)
  21. # the target label is not one-hotted
  22. loss_func = nn.MSELoss()
  23. for epoch in range(1000):
  24. output = rnn(train_tensor) # cnn output`
  25. loss = loss_func(output, train_labels_tensor) # cross entropy loss
  26. optimizer.zero_grad() # clear gradients for this training step
  27. loss.backward() # backpropagation, compute gradients
  28. optimizer.step() # apply gradients
  29. output_sum = output
  30. # 保存模型
  31. torch.save(rnn.state_dict(), 'rnn.pt')

保存完之后利用这个训练完的模型对数据进行处理:

  1. # 测试所保存的模型
  2. m_state_dict = torch.load('rnn.pt')
  3. new_m = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)
  4. new_m.load_state_dict(m_state_dict)
  5. predict = new_m(test_tensor)

注意保存模型和加载模型使用的模型结构必须是一样的(在上例代码中,实例化一个LSTM对像,这里要保证传入的参数跟实例化rnn是传入的对象时一样的,即结构相同new_m = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device);)。最简单的方法其实是直接拷贝一份原来的Python脚本,在里面加上一行就行了

new_m.load_state_dict(m_state_dict)

4.保存整个模型的情况(例子)

  1. class LSTM(nn.Module):
  2. def __init__(self, input_size, hidden_size, num_layers):
  3. super(LSTM, self).__init__()
  4. self.hidden_size = hidden_size
  5. self.num_layers = num_layers
  6. self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
  7. self.fc = nn.Linear(hidden_size, 1)
  8. def forward(self, x):
  9. # Set initial states
  10. h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) # 2 for bidirection
  11. c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
  12. # Forward propagate LSTM
  13. out, _ = self.lstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size*2)
  14. # print("output_in=", out.shape)
  15. # print("fc_in_shape=", out[:, -1, :].shape)
  16. # Decode the hidden state of the last time step
  17. # out = torch.cat((out[:, 0, :], out[-1, :, :]), axis=0)
  18. # out = self.fc(out[:, -1, :]) # 取最后一列为out
  19. out = self.fc(out)
  20. return out
  21. rnn = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)
  22. print(rnn)
  23. optimizer = torch.optim.Adam(rnn.parameters(), lr=0.001) # optimize all cnn parameters
  24. loss_func = nn.MSELoss() # the target label is not one-hotted
  25. for epoch in range(1000):
  26. output = rnn(train_tensor) # cnn output`
  27. loss = loss_func(output, train_labels_tensor) # cross entropy loss
  28. optimizer.zero_grad() # clear gradients for this training step
  29. loss.backward() # backpropagation, compute gradients
  30. optimizer.step() # apply gradients
  31. output_sum = output
  32. # 保存模型
  33. torch.save(rnn, 'rnn1.pt')

保存完之后利用这个训练完的模型对数据进行处理:

  1. new_m = torch.load('rnn1.pt')
  2. predict = new_m(test_tensor)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/772769
推荐阅读
相关标签
  

闽ICP备14008679号