在Pytorch中使用样本权重(sample_weight)的正确方法

yipeiwu_com6年前Python基础

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的多分类交叉熵损失函数如下:

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)的正确方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python使用正则表达式匹配字符串开头并打印示例

本文实例讲述了python使用正则表达式匹配字符串开头并打印的方法。分享给大家供大家参考,具体如下: import re s="name=z1hangshan username=ff...

python实现连连看辅助(图像识别)

个人兴趣,用python实现连连看的辅助程序,总结实现过程及知识点。 总体思路 1、获取连连看程序的窗口并前置 2、游戏界面截图,将每个一小图标切图,并形成由小图标组成的二维列表 3、对...

python中时间转换datetime和pd.to_datetime详析

python中时间转换datetime和pd.to_datetime详析

前言 我们在python对数据进行操作时,经常会选取某一时间段的数据进行分析。这里为大家介绍两个我经常用到的用来选取某一时间段数据的函数:datetime( )和pd.to_dateti...

python和shell获取文本内容的方法

这两天搞脚本,花费不少时间。 Python和Shell都可以获取文本内容,网上许多资料介绍的都不具体。简单的使用Python和Shell写了脚本。 做一些笔记沉淀一下。 1、Python...

Python利用Beautiful Soup模块创建对象详解

安装 通过 pip 安装 Beautiful Soup 模块:pip install beautifulsoup4 。 还可以使用 PyCharm IDE 来写代码,在 PyChar...