改变 TensorSpec tensorflow 的形状

Change shape of TensorSpec tensorflow

我目前正在尝试通过迁移学习实现 VGG16 模型,但在尝试评估模型时遇到了问题。

我是这样称呼它的:

initial_epochs = 10
loss0, accuracy0 = model.evaluate(validation_dataset)

这就是 validation_dataset 的样子:

<PrefetchDataset element_spec=(TensorSpec(shape=(None, 3, 96, 96), dtype=tf.uint8, name=None), TensorSpec(shape=(None, 4), dtype=tf.int32, name=None))>

这是我的错误信息:

ValueError                                Traceback (most recent call last)

<ipython-input-29-c7fea149280c> in <module>()
      1 initial_epochs = 10
----> 2 loss0, accuracy0 = model.evaluate(validation_dataset)

1 frames

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1145           except Exception as e:  # pylint:disable=broad-except
   1146             if hasattr(e, "ag_error_metadata"):
-> 1147               raise e.ag_error_metadata.to_exception(e)
   1148             else:
   1149               raise

ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1525, in test_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1514, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1507, in run_step  **
        outputs = model.test_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1471, in test_step
        y_pred = self(x, training=False)
    File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Input 0 of layer "model" is incompatible with the layer: expected shape=(None, 96, 96, 3), found shape=(None, 3, 96, 96)

我尝试将模型输入形状设置为 (3, 96, 96) 而不是 (96, 96, 3) 但这不起作用... 谁能帮帮我?

尝试使用 validation_dataset.maptf.transpose:

import tensorflow as tf

images = tf.random.normal((10, 3, 96, 96))
labels = tf.random.uniform((10, 4),  maxval=4, dtype=tf.int32)
validation_dataset = tf.data.Dataset.from_tensor_slices((images, labels)).batch(2)
print(validation_dataset)
validation_dataset = validation_dataset.map(lambda x, y: (tf.transpose(x, perm=[0, 3, 2, 1]), y))
print(validation_dataset)
<BatchDataset element_spec=(TensorSpec(shape=(None, 3, 96, 96), dtype=tf.float32, name=None), TensorSpec(shape=(None, 4), dtype=tf.int32, name=None))>
<MapDataset element_spec=(TensorSpec(shape=(None, 96, 96, 3), dtype=tf.float32, name=None), TensorSpec(shape=(None, 4), dtype=tf.int32, name=None))>