百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Day234:torch中数据采样方法Sampler源码解析

ztj100 2024-11-03 16:15 13 浏览 0 评论

Sampler采样函数基类

torch.utils.data.Sampler(data_source)
  • 所有采样器的基类。
  • 每个采样器子类都必须提供一个__iter__()方法,这是一种遍历dataset元素索引的方法;以及一个返回迭代器长度的__len__()方法。
  • pytorch中提供的采样方法主要有SequentialSampler, RandomSampler, SubsetRandomSampler, WeightedRandomSampler,关键是__iter__的实现.

下面用一个简单的例子来分析各个采样函数的源码以及

import torch
from torch.utils.data.sampler import *
import numpy as np

t = np.arange(10)

SequentialSampler顺序采样

torch.utils.data.SequentialSampler(data_source)

其中__iter__为:

iter(range(len(self.data_source)))

参数

  • data_source为数据集

所以SequentialSampler的功能是顺序逐个采样数据

for i in SequentialSampler(t):
    print(i,end=',')

输出:

0,1,2,3,4,5,6,7,8,9,
1

RandomSampler随机采样

torch.utils.data.RandomSampler(data_source, replacement=False, num_samples=None)

其中__iter__为:

n = len(self.data_source)
if self.replacement:
    return iter(torch.randint(high=n, 
                              size=(self.num_samples,),
                              dtype=torch.int64).tolist())
return iter(torch.randperm(n).tolist())
123456

参数

  • data_source为数据集
  • replacement:是否为有放回取样

RandomSamplerreplacement开关关闭时,返回原始数据集长度下标数组随机打乱后采样值, 而当replacment开关打开后,则根据num_samples长度来生成采样序列长度。
具体可见如下代码,在replacement=False时,RandomSampler对数组t下标随机打乱输出,迭代器长度与源数据长度一致。
replacement=True并设定num_samples=20,这时迭代器长度大于源数据,故会出现重复值。

t = np.arange(10)
for i in RandomSampler(t):
    print(i,end=',')

输出:

4,5,6,0,8,1,7,9,2,3,

输入

for i in RandomSampler(t,replacement=True,num_samples=20):
    print(i,end=',')

输出:

8,0,4,6,4,0,1,5,3,1,6,8,9,0,4,7,0,8,7,4,

SubsetRandomSampler索引随机采样

torch.utils.data.SubsetRandomSampler(indices)

其中__iter__为:

(self.indices[i] for i in torch.randperm(len(self.indices)))

其中

  • torch.randperm对数组随机排序
  • indices为给定的下标数组

所以SubsetRandomSampler的功能是在给定一个数据集下标后,对该下标数组随机排序,然后不放回取样

for i in SubsetRandomSampler(t):
    print(i,end=',')

输出:

2,6,1,7,4,3,0,5,8,9,

WeightedRandomSampler加权随机采样

torch.utils.data.WeightedRandomSampler(weights, num_samples, replacement=True)

其中__iter__为:

iter(torch.multinomial(self.weights, self.num_samples, self.replacement).tolist())

其中

  • weights为index权重,权重越大的取到的概率越高
  • num_samples: 生成的采样长度
  • replacement:是否为有放回取样
  • multinomial: 伯努利随机数生成函数,也就是根据概率设定生成{0,1,…,n}
weights = torch.tensor([0, 10, 3, 0], dtype=torch.float)
torch.multinomial(weights,1,replacement=False)

输出:

tensor([1])
weights = torch.tensor([0, 10, 3, 0], dtype=torch.float)
torch.multinomial(weights,2,replacement=False)

输出:

tensor([2, 1])
weights = torch.tensor([0, 10, 3, 0], dtype=torch.float)
torch.multinomial(weights,3,replacement=False)

输出:

---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

<ipython-input-41-c641212fcbc8> in <module>
      1 weights = torch.tensor([0, 10, 3, 0], dtype=torch.float)
----> 2 torch.multinomial(weights,3,replacement=False)
RuntimeError: invalid argument 2: invalid multinomial distribution (with replacement=False, not enough non-negative category to sample) at /opt/conda/conda-bld/pytorch_1565287148058/work/aten/src/TH/generic/THTensorRandom.cpp:378
weights = torch.tensor([0, 10, 3, 0], dtype=torch.float)
torch.multinomial(weights,2,replacement=True)

