在Pytorch中使用樣本權重(sample_weight)的正確方法
step:
1.將標簽轉換為one-hot形式。
2.將每一個one-hot標簽中的1改為預設樣本權重的值
即可在Pytorch中使用樣本權重。
eg:
對于單個樣本:loss = - Q * log(P),如下:
P = [0.1,0.2,0.4,0.3] Q = [0,0,1,0] loss = -Q * np.log(P)
增加樣本權重則為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)
對應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中使用樣本權重(sample_weight)的正確方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決python3報錯之takes?1?positional?argument?but?2?were?gi
這篇文章主要介紹了解決python3報錯之takes?1?positional?argument?but?2?were?given問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
python多進程實現(xiàn)數(shù)據(jù)共享的示例代碼
本文介紹了Python中多進程實現(xiàn)數(shù)據(jù)共享的方法,包括使用multiprocessing模塊和manager模塊這兩種方法,具有一定的參考價值,感興趣的可以了解一下2025-01-01
使用Python創(chuàng)建多功能文件管理器的代碼示例
在本文中,我們將探索一個使用Python的wxPython庫開發(fā)的文件管理器應用程序,這個應用程序不僅能夠瀏覽和選擇文件,還支持文件預覽、壓縮、圖片轉換以及生成PPT演示文稿的功能,需要的朋友可以參考下2024-08-08
Pytorch之8層神經(jīng)網(wǎng)絡實現(xiàn)Cifar-10圖像分類驗證集準確率94.71%
這篇文章主要介紹了Pytorch之8層神經(jīng)網(wǎng)絡實現(xiàn)Cifar-10圖像分類驗證集準確率94.71%問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

