您可以在model.layers
上使用pop()
,然后使用model.layers[-1].output
创建新图层。
例子:
from keras.models import Model
from keras.layers import Dense,Flatten
from keras.applications import vgg16
from keras import backend as K
model = vgg16.VGG16(weights='imagenet', include_top=True)
model.input
model.summary(line_length=150)
model.layers.pop()
model.layers.pop()
model.summary(line_length=150)
new_layer = Dense(10, activation='softmax', name='my_dense')
inp = model.input
out = new_layer(model.layers[-1].output)
model2 = Model(inp, out)
model2.summary(line_length=150)
或者,您可以使用这些模型include_top=False
选项。在这种情况下,如果您需要使用拼合图层,则还需要传递input_shape
。
model3 = vgg16.VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
model3.summary(line_length=150)
flatten = Flatten()
new_layer2 = Dense(10, activation='softmax', name='my_dense_2')
inp2 = model3.input
out2 = new_layer2(flatten(model3.output))
model4 = Model(inp2, out2)
model4.summary(line_length=150)
这很重要!我解决了我一直在挣扎数小时的问题!谢谢 ! – user40780
令人难以置信的有用。这应该在Keras官方文档中。 –