我具有以下形状[?,m,n]的输入x,并且我想创建形式为x w + b的新层,并保留x的原始形状。因此,基本上x w应该是逐元素的乘法。
但是由于批次大小未知,所以我不确定如何将w与x保持相同的尺寸。
我不能强迫w为[?,m,n],如果w为[m,n],则在尝试3D和2D之间的乘法时会出错
已解决:
class LinearLayer(Layer):
def __init__(self, **kwargs):
super(LinearLayer, self).__init__(**kwargs)
def build(self, input_shape):
self.w = self.add_weight(name='w',
shape=(input_shape[1], input_shape[2]),
initializer=RandomNormal(),
trainable=True)
self.b = self.add_weight(name='b',
shape=(input_shape[1], input_shape[2]),
initializer=RandomNormal(),
trainable=True)
super(LinearLayer, self).build(input_shape)
def call(self, x, **kwargs):
batch_size = tf.shape(x)[0]
w_expand = tf.expand_dims(self.w, axis=0)
w_tile = tf.tile(w_expand, multiples=[batch_size, 1, 1])
return tf.multiply(x, w_tile) + self.b
def compute_output_shape(self, input_shape):
return input_shape
使w
为[1,m,n],然后与[?,m,n]张量的乘法应该很简单。
甚至更好,如果您可以使用Tensorflow操作代替纯Keras,x*self.W
(或更明确地讲tf.math.multiply(x,self.W)
)应该可以正常工作(Tensorflow的广播不如Keras的la脚。