首页 > 解决方案 > R- 具有权重约束的自定义 Keras 层

问题描述

我正在尝试在 R 中编写一个具有可训练权重的自定义 Keras 层,其中:

其中exp是矩阵指数映射。

标签: rtensorflowmachine-learningkerasdeep-learning

解决方案


请注意,了解批量大小的位置非常重要,并且层不能具有基于批量大小的权重(除非您使用batch_shapebatch_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
    }

推荐阅读