r - R- 具有权重约束的自定义 Keras 层
问题描述
我正在尝试在 R 中编写一个具有可训练权重的自定义 Keras 层,其中:
- 接受输入向量 x 并返回
exp(A * X*A)
$A$ 是对角线且可训练的值。
其中exp是矩阵指数映射。
解决方案
请注意,了解批量大小的位置非常重要,并且层不能具有基于批量大小的权重(除非您使用batch_shape
或batch_input_shape
代替定义输入shape
- 这将迫使您使用固定的批量大小在模型中)。由于批量大小通常用于“个体”和“独立”样本,因此在操作和混合样本中使用批量大小是不健康的!
也就是说,我假设X
这里有 shape (batch, dim, dim)
,因此A
会有 shape (dim, dim)
。
为此,您可以构建一个自定义层,例如:https ://tensorflow.rstudio.com/guide/keras/custom_layers/
哪里build
会有kernel
( A
) 的形状(1, dim, 1)
——
build = function(input_shape) {
self$kernel <- self$add_weight(
name = 'kernel',
shape = list(1,input_shape[[2]], 1),
initializer = initializer_random_normal(), #you may choose different initializers
trainable = TRUE
)
},
并且 call 将使用数学技巧来模拟对角线。
请注意,如果A
是对角线,则结果A x X x A
将是B*X
(elementwise),其中B
是:
#supposing A has the elements [a, b, c, ...] in the diagonals,
B is:
[ [aa, ab, ac, ...],
[ab, bb, bc, ...],
[ac, bc, cc, ...],
...
]
因此,我们不会使用对角线,而是使用元素乘法的广播技巧:
call = function(x, mask = NULL) {
kernelTransposed <- tf$reshape(self$kernel, shape(1L, 1L, -1L)) #(1, 1, dim)
B <- self$kernel * kernelTransposed #(1, dim, dim)
tf$math$exp(x * B)
},
输出形状不变:
compute_output_shape = function(input_shape) {
input_shape
}
推荐阅读
- node.js - 文件替换不适用于 e2e 测试
- swift - 从函数返回符合 CaseIterable 的通用类型
- bash - 每个日期创建一个文件,仅包含与该日期对应的文件名
- c# - 无法使用 WebBrowser 控件等待网页加载
- shell - symfony4:启动和跟踪长后台任务的进度
- javascript - 打字机 JS,如何删除 Fast 中的字符,按原样在 Normal 中键入字符
- performance-testing - JMETER 4. 0 | JMeter 分布式负载测试 | jp@gc - 步进线程组
- elasticsearch - Elasticsearch 部分匹配顺序
- angular - 基于 Angular 6 角色的根 url 路由
- c# - C#:是否可以将位图保存为 GIF 和 JPEG 而不会进行有损压缩?