Pytorch 的随机选择? [英] Random Choice with Pytorch?

查看:15
本文介绍了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.

  1. 生成n个随机索引
  2. 用这些索引索引你的原始张量

pictures[torch.randint(len(pictures), (10,))]  

做到无需替换:

  1. 随机索引
  2. n 个第一个元素
  1. Shuffle the index
  2. Take the n first elements

indices = torch.randperm(len(pictures))[:10]

pictures[indices]

阅读有关 torch.randinttorch.randperm.第二个代码片段的灵感来自这个帖子 在 PyTorch 论坛中.

Read more about torch.randint and torch.randperm. Second code snippet is inspired by this post in PyTorch Forums.

这篇关于Pytorch 的随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