我目前正在尝试使用MobileNetV2的前50层。因此,我想提取这些图层并创建一个新模型。
我以为我可以调用每个层,但是“ block_2_add”层会导致错误,我不明白为什么。
import tensorflow as tf
from keras.models import Model
mobile_net=tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), alpha=0.5, include_top=False, weights='imagenet')
inputs = Input(shape=(224, 224, 3))
x=mobile_net.layers[1](inputs)
for layer in mobile_net.layers[2:50]:
x=layer(x)
{'name': 'block_2_add', 'trainable': True, 'dtype': 'float32'}
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-77-5873b9344fa3> in <module>()
3 for layer in mobile_net.layers[2:50]:
4 print(layer.get_config())
----> 5 x=layer(x)
6
7 for layer in mobile_net.layers[:50]:
1 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/layers/merge.py in call(self, inputs)
119 def call(self, inputs):
120 if not isinstance(inputs, list):
--> 121 raise ValueError('A merge layer should be called on a list of inputs.')
122 if self._reshape_required:
123 reshaped_inputs = []
ValueError: A merge layer should be called on a list of inputs.
答案 0 :(得分:2)
我的猜测是MobileNetV2不是顺序模型,即层图不是线性的。如果您只需要模型的输出而不是任何中间层的输出,我认为下面的代码就可以完成这项工作(即使您似乎想在输出前计算最后一层,结果仍然应该是您想要的):
import tensorflow as tf
from keras.models import Model
mobile_net=tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), alpha=0.5, include_top=False, weights='imagenet')
inputs = Input(shape=(224, 224, 3))
output = mobile_net(inputs)
答案 1 :(得分:0)
我可能会迟到,但我想下面的代码会为你做的
pre_trained_model = MobileNetV2(input_shape = (256, 256, 3),
include_top = False,
weights = "imagenet" )
last_layer = pre_trained_model.get_layer('block_15_project_BN')
layer.output
input_l = pre_trained_model.input
base_model1 = tf.keras.Model(input_l, last_output
)