首页 > 解决方案 > 如何制作火炬张量?

问题描述

我想制作一个仅由 1 或 -1 组成的火炬张量。

我只是尝试使用torch.empty()and torch.randn()

tmp = torch.randint(low=0, high=2, size=(4, 4))
tmp[tmp==0] = -1
tmp
>> tensor([[ 1, -1, -1,  1],
           [-1,  1,  1, -1],
           [-1, -1,  1,  1],
           [-1,  1, -1,  1]])

但是,我不知道哪种方法在时间上最有效。

我想把这段代码尽可能地写成一行,因为这段代码位于__init__ ()

标签: pytorchtensor

解决方案


为什么不:

tmp = -1 + 2 * torch.randint(low=0, high=2, size=(4, 4))

推荐阅读