在Pytorch中使用樣本權(quán)重(sample_weight)的正確方法
step:
1.將標(biāo)簽轉(zhuǎn)換為one-hot形式。
2.將每一個(gè)one-hot標(biāo)簽中的1改為預(yù)設(shè)樣本權(quán)重的值
即可在Pytorch中使用樣本權(quán)重。
eg:
對(duì)于單個(gè)樣本: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)
對(duì)應(yīng)one-target的多分類交叉熵?fù)p失函數(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)的正確方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python shell根據(jù)ip獲取主機(jī)名代碼示例
這篇文章主要介紹了python shell根據(jù)ip獲取主機(jī)名代碼示例,涉及用socket模塊和shell中hostname命令獲取等相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
解決python3報(bào)錯(cuò)之takes?1?positional?argument?but?2?were?gi
這篇文章主要介紹了解決python3報(bào)錯(cuò)之takes?1?positional?argument?but?2?were?given問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
Python浮點(diǎn)數(shù)四舍五入問(wèn)題的分析與解決方法
這篇文章主要給大家介紹了關(guān)于Python中浮點(diǎn)數(shù)四舍五入問(wèn)題的分析與解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
python多進(jìn)程實(shí)現(xiàn)數(shù)據(jù)共享的示例代碼
本文介紹了Python中多進(jìn)程實(shí)現(xiàn)數(shù)據(jù)共享的方法,包括使用multiprocessing模塊和manager模塊這兩種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2025-01-01
使用Python創(chuàng)建多功能文件管理器的代碼示例
在本文中,我們將探索一個(gè)使用Python的wxPython庫(kù)開(kāi)發(fā)的文件管理器應(yīng)用程序,這個(gè)應(yīng)用程序不僅能夠?yàn)g覽和選擇文件,還支持文件預(yù)覽、壓縮、圖片轉(zhuǎn)換以及生成PPT演示文稿的功能,需要的朋友可以參考下2024-08-08
Pytorch之8層神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)Cifar-10圖像分類驗(yàn)證集準(zhǔn)確率94.71%
這篇文章主要介紹了Pytorch之8層神經(jīng)網(wǎng)絡(luò)實(shí)現(xiàn)Cifar-10圖像分類驗(yàn)證集準(zhǔn)確率94.71%問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03

