如何防止Tensorflow Input生成batch dimension

How to prevent Tensorflow Input from generating batch dimension

我最近更新到最新版本的 Tensorflow 2.3.1,更新后我的模型不再工作了:

model = tf.keras.Sequential([
        layers.Input(shape= input_shape), # input_shape:  (1623, 105, 105, 3)
        layers.experimental.preprocessing.Rescaling(1./255),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Conv2D(32, 3, activation='relu'),
        layers.MaxPooling2D(),
        layers.Flatten(),
        layers.Dense(128, activation='relu'),
        layers.Dense(ds_info.features['label'].num_classes)
    ])

问题是输入层添加了一个新的 batch_size 维度,这又会导致以下错误:

Input 0 of layer max_pooling2d_22 is incompatible with the layer: expected ndim=4, found ndim=5. Full shape received: [None, 1623, 103, 103, 32]

如何防止生成该问题或解决此问题。

指定输入形状时,需要省略样本数。那是因为 Keras 可以接受任何数字。所以试试这个:

layers.Input(shape = input_shape[1:]),

这将指定 (rows, columns, channels) 的输入形状,省略样本数。