Numpy.tensordot 给出错误"tuple index out of range"



我正在尝试创建PyTorch的conv2d函数的矢量化版本。在代码中,我有一个表示内核大小的视图的矩阵,我需要将它与过滤器权重进行点积。代码如下所示

blocks # shape: (a, b, c, d, e, f)
filters # shape: (d, e, f, g)
# goal output size: (a, b, c, g)
return np.tensordot(blocks, filters, axes=([3, 4, 5], [0, 1, 2]))

这给了我错误&;IndexError:元组索引超出范围&;,我不太确定为什么。我该如何着手解决这个问题?(可能使用np。

不是最通用的测试,但足以测试基本参数:

In [85]: blocks = np.ones((2,2,2,3,3,3)); filters=np.ones((3,3,3,4))
In [86]: res = np.tensordot(blocks, filters, axes=([3, 4, 5], [0, 1, 2]))
In [87]: res.shape
Out[87]: (2, 2, 2, 4)

tensordot将参数重塑为(2,2,2,27)和(27,4),并执行dotres的A元素为27。

带有故意错误:

In [89]: res = np.tensordot(blocks, filters, axes=([3, 4, 6], [0, 1, 2]))
Traceback (most recent call last):
File "<ipython-input-89-370e50bf3a02>", line 1, in <module>
res = np.tensordot(blocks, filters, axes=([3, 4, 6], [0, 1, 2]))
File "<__array_function__ internals>", line 5, in tensordot
File "/usr/local/lib/python3.8/dist-packages/numpy/core/numeric.py", line 1102, in tensordot
if as_[axes_a[k]] != bs[axes_b[k]]:
IndexError: tuple index out of range

最新更新