我想在Keras中获得预先训练的VGG16模型,删除其输出层,然后放置一个新的输出层,其中包含适合我的问题的类数,然后将其放在新数据上.出于这个原因,我试图在这里使用这个模型:https://keras.io/applications/#vgg16,但由于它不是Sequential,我不能只是model.pop().从图层弹出并添加它也不起作用,因为在预测中它仍然期望旧的形状.我该怎么办?有没有办法将这种类型的模型转换为Sequential?
我想从预训练的 Keras 模型中删除前N层。例如, an EfficientNetB0,其前3层仅负责预处理:
import tensorflow as tf
efinet = tf.keras.applications.EfficientNetB0(weights=None, include_top=True)
print(efinet.layers[:3])
# [<tensorflow.python.keras.engine.input_layer.InputLayer at 0x7fa9a870e4d0>,
# <tensorflow.python.keras.layers.preprocessing.image_preprocessing.Rescaling at 0x7fa9a61343d0>,
# <tensorflow.python.keras.layers.preprocessing.normalization.Normalization at 0x7fa9a60d21d0>]
Run Code Online (Sandbox Code Playgroud)
正如M.Innat提到的,第一层是Input Layer,应该保留或重新附加。我想删除这些层,但是像这样的简单方法会引发错误:
import tensorflow as tf
efinet = tf.keras.applications.EfficientNetB0(weights=None, include_top=True)
print(efinet.layers[:3])
# [<tensorflow.python.keras.engine.input_layer.InputLayer at 0x7fa9a870e4d0>,
# <tensorflow.python.keras.layers.preprocessing.image_preprocessing.Rescaling at 0x7fa9a61343d0>,
# <tensorflow.python.keras.layers.preprocessing.normalization.Normalization at 0x7fa9a60d21d0>]
Run Code Online (Sandbox Code Playgroud)
这将导致:
ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(...)
Run Code Online (Sandbox Code Playgroud)
推荐的方法是什么?