基于MSELoss()與CrossEntropyLoss()的區(qū)別詳解
基于pytorch來講
MSELoss()多用于回歸問題,也可以用于one_hotted編碼形式,
CrossEntropyLoss()名字為交叉熵損失函數,不用于one_hotted編碼形式
MSELoss()要求batch_x與batch_y的tensor都是FloatTensor類型
CrossEntropyLoss()要求batch_x為Float,batch_y為LongTensor類型
(1)CrossEntropyLoss() 舉例說明:
比如二分類問題,最后一層輸出的為2個值,比如下面的代碼:
class CNN (nn.Module ) : def __init__ ( self , hidden_size1 , output_size , dropout_p) : super ( CNN , self ).__init__ ( ) self.hidden_size1 = hidden_size1 self.output_size = output_size self.dropout_p = dropout_p self.conv1 = nn.Conv1d ( 1,8,3,padding =1) self.fc1 = nn.Linear (8*500, self.hidden_size1 ) self.out = nn.Linear (self.hidden_size1,self.output_size ) def forward ( self , encoder_outputs ) : cnn_out = F.max_pool1d ( F.relu (self.conv1(encoder_outputs)),2) cnn_out = F.dropout ( cnn_out ,self.dropout_p) #加一個dropout cnn_out = cnn_out.view (-1,8*500) output_1 = torch.tanh ( self.fc1 ( cnn_out ) ) output = self.out ( ouput_1) return output
最后的輸出結果為:
上面一個tensor為output結果,下面為target,沒有使用one_hotted編碼。
訓練過程如下:
cnn_optimizer = torch.optim.SGD(cnn.parameters(),learning_rate,momentum=0.9,\ weight_decay=1e-5) criterion = nn.CrossEntropyLoss() def train ( input_variable , target_variable , cnn , cnn_optimizer , criterion ) : cnn_output = cnn( input_variable ) print(cnn_output) print(target_variable) loss = criterion ( cnn_output , target_variable) cnn_optimizer.zero_grad () loss.backward( ) cnn_optimizer.step( ) #print('loss: ',loss.item()) return loss.item() #返回損失
說明CrossEntropyLoss()是output兩位為one_hotted編碼形式,但target不是one_hotted編碼形式。
(2)MSELoss() 舉例說明:
網絡結構不變,但是標簽是one_hotted編碼形式。下面的圖僅做說明,網絡結構不太對,出來的預測也不太對。
如果target不是one_hotted編碼形式會報錯,報的錯誤如下。
目前自己理解的兩者的區(qū)別,就是這樣的,至于多分類問題是不是也是樣的有待考察。
以上這篇基于MSELoss()與CrossEntropyLoss()的區(qū)別詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python 3.6 中使用pdfminer解析pdf文件的實現
這篇文章主要介紹了Python 3.6 中使用pdfminer解析pdf文件的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09python創(chuàng)建ArcGIS shape文件的實現
今天小編就為大家分享一篇python創(chuàng)建ArcGIS shape文件的實現,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12PyQt5的PyQtGraph實踐系列3之實時數據更新繪制圖形
這篇文章主要介紹了PyQt5的PyQtGraph實踐系列3之實時數據更新繪制圖形,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05