- 要获取中间层的输出,最好的办法是新建一个模型
from keras.models import Model
model = ... #原始model
layer_name = "my_layer"
intermediate_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)
####or
base_model = load_model(model_path)
base_model.layers.pop()
pre = Dense(units=num_label,activation='softmax')(base_model.layers[-1].output)
model = Model(base_model.input,pre)
- 或者使用keras function来实现返回一个特定的输出
from keras import backend as K
get_3rd_layer_output = K.function([model.layers[0].input, model.layers[3].output])
layer_output = get_3rd_layer_output([x])[0]
- 固定特定层权重freeze weights
base_model = InceptionV3(weights='imagenet', include_top=False)
for layer in base_model.layers:
layer.trainable = False
或者比如指定前3层不训练
for layer in base_model.layers[:3]:
layer.trainable = False
- 使用pop方法来删除最后一层
model = Sequential()
model.add(Dense(32, activation="relu", input_dim=784))
model.add(Dense(32, activation="relu"))
print(len(model.layers)) #输出2
model.pop()
print(len(model.layers)) #输出1
网友评论