您可能正在混合使用 keras 和 tensorflow 库。由于 Tensorflow 实现了 keras 库,因此在导入 keras 和 tensorflow 并随机使用它们的开发人员之间这是一个常见的错误,这会导致一些奇怪的行为。
只需使用其中一个import tensorflow.keras
或import keras
在整个代码中使用。
例如,如果我这样编码(随机使用两个库):
import keras #import keras
import tensorflow as tf
from tensorflow.keras.layers import Dense #import layers from tensorflow.keras
from tensorflow.keras import Input
input = Input(shape = (20,))
x = Dense(30, name = 'dense1')(input)
x = Dense(20, name = 'dense2')(x)
output = Dense(1)(x)
model = keras.models.Model(inputs = input ,outputs = output)
model.compile(loss = 'mse', optimizer = 'adam')
model.summary()
输出将是:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
Total params: 1,271
Trainable params: 1,271
Non-trainable params: 0
_________________________________________________________________
但是,如果我修改导入并只使用tensorflow.keras
而不是keras
这样使用:
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras import Input
from tensorflow.keras.models import Model
input = Input(shape = (20,))
x = Dense(30, name = 'dense1')(input)
x = Dense(20, name = 'dense2')(x)
output = Dense(1)(x)
model = Model(inputs = input ,outputs = output)
model.compile(loss = 'mse', optimizer = 'adam')
model.summary()
我会得到这样的输出:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_3 (InputLayer) [(None, 20)] 0
_________________________________________________________________
dense1 (Dense) (None, 30) 630
_________________________________________________________________
dense2 (Dense) (None, 20) 620
_________________________________________________________________
dense_2 (Dense) (None, 1) 21
=================================================================
Total params: 1,271
Trainable params: 1,271
Non-trainable params: 0
_________________________________________________________________