1. ValueError: Layer dense expects 1 inputs, but it received 2 input tensors.
问题代码:
model.build(input_shape=[None, 50])
问题出在参数input_shape的传入上,不能传入列表形式的shape,只能是tuple类型的。
修改后正确代码为
model.build(input_shape=(None, 50))
2.ValueError: You tried to call count_params on ***, but the layer isn’t built. You can build it manually via: ****
问题代码:
import tensorflow as tf
from tensorflow.keras import layers, models
class MyModel(tf.keras.models.Model):
def __init__(self):
super(MyModel, self).__init__()
def build(self, input_shape):
# self.dense = layers.Dense(4)
# self.dense2 = layers.Dense(2)
# self.built = True
super(MyModel, self).build(input_shape)
def call(self, inputs):
# x = self.dense(inputs)
# x = self.dense2(x)
x = layers.Dense(4)(inputs)
x = layers.Dense(2)(x)
return x
def main():
model = MyModel()
model.build(input_shape=(None, 50))
model.summary()
if __name__ == "__main__":
main()
问题出在call函数内部,不可以直接通过layers.Dense()的方式构建网络层,
应该在build函数内部先建立对应的层
正确代码应为:
import tensorflow as tf
from tensorflow.keras import layers, models
class MyModel(tf.keras.models.Model):
def __init__(self):
super(MyModel, self).__init__()
def build(self, input_shape):
self.dense = layers.Dense(4)
self.dense2 = layers.Dense(2)
# self.built = True
super(MyModel, self).build(input_shape)
def call(self, inputs):
x = self.dense(inputs)
x = self.dense2(x)
# x = layers.Dense(4)(inputs)
# x = layers.Dense(2)(x)
return x
def main():
model = MyModel()
model.build(input_shape=(None, 50))
model.summary()
if __name__ == "__main__":
main()
同时如果只是通过self.built = True
的方式,同样会出现此错误,建议通过super(MyModel, self).build(input_shape)
的方式,使得build生效。
3. summary输出时output shape 为multiple的方法
- 在model.build()后手动调用call方法,并输入shape大小。
eg:
model = MyModel()
model.build(input_shape=(None, 50))
model.call(tf.keras.Input(shape=(50, )))
model.summary()
最终summary输出:
Model: "my_model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 4) 204
_________________________________________________________________
dense_1 (Dense) (None, 2) 10
=================================================================
Total params: 214
Trainable params: 214
Non-trainable params: 0
_________________________________________________________________
Process finished with exit code 0