无法挤压 dim[1],期望维度为 1,得到 2 [[{{node predict/feature_vector/SpatialSqueeze}}]] [Op:__inference_train_function_253305]

Can not squeeze dim[1], expected a dimension of 1, got 2 [[{{node predict/feature_vector/SpatialSqueeze}}]] [Op:__inference_train_function_253305]

我发现在使用 'Mobilenet_tranferLearning' 时很难训练以下模型。我正在使用 ImageDataGenerator 和 flow_from_directory 方法从目录中扩充和加载文件。有趣的是,我的代码在使用 InceptionV3 时不会抛出任何错误,但在我使用 'Mobilenet_tranferLearning' 时会抛出任何错误。 我会很感激一些指示,因为我相信我使用的是正确的损失函数 'categorical_crossentropy',我也在 train_generator 中定义了它(class_mode='categorical')。

train_datagen = ImageDataGenerator(
rescale= 1./255,
shear_range= 0.2,
zoom_range= 0.2,
horizontal_flip= True,
rotation_range= 20,
width_shift_range= 0.2,
height_shift_range= 0.2,   
validation_split=0.2,)


valid_datagen = ImageDataGenerator(
rescale= 1./255, 
validation_split=0.2,)

train_generator = train_datagen.flow_from_directory(  
'/content/fold/images/Images',  
target_size= (243, 243), 
color_mode= 'rgb',
batch_size= 64,  
class_mode= 'categorical',
subset='training',
shuffle= True, 
seed= 1337) 

valid_generator = valid_datagen.flow_from_directory(
'/content/fold/images/Images',
target_size= (243, 243),
color_mode= 'rgb',
batch_size= 64,  
class_mode= 'categorical',
subset='validation',
shuffle= True, 
seed= 1337)

`import tensorflow_hub as hub 
# from tensorflow.keras import Activations
classifier_url ="https://hub.tensorflow.google.cn/google/tf2- 
 preview/mobilenet_v2/feature_vector/4"
 baseModel = hub.KerasLayer(classifier_url, input_shape=(224,224,3), output_shape=[1280], 
 name="Mobilenet")
 baseModel.trainable = False # freeze mobilenet weights
 myModel = Sequential(name="Mobilenet_tranferLearning")
 myModel.add(baseModel)
 myModel.add(Flatten())
 myModel.add(Dropout(0.2))
 myModel.add(Dense(120,activation='softmax'))
 myModel.summary()`
 
 myModel.compile(optimizer= 'adam', loss= 'categorical_crossentropy', metrics= ['accuracy'])


  history = myModel.fit(train_generator,
                epochs=25,
                validation_data=valid_generator)`

我收到以下错误:

InvalidArgumentError:图形执行错误:

在节点 'predict/feature_vector/SpatialSqueeze' 处检测到定义于(最近一次调用最后一次): 文件“/usr/lib/python3.7/runpy.py”,第 193 行,在 _run_module_as_main 中 "主要", mod_spec) 文件“/usr/lib/python3.7/runpy.py”,第 85 行,在 _run_code 中 执行(代码,run_globals) 文件“/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py”,第 16 行,位于 app.launch_new_instance() 文件“/usr/local/lib/python3.7/dist-packages/traitlets/config/application.py”,第 846 行,在 launch_instance 中 app.start() 文件“/usr/local/lib/python3.7/dist-packages/ipykernel/kernelapp.py”,第 499 行,在开始 self.io_loop.start() 文件“/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py”,第 132 行,开始 self.asyncio_loop.run_forever() 文件“/usr/lib/python3.7/asyncio/base_events.py”,第 541 行,在 run_forever 中 self._run_once() 文件“/usr/lib/python3.7/asyncio/base_events.py”,第 1786 行,在 _run_once 中 handle._run() 文件“/usr/lib/python3.7/asyncio/events.py”,第 88 行,在 _run self._context.run(self._callback, *self._args) 文件“/usr/local/lib/python3.7/dist-packages/tornado/platform/asyncio.py”,第 122 行,在 _handle_events 中 handler_func(文件对象,事件) 文件“/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py”,第 300 行,在 null_wrapper 中 return fn(*args, **kwargs) 文件“/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py”,第 452 行,在 _handle_events 中 self._handle_recv() 文件“/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py”,第 481 行,在 _handle_recv 中 self._run_callback(回调,消息) 文件“/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py”,第 431 行,在 _run_callback 中 回调(*args,**kwargs) 文件“/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py”,第 300 行,在 null_wrapper 中 return fn(*args, **kwargs) 调度程序中的文件“/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py”,第 283 行 return self.dispatch_shell(流,消息) 文件“/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py”,第 233 行,在 dispatch_shell 中 处理程序(流、标识、消息) 文件“/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py”,第 399 行,在 execute_request 中 user_expressions, allow_stdin) 文件“/usr/local/lib/python3.7/dist-packages/ipykernel/ipkernel.py”,第 208 行,在 do_execute 中 res = shell.run_cell(代码, store_history=store_history, silent=无声) 文件“/usr/local/lib/python3.7/dist-packages/ipykernel/zmqshell.py”,第 537 行,在 run_cell 中 return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) 文件“/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py”,第 2718 行,在 run_cell 中 交互性=交互性,编译器=编译器,结果=结果) 文件“/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py”,第 2822 行,在 run_ast_nodes 中 如果 self.run_code(代码,结果): 文件“/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py”,第 2882 行,在 run_code 中 执行(code_obj,self.user_global_ns,self.user_ns) 文件“”,第 4 行,位于 baseModel = hub.KerasLayer(classifier_url, input_shape=(224,224,3), output_shape=[1280], name="Mobilenet") 文件“/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py”,第 153 行,在 init 中 self._func = load_module(句柄,标签,self._load_options) 文件“/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py”,第 449 行,在 load_module 中 return module_v2.load(句柄,标签=标签,选项=set_load_options) 文件“/usr/local/lib/python3.7/dist-packages/tensorflow_hub/module_v2.py”,第 106 行,加载中 obj = tf.compat.v1.saved_model.load_v2(module_path, 标签=标签) 节点:'predict/feature_vector/SpatialSqueeze' 无法挤压 dim[1],期望维度为 1,结果为 2 [[{{节点 predict/feature_vector/SpatialSqueeze}}]] [操作:__inference_train_function_253305]

确保您在 flow_from_directoryhub.KerasLayer 中的图像尺寸 相同 (224, 224)。这是一个工作示例:

import tensorflow_hub as hub
import tensorflow as tf

img_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=20)

flowers = tf.keras.utils.get_file(
    'flower_photos',
    'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',
    untar=True)

train_ds = img_gen.flow_from_directory(flowers, target_size=(224, 224), batch_size=32, shuffle=True)
classifier_url ="https://hub.tensorflow.google.cn/google/tf2-preview/mobilenet_v2/feature_vector/4"
baseModel = hub.KerasLayer(classifier_url, input_shape=(224,224,3), output_shape=[1280], 
name="Mobilenet")
baseModel.trainable = False # freeze mobilenet weights
myModel = tf.keras.Sequential(name="Mobilenet_tranferLearning")
myModel.add(baseModel)
myModel.add(tf.keras.layers.Flatten())
myModel.add(tf.keras.layers.Dropout(0.2))
myModel.add(tf.keras.layers.Dense(5,activation='softmax'))
myModel.summary()

myModel.compile(optimizer= 'adam', loss= 'categorical_crossentropy', metrics= ['accuracy'])

history = myModel.fit(train_ds, epochs=25)