在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微信公众号之关注公众号自动回复

我们知道一旦使用开发者模式,我们就无法使用公众号平台中的自动回复功能,也就是关注自动回复功能只有自己写才可以。 如图所示,我们无法直接使用此功能。 那么接着上一个博客,我们完成了关键词...

Python input函数使用实例解析

这篇文章主要介绍了Python input函数使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 函数定义 def inpu...

Python字节单位转换实例

我就废话不多说了,直接上代码! from enum import Enum class Values(): values={'B':1} @staticmethod...

Python中函数参数设置及使用的学习笔记

Python中函数参数设置及使用的学习笔记

一、参数和共享引用: In [56]: def changer(a,b): ....: a=2 ....: b[0]='spam' ....: In [57...

Python使用combinations实现排列组合的方法

好久没有写博客了!昨天小牛在上海举办了牛友见面会,现场优惠还是比较大,心仪已久加上一时脑热就入手了。以为会有多么开心,其实目前最大的感受就是焦虑!担心电动车被偷,担心电池被偷,担心路上突...