在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法
step:
1.將標簽轉(zhuǎn)換為one-hot形式。
2.將每一個one-hot標簽中的1改為預(yù)設(shè)樣本權(quán)重的值
即可在Pytorch中使用樣本權(quán)重。
eg:
對于單個樣本:loss = - Q * log(P),如下:
P = [0.1,0.2,0.4,0.3] Q = [0,0,1,0] loss = -Q * np.log(P)
增加樣本權(quán)重則為loss = - Q * log(P) *sample_weight
P = [0.1,0.2,0.4,0.3] Q = [0,0,sample_weight,0] loss_samle_weight = -Q * np.log(P)
在pytorch中示例程序
train_data = np.load(open('train_data.npy','rb')) train_labels = [] for i in range(8): train_labels += [i] *100 train_labels = np.array(train_labels) train_labels = to_categorical(train_labels).astype("float32") sample_1 = [random.random() for i in range(len(train_data))] for i in range(len(train_data)): floor = i / 100 train_labels[i][floor] = sample_1[i] train_data = torch.from_numpy(train_data) train_labels = torch.from_numpy(train_labels) dataset = dataf.TensorDataset(train_data,train_labels) trainloader = dataf.DataLoader(dataset, batch_size=batch_size, shuffle=True)
對應(yīng)one-target的多分類交叉熵損失函數(shù)如下:
def my_loss(outputs, targets): output2 = outputs - torch.max(outputs, 1, True)[0] P = torch.exp(output2) / torch.sum(torch.exp(output2), 1,True) + 1e-10 loss = -torch.mean(targets * torch.log(P)) return loss
以上這篇在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法
今天小編就為大家分享一篇tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06使用Python pyWinAuto庫自動化Windows任務(wù)的示例代碼
pywinauto是Python的一個強大的自動化庫,它可以用于控制Windows應(yīng)用程序的用戶界面,本文將詳細介紹pywinauto庫的安裝、基本用法和高級應(yīng)用,以便你能夠更好地了解如何使用它來自動化Windows應(yīng)用程序,文中有詳細的代碼示例供大家參考,需要的朋友可以參考下2023-11-11Python實現(xiàn)基于多線程、多用戶的FTP服務(wù)器與客戶端功能完整實例
這篇文章主要介紹了Python實現(xiàn)基于多線程、多用戶的FTP服務(wù)器與客戶端功能,結(jié)合完整實例形式分析了Python多線程、多用戶FTP服務(wù)器端與客戶端相關(guān)實現(xiàn)技巧與注意事項,需要的朋友可以參考下2017-08-08tensorflow入門:TFRecordDataset變長數(shù)據(jù)的batch讀取詳解
今天小編就為大家分享一篇tensorflow入門:TFRecordDataset變長數(shù)據(jù)的batch讀取詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01python操作攝像頭截圖實現(xiàn)遠程監(jiān)控的例子
這篇文章主要介紹了python操作攝像頭截圖實現(xiàn)遠程監(jiān)控的例子,例子中包含了控制攝像頭、寫入Windows注冊表方法等,需要的朋友可以參考下2014-03-03