欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pytorch怎樣保存訓(xùn)練好的模型

 更新時(shí)間:2023年02月20日 09:55:33   作者:comli_cn  
這篇文章主要介紹了Pytorch怎樣保存訓(xùn)練好的模型問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

為什么要保存和加載模型

用數(shù)據(jù)對(duì)模型進(jìn)行訓(xùn)練后得到了比較理想的模型,但在實(shí)際應(yīng)用的時(shí)候不可能每次都先進(jìn)行訓(xùn)練然后再使用,所以就得先將之前訓(xùn)練好的模型保存下來(lái),然后在需要用到的時(shí)候加載一下直接使用。

模型的本質(zhì)是一堆用某種結(jié)構(gòu)存儲(chǔ)起來(lái)的參數(shù),所以在保存的時(shí)候有兩種方式

  • 一種方式是直接將整個(gè)模型保存下來(lái),之后直接加載整個(gè)模型,但這樣會(huì)比較耗內(nèi)存;
  • 另一種是只保存模型的參數(shù),之后用到的時(shí)候再創(chuàng)建一個(gè)同樣結(jié)構(gòu)的新模型,然后把所保存的參數(shù)導(dǎo)入新模型。

兩種情況的實(shí)現(xiàn)方法

(1)只保存模型參數(shù)字典(推薦)

#保存
torch.save(the_model.state_dict(), PATH)
#讀取
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

(2)保存整個(gè)模型

#保存
torch.save(the_model, PATH)
#讀取
the_model = torch.load(PATH)

只保存模型參數(shù)的情況(例子)

pytorch會(huì)把模型的參數(shù)放在一個(gè)字典里面,而我們所要做的就是將這個(gè)字典保存,然后再調(diào)用。

比如說(shuō)設(shè)計(jì)一個(gè)單層LSTM的網(wǎng)絡(luò),然后進(jìn)行訓(xùn)練,訓(xùn)練完之后將模型的參數(shù)字典進(jìn)行保存,保存為同文件夾下面的rnn.pt文件:

class LSTM(nn.Module):
? ? def __init__(self, input_size, hidden_size, num_layers):
? ? ? ? super(LSTM, self).__init__()
? ? ? ? self.hidden_size = hidden_size
? ? ? ? self.num_layers = num_layers
? ? ? ? self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
? ? ? ? self.fc = nn.Linear(hidden_size, 1)

? ? def forward(self, x):
? ? ? ? # Set initial states
? ? ? ? h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)?
? ? ? ? ?# 2 for bidirection
? ? ? ? c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
? ? ? ? # Forward propagate LSTM
? ? ? ? out, _ = self.lstm(x, (h0, c0)) ?
? ? ? ? # out: tensor of shape (batch_size, seq_length, hidden_size*2)
? ? ? ? out = self.fc(out)
? ? ? ? return out


rnn = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)

# optimize all cnn parameters
optimizer = torch.optim.Adam(rnn.parameters(), lr=0.001) ?
# the target label is not one-hotted
loss_func = nn.MSELoss() ?

for epoch in range(1000):
? ? output = rnn(train_tensor) ?# cnn output`
? ? loss = loss_func(output, train_labels_tensor) ?# cross entropy loss
? ? optimizer.zero_grad() ?# clear gradients for this training step
? ? loss.backward() ?# backpropagation, compute gradients
? ? optimizer.step() ?# apply gradients
? ? output_sum = output


# 保存模型
torch.save(rnn.state_dict(), 'rnn.pt')

保存完之后利用這個(gè)訓(xùn)練完的模型對(duì)數(shù)據(jù)進(jìn)行處理:

# 測(cè)試所保存的模型
m_state_dict = torch.load('rnn.pt')
new_m = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)
new_m.load_state_dict(m_state_dict)
predict = new_m(test_tensor)

這里做一下說(shuō)明,在保存模型的時(shí)候rnn.state_dict()表示rnn這個(gè)模型的參數(shù)字典,在測(cè)試所保存的模型時(shí)要先將這個(gè)參數(shù)字典加載一下

m_state_dict = torch.load('rnn.pt');

然后再實(shí)例化一個(gè)LSTM對(duì)像,這里要保證傳入的參數(shù)跟實(shí)例化rnn是傳入的對(duì)象時(shí)一樣的,即結(jié)構(gòu)相同

new_m = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device);

下面是給這個(gè)新的模型傳入之前加載的參數(shù)

new_m.load_state_dict(m_state_dict);

最后就可以利用這個(gè)模型處理數(shù)據(jù)了

predict = new_m(test_tensor)

保存整個(gè)模型的情況(例子)

class LSTM(nn.Module):
? ? def __init__(self, input_size, hidden_size, num_layers):
? ? ? ? super(LSTM, self).__init__()
? ? ? ? self.hidden_size = hidden_size
? ? ? ? self.num_layers = num_layers
? ? ? ? self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
? ? ? ? self.fc = nn.Linear(hidden_size, 1)

? ? def forward(self, x):
? ? ? ? # Set initial states
? ? ? ? h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) ?# 2 for bidirection
? ? ? ? c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)

? ? ? ? # Forward propagate LSTM
? ? ? ? out, _ = self.lstm(x, (h0, c0)) ?# out: tensor of shape (batch_size, seq_length, hidden_size*2)
? ? ? ? # print("output_in=", out.shape)
? ? ? ? # print("fc_in_shape=", out[:, -1, :].shape)
? ? ? ? # Decode the hidden state of the last time step
? ? ? ? # out = torch.cat((out[:, 0, :], out[-1, :, :]), axis=0)
? ? ? ? # out = self.fc(out[:, -1, :]) ?# 取最后一列為out
? ? ? ? out = self.fc(out)
? ? ? ? return out


rnn = LSTM(input_size=1, hidden_size=10, num_layers=2).to(device)
print(rnn)


optimizer = torch.optim.Adam(rnn.parameters(), lr=0.001) ?# optimize all cnn parameters
loss_func = nn.MSELoss() ?# the target label is not one-hotted

for epoch in range(1000):
? ? output = rnn(train_tensor) ?# cnn output`
? ? loss = loss_func(output, train_labels_tensor) ?# cross entropy loss
? ? optimizer.zero_grad() ?# clear gradients for this training step
? ? loss.backward() ?# backpropagation, compute gradients
? ? optimizer.step() ?# apply gradients
? ? output_sum = output


# 保存模型

torch.save(rnn, 'rnn1.pt')

保存完之后利用這個(gè)訓(xùn)練完的模型對(duì)數(shù)據(jù)進(jìn)行處理:

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

參考pytorch的官方文檔

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論