问题:
使用以下代码来删除模型的layer
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Dense, Input, Layer
from tensorflow.keras.models import Model
input_tensor = Input(shape=(10,))
hidden = Dense(100, activation='relu')(input_tensor)
out = Dense(10, activation='relu')(hidden)
model = Model(input_tensor, out)
model.compile(loss="mse", optimizer=tf.train.AdamOptimizer(learning_rate=0.001))
model.summary()
model.layers.pop()
model.layers.pop()
model.summary()
hidden = Dense(120, activation='relu')(model.layers[-1].output)
out = Dense(5, activation='softmax')(hidden)
model = Model(input_tensor, out)
model.summary()
但是结果却显示model.layers.pop()不起作用
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 10) 0
_________________________________________________________________
dense (Dense) (None, 100) 1100
_________________________________________________________________
dense_1 (Dense) (None, 10) 1010
=================================================================
Total params: 2,110
Trainable params: 2,110
Non-trainable params: 0
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_1 (InputLayer) (None, 10) 0
_________________________________________________________________
dense (Dense) (None, 100) 1100
_________________________________________________________________
dense_1 (Dense) (None, 10) 1010
=================================================================
Total params: 2,110
Trainable params: 2,110
Non-trainable params: 0
解决方法:
- 重新建立模型并且复制原模型的layer,例:
model = Sequential()
for layer in source_model.layers[:-1]: # 跳过最后一层
model.add(layer)
model.summary()
当然可以自定义增加层用来去掉模型的最后几层,例:
model = Sequential()
for layer in source_model.layers[:-1]: # 跳过最后一层
model.add(layer)
model.add(Dense(2, activation='softmax'))
model.summary()
- 使用函数型模型,即functional model,例:
model = Model(inputs=source_model.input, outputs=source_model.layers[-2].output) # 这里的source_model即为原来的模型
同样也可以添加层,例:
prediction = Dense(2, activation='softmax')(source_model.layers[-2].output)
model = Model(inputs=source_model.input, outputs=prediction)