两个4D垫mul numpy,应预期输出5D

时间:2018-11-30 19:18:52

标签: numpy tensorflow 4d

我想用3个滤镜将注意力权重(5个标签)应用于我的卷积,有什么可以帮助我做如何应用matmul的。如果您也提供张量流版本,将不胜感激。

import numpy as np
conv = np.random.randint(10,size=[1,3,2,2], dtype=int) # [batches,filter,row,col]
attention = np.random.randint(5,size=[1,5,2,1], dtype=int) # [batches,label,row,col]
np.matmul(conv,attention).shape # expected output size [1,3,5,2,1] [batches,filter,label,row,col]

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (1,3,2,2)->(1,3,2,newaxis,2) (1,5,2,1)->(1,5,newaxis,1,2) 

1 个答案:

答案 0 :(得分:2)

根据matmul的文档:

  

如果任一参数为N-D,N> 2,则将其视为位于最后两个索引中并相应广播的一组矩阵。

  

将矩阵堆栈一起广播,就好像矩阵是元素一样。

这意味着,在您的情况下,除最后两个维度以外的所有维度都需要匹配。如果希望输出形状为js-implementation,则需要在每个数组中显式插入一个空轴。您可以在创建时执行此操作:

import numpy as np
conv = np.random.randint(10, size=[1, 3, 1, 2, 2], dtype=int)
attention = np.random.randint(5, size=[1, 1, 5,2,1], dtype=int)
np.matmul(conv,attention).shape

或者,您可以通过将视图与适当的插入物相乘来使插入物明确:

1, 3, 5, 2, 1