Nor*_*ran 2 python machine-learning neural-network deep-learning keras
我使用以下代码使用 VGG16 创建了一个 CNN 模型,但在创建模型后,模型的输入层从结构中消失了(见图)。
为什么输入层从结构中消失了?
vgg16_model = keras.applications.vgg16.VGG16()
model = Sequential([])
for layer in vgg16_model.layers[:-1]:
model.add(layer)
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax', name = 'prediction'))
Run Code Online (Sandbox Code Playgroud)
模型结构
当使用 Sequential API 时,这只是 Keras 模型表示的一个工件,它没有任何实际效果:该Input层隐式存在,但不被视为正确的层,也不会出现在model.summary(). 如果使用 Functional API,它确实会显示。
考虑以下两个相同的模型,使用两个不同的 API 编写:
顺序API
from keras.models import Sequential
from keras.layers import Dense # notice that we don't import Input here...
model_seq = Sequential([
Dense(64, input_shape=(784,),activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model_seq.summary()
# result:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 64) 50240
_________________________________________________________________
dense_2 (Dense) (None, 64) 4160
_________________________________________________________________
dense_3 (Dense) (None, 10) 650
=================================================================
Total params: 55,050
Trainable params: 55,050
Non-trainable params: 0
_________________________________________________________________
Run Code Online (Sandbox Code Playgroud)
功能API
from keras.models import Model
from keras.layers import Input, Dense # explicitly import Input layer
inputs = Input(shape=(784,))
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
model_func = Model(inputs=inputs, outputs=predictions)
model_func.summary()
# result:
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 784) 0
_________________________________________________________________
dense_1 (Dense) (None, 64) 50240
_________________________________________________________________
dense_2 (Dense) (None, 64) 4160
_________________________________________________________________
dense_3 (Dense) (None, 10) 650
=================================================================
Total params: 55,050
Trainable params: 55,050
Non-trainable params: 0
_________________________________________________________________
Run Code Online (Sandbox Code Playgroud)
这两个模型是相同的;当使用 Sequential API 时,Input层没有明确显示这一事实model.summary()并不意味着与模型的功能有关。编辑:正如 Daniel Möller 在下面的评论中正确指出的那样,它甚至不是一个真正的层,除了定义输入形状之外什么都不做(注意model_func.summary上面的0 训练参数)。
换句话说,不用担心...
此相关线程也可能有用:Keras Sequential 模型输入层
| 归档时间: |
|
| 查看次数: |
948 次 |
| 最近记录: |