我是 Keras 的新手,我正在编写一个实现高斯函数的自定义层 [exp(-(w*x-mean)^2/sigma^2)
其中 W,意味着,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 tutorial中之后(只是想确保它运行时不会产生错误,不关心准确性)并训练模型,看起来损失在大约 4 个时期后停止减少,只有“均值”和“西格玛”的数字在训练后发生变化而“W”的数字保持不变。但是,如果我把它放在第二层,就不会发生这种情况。
我在没有自定义层的情况下再次运行 Keras mnist 教程,发现第一层的权重也没有改变。
更新第一层的权重(更具体地说是第一个参数)不是 Keras 的事情,还是我遗漏了什么?我可以强制更新吗?
谢谢!
最佳答案
你没有正确实现你的层,Keras 不知道你的权重,这意味着它们没有通过梯度下降进行训练。看看this示例:
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape) # Be sure to call this at the end
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
这里您必须使用add_weight
来获得可训练的权重,而不是像您目前所做的那样只使用K.variable
。通过这种方式,您的权重将在 Keras 中注册,并且它们将得到适当的训练。您应该对层中的所有可训练参数执行此操作。
关于python - 第一层的 Keras 权重没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51288330/