理解keras中的方法构建和输入input_shape



我试图理解一个基本的例子,特别是https://keras.io/getting_started/intro_to_keras_for_researchers/:

class Linear(keras.layers.Layer):
def __init__(self, units):
super(Linear, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True)
self.b = self.add_weight(shape=(self.units,), initializer="random_normal", trainable=True)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b

class MLP(keras.layers.Layer):
"""Simple stack of Linear layers."""
def __init__(self):
super(MLP, self).__init__()
self.linear_1 = Linear(32)
self.linear_2 = Linear(32)
self.linear_3 = Linear(10)
def call(self, inputs):
x = self.linear_1(inputs)
x = tf.nn.relu(x)
x = self.linear_2(x)
x = tf.nn.relu(x)
return self.linear_3(x)
mlp = MLP()
y = mlp(tf.ones(shape=(3, 64)))

我认为这是一个非常基本的问题,但我没有找到一个解释(可能是因为我不怎么找)。

1-为什么调用方法build第一次是叫层吗?

2-如果张量tf.ones(shape=(3, 64))通过,为什么input_shape在方法中构建是一个TensorShape吗?

感谢

Build在对象创建时调用input_shape因为通常你事先不知道张量的输入形状也不知道你的层需要多少权重,这样做是很健康的因为每次前向传播发生时都会调用call方法所以keras将它们分开了

相关内容

最新更新