首页 > 解决方案 > 矩阵乘以 Keras 中的矩阵列表

问题描述

我正在尝试在 Keras 中添加我自己定义的层。在层中,我想将一个大小为 (30, 20) 的矩阵与输入相乘,该输入是一个大小为 (?, 20, 40) 的矩阵列表。这 ”?” 取决于输入批量大小。

我想要 (30, 20) * (?, 20, 40) -> (?, 30, 40)。

我尝试使用 K.dot() 和 K.dot_batch() 但它们没有用。有没有办法在 Keras 中做到这一点?

提前致谢。

标签: pythonkerasmatrix-multiplication

解决方案


我猜想 (30, 20) 矩阵是层的权重,并且您想计算 40 个矩阵中的每一个的点积。即令X为 (?, 20, 40)-张量,并且W为 (30, 20)-矩阵, Y[:, :, k] = Dot(X[:, :, k], W)(为了尺寸兼容性而进行适当的转置)。

如果这是您所做的,您可以通过组合PermuteTimeDistributed来实现它。

from keras.layers import Input, Dense, Permute, TimeDistributed
from keras.models import Model

x = Input((20, 40))
y = Permute((2,1))(x)
y = TimeDistributed(Dense(30))(y)
y = Permute((2,1))(y)
model = Model(inputs=x, outputs=y)
model.summary()

产量:

Layer (type)                 Output Shape              Param #   
=================================================================
input_13 (InputLayer)        (None, 20, 40)            0         
_________________________________________________________________
permute_15 (Permute)         (None, 40, 20)            0         
_________________________________________________________________
time_distributed_9 (TimeDist (None, 40, 30)            630       
_________________________________________________________________
permute_16 (Permute)         (None, 30, 40)            0         
=================================================================
Total params: 630
Trainable params: 630
Non-trainable params: 0

如果您仍然需要实现自定义层,一个很好的参考将是TimeDistributed源代码(https://github.com/keras-team/keras/blob/master/keras/layers/wrappers.py#L114)。

该方法的草图将是:

  1. 置换为 (n, 40, 20)
  2. 展平到 (n*40, 20) 维度
  3. 取点积 -> (n*40, 30)
  4. 重塑回 (n, 40, 30)
  5. 置换为 (n, 30, 40)

推荐阅读