我试图获取层的权重。当使用Keras层并将输入连接到它时,似乎正常工作。 但是,当将其封装在我的自定义层中时,就不再起作用了。这是一个bug还是我漏掉了什么?
编辑:考虑:
我读到可以在自定义层的build()函数中定义可训练变量。然而,由于自定义层包含Keras层Dense(以及之后可能有更多Keras层),它们应该已经定义了可训练变量和权重/偏差初始化器。 (我看不到一种方法可以通过TestLayer的init()函数来覆盖它们,并使用在TestLayer的build()函数中定义的变量)。
class TestLayer(layers.Layer):
def __init__(self):
super(TestLayer, self).__init__()
self.test_nn = layers.Dense(3)
def build(self, input_shape):
super(TestLayer, self).build(input_shape)
def call(self, inputs, **kwargs):
test_out = test_nn(inputs) # which is test_in
return test_out
test_in = layers.Input((2,))
test_nn = layers.Dense(3)
print(test_nn.get_weights()) # empty, since no connection to the layer
test_out = test_nn(test_in)
print(test_nn.get_weights()) # layer returns weights+biases
testLayer = TestLayer()
features = testLayer(test_in)
print(testLayer.get_weights()) # Problem: still empty, even though connected to input.
Sequential()
)中使用它,那么就没问题了。否则,你将不得不覆盖所有必需的方法(get_weights()
是其中之一)才能使其正常工作。我真的建议你去官方网站上查看教程。此外,如果你想要子类化BN,请确保你理解了实现方式。它并不像tf.matmul() + bias
那样简单。 - Vladhow would the implementation then look like if I had layers.BatchNormalization after Dense?
- like this:bn = tf.keras.layers.BatchNormalization()(features)
- Vlad