python - layout = torch.strided 是什么意思?

标签 python multidimensional-array pytorch tensor numpy-ndarray

在浏览 pytorch 文档时,我在许多函数中遇到了术语 layout = torch.strided。任何人都可以帮助我了解它在哪里使用以及如何使用。描述说这是返回张量的所需布局。布局是什么意思,有多少种布局?

torch.rand(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

最佳答案

strides 是在给定维度中从一个元素转到下一个元素所需的步数(或跳跃)。在计算机内存中,数据线性存储在连续的内存块中。我们看到的只是一个(重新)呈现。

让我们举一个张量的例子来理解这一点:

# a 2D tensor
In [62]: tensor = torch.arange(1, 16).reshape(3, 5) 

In [63]: tensor  
Out[63]: 
tensor([[ 1,  2,  3,  4,  5],
        [ 6,  7,  8,  9, 10],
        [11, 12, 13, 14, 15]])

有了这个张量,步幅为:

# get the strides
In [64]: tensor.stride() 
Out[64]: (5, 1)

这个结果元组 (5, 1) 说的是:

  • 要遍历第 0th 维/轴(Y 轴),假设我们要从 16,我们应该走5步(或跳跃)
  • 要遍历第 1st 维/轴(X 轴),假设我们要从 78,我们应该走 1 步(或跳)

元组中 51 的顺序(或索引)表示维度/轴。您还可以将需要步幅的维度作为参数传递:

# get stride for axis 0
In [65]: tensor.stride(0) 
Out[65]: 5

# get stride for axis 1
In [66]: tensor.stride(1) 
Out[66]: 1

有了这种理解,我们可能不得不问为什么在创建张量时需要这个额外参数?答案是出于效率原因。 (我们如何最有效地存储/读取/访问(稀疏)张量中的元素?)。

使用稀疏张量(大多数元素都为零的张量),所以我们不想存储这些值。我们只存储非零值及其索引。有了所需的形状,其余的值就可以用零填充,从而产生所需的稀疏张量。


要进一步阅读,以下文章可能会有所帮助:


P.S:我猜 torch.layout 文档中有一个拼写错误

Strides are a list of integers ...

tensor.stride() 返回的复合数据类型是元组,不是列表。

关于python - layout = torch.strided 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659255/

相关文章:

python - 为什么Python 3.x中的map和filter不像Python 3.x中的 'interactive'?

python - 为折线图绘制趋势线

c - 在c中排序5d数组

pytorch - "greater than"运算符 ">"对 PyTorch 张量意味着什么?

python - 在 Python 中创建元组范围的最快方法

python - 如何使用 AJAX 将图像上传到 Google 云存储?

java - tictactoe 类的二维数组有问题

c++ - 传递 const 大小的二维数组

python - pytorch使用索引列表修改数组

python - Pytorch Batchnorm 层与 Keras Batchnorm 不同