Pytorch 的随机选择? [英] Random Choice with Pytorch?
本文介绍了Pytorch 的随机选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个图片张量,想从中随机选择.我正在寻找与 np.random.choice()
等效的东西.
I have a tensor of pictures, and would like to randomly select from it. I'm looking for the equivalent of np.random.choice()
.
import torch
pictures = torch.randint(0, 256, (1000, 28, 28, 3))
假设我想要其中的 10 张图片.
Let's say I want 10 of these pictures.
推荐答案
torch
没有 np.random.choice()
的等效实现,请参阅讨论
torch
has no equivalent implementation of np.random.choice()
, see the discussion here. The alternative is indexing with a shuffled index or random integers.
- 生成n个随机索引
- 用这些索引索引你的原始张量
pictures[torch.randint(len(pictures), (10,))]
做到无需替换:
- 随机索引
- 取 n 个第一个元素
- Shuffle the index
- Take the n first elements
indices = torch.randperm(len(pictures))[:10]
pictures[indices]
阅读有关 torch.randint
和 torch.randperm
.第二个代码片段的灵感来自这个帖子 在 PyTorch 论坛中.
Read more about torch.randint
and torch.randperm
. Second code snippet is inspired by this post in PyTorch Forums.
这篇关于Pytorch 的随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文