输出:

tensor([1, 1])
weights = torch.tensor([1, 10, 3, 0], dtype=torch.float)
torch.multinomial(weights,10,replacement=True)

输出:

tensor([1, 1, 0, 0, 1, 0, 2, 1, 2, 1])

通过上面几个例子可以看出,权重值为0的index不会被取到。

当不放回取样时,replacement=False,若num_samplers小于输入数组中权重非零值个数,那么非零权重大小基本不起什么作用,反正所有的值都会取到一次

当放回取样时,权重越大的取到的概率越高。

BatchSampler批采样

torch.utils.data.BatchSampler(sampler, batch_size, drop_last)

其中__iter__为:

batch = []
for idx in self.sampler:
    batch.append(idx)
    if len(batch) == self.batch_size:
        yield batch
        batch = []
if len(batch) > 0 and not self.drop_last:
    yield batch

其中

  • drop_last为布尔类型值,当其为真时,如果数据集长度不是batch_size整数倍时,最后一批数据将会丢弃。
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

代码中例子很清晰,数据总长度为10,如果drop_last设置为False,那么最后余下的一个作为新的batch.

原文:https://blog.csdn.net/u010137742/article/details/100996937

相关推荐

Whoosh,纯python编写轻量级搜索工具

引言在许多应用程序中,搜索功能是至关重要的。Whoosh是一个纯Python编写的轻量级搜索引擎库,可以帮助我们快速构建搜索功能。无论是在网站、博客还是本地应用程序中,Whoosh都能提供高效的全文搜...

如何用Python实现二分搜索算法(python二分法查找代码)

如何用Python实现二分搜索算法二分搜索(BinarySearch)是一种高效的查找算法,适用于在有序数组中快速定位目标值。其核心思想是通过不断缩小搜索范围,每次将问题规模减半,时间复杂度为(O...

路径扫描 -- dirsearch(路径查找器怎么使用)

外表干净是尊重别人,内心干净是尊重自己,干净,在今天这个时代,应该是一种极高的赞美和珍贵。。。----网易云热评一、软件介绍Dirsearch是一种命令行工具,可以强制获取web服务器中的目录和文件...

78行Python代码帮你复现微信撤回消息!

来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。...

从零开始学习 Python!2《进阶知识》 Python进阶之路

欢迎来到Python学习的进阶篇章!如果你说已经掌握了基础语法,那么这篇就是你开启高手之路的大门。我们将一起探讨面向对象编程...

白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件

一、背景介绍...

Python之txt数据预定替换word预定义定位标记生成word报告(四)

续接Python之txt数据预定替换word预定义定位标记生成word报告(一)https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=748...

假期苦短,我用Python!这有个自动回复拜年信息的小程序

...

Python——字符串和正则表达式中的反斜杠(&#39;\&#39;)问题详解

在本篇文章里小编给大家整理的是关于Python字符串和正则表达式中的反斜杠('\')问题以及相关知识点,有需要的朋友们可以学习下。在Python普通字符串中在Python中,我们用'\'来转义某些普通...

Python re模块:正则表达式综合指南

Python...

Python中re模块详解(rem python)

在《...

python之re模块(python re模块sub)

re模块一.re模块的介绍1.什么是正则表达式"定义:正则表达式是一种对字符和特殊字符操作的一种逻辑公式,从特定的字符中,用正则表达字符来过滤的逻辑。(也是一种文本模式;)2、正则表达式可以帮助我们...

MySQL、PostgreSQL、SQL Server 数据库导入导出实操全解

在数字化时代,数据是关键资产,数据库的导入导出操作则是连接数据与应用场景的桥梁。以下是常见数据库导入导出的实用方法及代码,包含更多细节和特殊情况处理,助你应对各种实际场景。一、MySQL数据库...

Zabbix监控系统系列之六:监控 mysql

zabbix监控mysql1、监控规划在创建监控项之前要尽量考虑清楚要监控什么,怎么监控,监控数据如何存储,监控数据如何展现,如何处理报警等。要进行监控的系统规划需要对Zabbix很了解,这里只是...

mysql系列之一文详解Navicat工具的使用(二)

本章内容是系列内容的第二部分,主要介绍Navicat工具的使用。若查看第一部分请见:...

取消回复欢迎 发表评论: