首页 > 解决方案 > 将分类器添加到 MobileNet 模型时出现检索错误

问题描述

我有以下代码,当我尝试添加自己的分类器时出现错误。

import keras
from keras import layers,Model
from keras.layers import Input,GlobalAveragePooling2D,Flatten,Dense
MobileNetV2_model= tf.keras.applications.MobileNetV2(input_shape=None, alpha=1.0, include_top=False, 
weights='imagenet')
#MobileNetV2_model.summary()
x= MobileNetV2_model.output
x = layers.GlobalAveragePooling2D()(x)
final_output=layers.Dense(2, activation='sigmoid')(x)
model = keras.Model(inputs=MobileNetV2.input, outputs = final_output)
model.compile(optimizer="adam", loss='BinaryCrossentropy', metrics=['accuracy'],loss_weights=0.1)

错误

   TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that 
   you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying 
   to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

标签: tensorflowmachine-learningkerasconv-neural-network

解决方案


你不应该混合kerastf.keras。您可以参考工作代码,如下所示

import tensorflow as tf
from tensorflow.keras import layers, Model

MobileNetV2_model= tf.keras.applications.MobileNetV2(input_shape=(224,224,3), alpha=1.0, include_top=False, weights='imagenet')

#MobileNetV2_model.summary()
x= MobileNetV2_model.output
x = layers.GlobalAveragePooling2D()(x)
final_output=layers.Dense(2, activation='sigmoid')(x)

model = Model(inputs=MobileNetV2_model.input, outputs = final_output)
model.compile(optimizer="adam", loss='BinaryCrossentropy', metrics=['accuracy'],loss_weights=0.1)

推荐阅读