在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设计】。

相关文章

使用pyqt 实现重复打开多个相同界面

一般采用的方法: self.window = Qdialog() # 实例化 self.window.show() # 显示界面 用这种方法只能打开一个界面,self使得默认只...

python针对不定分隔符切割提取字符串的方法

问题:我们需要在散沙一般的数据中提取出字符,分隔符不止一个,而且还有不少空格,比如: 原字符串如下: 'asd ff gg; asd , foo| og ' 我们需要删除上面的,;...

基于Python __dict__与dir()的区别详解

Python下一切皆对象,每个对象都有多个属性(attribute),Python对属性有一套统一的管理方案。 __dict__与dir()的区别: dir()是一个函数,返回的是lis...

深入学习python多线程与GIL

python 多线程效率 在一台8核的CentOS上,用python 2.7.6程序执行一段CPU密集型的程序。 import time def fun(n):#CPU密集型的程序...

老生常谈Python序列化和反序列化

通过将对象序列化可以将其存储在变量或者文件中,可以保存当时对象的状态,实现其生命周期的延长。并且需要时可以再次将这个对象读取出来。Python中有几个常用模块可实现这一功能。 pickl...