【问题标题】:How can I create a tensor of batch batch_size of uniformly distributed values between -1 and 1?如何在 -1 和 1 之间创建均匀分布值的批量 batch_size 张量?
【发布时间】:2021-01-16 00:53:20
【问题描述】:

标题几乎概括了它,我正在尝试实现一个 GAN: 如何使用 pytorch 创建一个在 -1 和 1 之间均匀分布的值的批量 batch_size 的张量?

def create_latent_batch_vectors(batch_size, latent_vector_size, device):
'''
The function creates a random batch of latent vectors with random values 
distributed uniformly between -1 and 1. 
Finally, it moves the tensor to the given ```device``` (cpu or gpu).
The output should have a shape of [batch_size, latent_vector_size].
'''
# maybe torch.distributions.uniform.Uniform() somehow?
return z.to(device)

谢谢!

【问题讨论】:

    标签: computer-vision pytorch


    【解决方案1】:

    让我们首先定义一个均匀分布,低范围为-1,高范围为+1

    dist = torch.distributions.uniform.Uniform(-1,1)
    sample_shape = torch.Size([2])
    dist.sample(sample_shape)
    >tensor([0.7628, 0.3497])
    

    这是一个形状为 2 (sample_shape) 的张量。它没有batch_shape。让我们检查一下:

    dist.batch_shape
    >torch.Size([])
    

    现在让我们使用expand。它本质上是通过扩展batch_shape 创建一个新的分发实例。

    new_batch_shape = torch.Size([5])   # batch_shape of [5]
    expanded_dist = dist.expand(new_batch_shape)
    

    检查:

    expanded_dist.batch_shape
    >torch.Size([5])
    

    创建一个形状为 [batch_size, sample_shape] 的张量

    expanded_dist.sample(sample_shape)
    >tensor([[0.1592, 0.3404, 0.3520, 0.3038, 0.0393],
            [0.9368, 0.0108, 0.5836, 0.6156, 0.6704]])
    

    三种形状定义如下:

    • 样本形状描述了从分布中独立、同分布的抽取。
    • Batch shape 描述独立的、非同分布的绘制。即,我们可能有一组(不同的) 参数化到相同的分布。这使常见的 一批示例的机器学习用例,每个示例由 它自己的分布。
    • 事件形状从分布中描述单次绘制(事件空间)的形状;它可能依赖于各个维度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2022-09-23
      相关资源
      最近更新 更多