简体   繁体   中英

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

I am training a model on top of the prebuilt imag.netV2 model to classify dog breeds.

Here is my code.


import os
import tensorflow as tf

\_URL = 'http://vision.stanford.edu/aditya86/ImageNetDogs/images.tar'
path_to_zip = tf.keras.utils.get_file('images.tar', origin=\_URL, extract=True)

BATCH_SIZE = 32
IMG_SIZE = (224, 224)
dir = os.path.join(os.path.dirname(path_to_zip), 'Images')
train_dataset = tf.keras.utils.image_dataset_from_directory(dir,
shuffle=True,
batch_size=BATCH_SIZE,
image_size=IMG_SIZE,
validation_split=.2,
subset='training',
seed=2021)

validation_dataset = tf.keras.utils.image_dataset_from_directory(dir,
shuffle=True,
batch_size=BATCH_SIZE,
image_size=IMG_SIZE,
validation_split=.2,
subset='validation',
seed=2021)

len(train_dataset.class_names)

import matplotlib.pyplot as plt
class_names = train_dataset.class_names

plt.figure(figsize=(10, 10))
for images, labels in train_dataset.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images\[i\].numpy().astype("uint8"))
plt.title(class_names\[labels\[i\]\])
plt.axis("off")

AUTOTUNE = tf.data.AUTOTUNE

train_dataset = train_dataset.prefetch(buffer_size=AUTOTUNE)
validation_dataset = validation_dataset.prefetch(buffer_size=AUTOTUNE)

val_batches = tf.data.experimental.cardinality(validation_dataset)

data_augmentation = tf.keras.Sequential(\[
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.2),
\])

for image, \_ in train_dataset.take(1):
plt.figure(figsize=(10, 10))
first_image = image\[0\]
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
augmented_image = data_augmentation(tf.expand_dims(first_image, 0))
plt.imshow(augmented_image\[0\] / 255)
plt.axis('off')

rescale = tf.keras.layers.Rescaling(1./127.5, offset=-1)

IMG_SHAPE = IMG_SIZE + (3,)
base_model = tf.keras.applications.MobileNetV2(IMG_SHAPE,
include_top=False,
weights='imagenet')

base_model.trainable = False

global_average_layer = tf.keras.layers.GlobalAveragePooling2D()

model = tf.keras.Sequential()
model.add(tf.keras.Input(shape=(244, 244, 3, )))
model.add(tf.keras.layers.RandomFlip('horizontal'))
model.add(tf.keras.layers.RandomRotation(0.2))
model.add(rescale)
model.add(base_model)
model.add(global_average_layer)
model.add(tf.keras.layers.Dropout(0.2))
model.add(tf.keras.layers.Dense(120))
model.summary()

At this point I get the following warning

WARNING:tensorflow:Model was constructed with shape (None, 224, 224, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 224, 224, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"), but it was called on an input with incompatible shape (None, 244, 244, 3).

And after I compile the model like below


model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=\['accuracy'\])

model.summary()

initial_epochs = 20

I get no errors but when I evaluate like so


loss0, accuracy0 = model.evaluate(train_dataset)

I get the following stack trace


ValueError: in user code:

    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1557, in test_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1546, 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 1535, in run_step  **
        outputs = model.test_step(data)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1499, 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_10" is incompatible with the layer: expected shape=(None, 244, 244, 3), found shape=(None, 224, 224, 3)

I have double checked the shape of everything and I am not sure what is causing this issue. I also have checked that the seed includes all classes for both training and validation. I suspect it has something to do with the transferred imag.net model but I have followed tensorflow tutorials closely and I have not seen a problem with the way I am doing things. Any and all help is appreciated thank you

The error is due to the shape mismatch. Your input image is of shape (224, 224, 3) but the shape in the input layer is (244, 244, 3). Both the shapes should be same.

model.add(tf.keras.Input(shape=(224, 224, 3)))

Kindly change the input shape as above to avoid the error. Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question ValueError: Input 0 is incompatible with layer similarity_model: expected shape=(None, 224, 224, 3), found shape=(None, None, 224, 224, 3) Tensorflow / Keras ValueError: Input 0 of layer "model" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(32, 224, 3) ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, 290, 290, 3) ValueError: Input 0 is incompatible with layer vggface_resnet50: expected shape=(None, 224, 224, 3), found shape=(None, 1, 224, 224, 3) I am getting error like "Input 1 of layer "model_5" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, 5) Input 0 is incompatible with layer functional_3: expected shape=(None, 224, 224, 3), found shape=(None, 240, 240, 3) ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 [None, 224, 224, 1] ValueError: Input 0 of layer sequential_16 is incompatible with the layer: expected ndim=5, found ndim=4. Full shape received: [None, 224, 224, 3] ValueError: Input 0 of layer sequential_3 is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 224, 256) ValueError: Input 0 is incompatible with layer model_8: expected shape=(None, 898, 699, 1), found shape=(None, 699, 1)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM