python - 矩阵乘以 Keras 中的矩阵列表
问题描述
我正在尝试在 Keras 中添加我自己定义的层。在层中,我想将一个大小为 (30, 20) 的矩阵与输入相乘,该输入是一个大小为 (?, 20, 40) 的矩阵列表。这 ”?” 取决于输入批量大小。
我想要 (30, 20) * (?, 20, 40) -> (?, 30, 40)。
我尝试使用 K.dot() 和 K.dot_batch() 但它们没有用。有没有办法在 Keras 中做到这一点?
提前致谢。
解决方案
我猜想 (30, 20) 矩阵是层的权重,并且您想计算 40 个矩阵中的每一个的点积。即令X
为 (?, 20, 40)-张量,并且W
为 (30, 20)-矩阵,
Y[:, :, k] = Dot(X[:, :, k], W)
(为了尺寸兼容性而进行适当的转置)。
如果这是您所做的,您可以通过组合Permute和TimeDistributed来实现它。
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)。
该方法的草图将是:
- 置换为 (n, 40, 20)
- 展平到 (n*40, 20) 维度
- 取点积 -> (n*40, 30)
- 重塑回 (n, 40, 30)
- 置换为 (n, 30, 40)
推荐阅读
- java - 无法运行 Spring Boot 应用程序:osboot.SpringApplication 应用程序运行失败
- amadeus - 航班报价响应中缺少额外行李信息
- python - 从python中的不规则字典列表创建CSV
- javascript - 制表器 - 如何在基于道具从数据库中获取数据时显示加载指示器?
- node.js - 通过从 Node.js 后端检索在 React 前端显示像谷歌驱动器这样的图像
- php - 如何阻止对我的网站的未知呼叫?
- react-native - React Native 漏斗图
- node.js - '在androidjs中没有定义的资源
- apache-spark - 如何实时调整 Spark 作业?
- powershell - 查找每月的第三个星期六