我是Keras的新手,正在编写实现高斯函数的自定义层[exp(-(w*x-mean)^2/sigma^2)
其中W、mean和sigma都是随机生成的]。
下面是自定义层的代码:
class Gaussian(Layer):
def __init__(self,**kwargs):
super(Gaussian, self).__init__(**kwargs)
def build(self, input_shape):
# Create trainable weights for this layer.
self.W_init = np.random.rand(1,input_shape[1])
self.W = K.variable(self.W_init, name="W")
# Create trainable means for this layer.
self.mean_init = np.random.rand(1,input_shape[1])
self.mean = K.variable(self.mean_init, name="mean")
# Create trainable sigmas for this layer.
self.sigma_init = np.random.rand(1,input_shape[1])
self.sigma = K.variable(self.sigma_init, name="sigma")
self.trainable_weights = [self.mean, self.sigma]
super(Gaussian, self).build(input_shape) # Be sure to call this somewhere!
def call(self, x):
result = tf.multiply(x, self.W)
result = tf.subtract(x, self.mean)
result = tf.multiply(tf.square(result),-1)
result = tf.divide(result, tf.square(self.sigma))
return result
def compute_output_shape(self, input_shape):
return input_shape
在Keras mnist教程中,我将自定义层放在第一层(只是为了确保它运行时不会产生错误,不关心准确性),并训练模型后发现,在约4轮后,损失停止下降,训练后“mean”和“sigma”的数字发生了变化,而“W”的数字保持不变。但是,如果将其作为第二层,则不会发生这种情况。
我再次运行了没有自定义层的Keras mnist教程,发现第一层的权重也没有改变。
这是Keras的一个问题,还是我漏掉了什么?我能强制更新吗?
谢谢!