简体   繁体   English

ValueError:形状不匹配:标签的形状(收到的 (200,))应该等于 logits 的形状,除了最后一个维度(收到的 (100, 2))

[英]ValueError: Shape mismatch: The shape of labels (received (200,)) should equal the shape of logits except for the last dimension (received (100, 2))

While training a model to recognize and categorize images with:在训练 model 以识别和分类图像时:

epochs=2
history = model.fit_generator(train_data_gen,
steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))),
epochs=epochs,
validation_data=val_data_gen,
validation_steps=int(np.ceil(total_validation / float(BATCH_SIZE)))
)

ValueError: Shape mismatch: The shape of labels (received (200,)) should equal the shape of logits except for the last dimension (received (100, 2)). ValueError:形状不匹配:标签的形状(收到的 (200,))应该等于 logits 的形状,除了最后一个维度(收到的 (100, 2))。

..this error turns up. ..这个错误出现了。 I read several answers to the same Shape mismatch question but can't find the right solution.我阅读了同一个形状不匹配问题的几个答案,但找不到正确的解决方案。

The entire code is as follows:整个代码如下:

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator

import numpy as np
import os
import matplotlib.pyplot as plt

_URL = r'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
zip_dir = tf.keras.utils.get_file('cats_and_dogs_filtered.zip', origin = _URL, extract = 
True)

base_dir = os.path.join(os.path.dirname(zip_dir), 'cats_and_dogs_filtered')
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')

train_cats_dir = os.path.join(train_dir, 'cats')
train_dogs_dir = os.path.join(train_dir, 'dogs')
validation_cats_dir = os.path.join(validation_dir, 'cats')
validation_dogs_dir = os.path.join(validation_dir, 'dogs')

num_cats_tr = len(os.listdir(train_cats_dir))
num_dogs_tr = len(os.listdir(train_dogs_dir))

num_cats_val = len(os.listdir(validation_cats_dir))
num_dogs_val = len(os.listdir(validation_dogs_dir))

total_train = num_cats_tr + num_dogs_tr

total_validation = num_cats_val + num_dogs_val

print('training cat images:', num_cats_tr)
print('training dog images:', num_dogs_tr)
print('validation cat images:', num_cats_val)
print('validation dog images:', num_dogs_val)

print('total training images:', total_train)
print('total validation images:', total_validation)

BATCH_SIZE = 100
IMG_SHAPE = 150

def plotImages(images_arr):
    fig, axes = plt.subplots(1,5, figsize=(20,20))
    axes = axes.flatten()
    for img, ax in zip(images_arr, axes):
        ax.imshow(img)
    plt.tight_layout()
    plt.show()

image_gen = ImageDataGenerator(rescale = 1./255, horizontal_flip = True)

train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, 
shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE))

augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images)

image_gen = ImageDataGenerator(rescale=1./255, rotation_range=45)

train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, 
shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE))

augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images)

image_gen = ImageDataGenerator(rescale=1./255, zoom_range=0.5)

train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, 
shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE))

image_gen_train = ImageDataGenerator(rescale=1./255, rotation_range=40, 
                  width_shift_range=0.2, height_shift_range=0.2, 
                  shear_range=0.2, zoom_range=0.2, horizontal_flip=True, 
                  fill_mode='nearest')

train_data_gen = image_gen_train.flow_from_directory(batch_size=BATCH_SIZE, 
                 directory=train_dir, shuffle=True, 
                 target_size=(IMG_SHAPE,IMG_SHAPE))

augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images)

image_gen_val = ImageDataGenerator(rescale=1./255)

val_data_gen = image_gen_val.flow_from_directory(batch_size=BATCH_SIZE, 
               directory=validation_dir, 
               target_size=(IMG_SHAPE,IMG_SHAPE), 
               class_mode='binary')

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150,150,3)),
    tf.keras.layers.MaxPooling2D(2,2),
    
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    
    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(2)
])

model.compile(optimizer='adam', 
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
     metrics=['accuracy'])

model.summary()

epochs=2
history = model.fit_generator(
    train_data_gen,
    steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))),
    epochs=epochs,
    validation_data=val_data_gen,
    validation_steps=int(np.ceil(total_validation / float(BATCH_SIZE)))
)

you need to define class_mode='binary' also in image_gen_train.flow_from_directory您还需要在image_gen_train.flow_from_directory中定义class_mode='binary'

here the running code: https://colab.research.google.com/drive/1tisXyQFLHet0vrLdmyAxKNOwHMmCayXu?usp=sharing这里的运行代码: https://colab.research.google.com/drive/1tisXyQFLHet0vrLdmyAxKNOwHMmCayXu?usp=sharing

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:形状不匹配:标签的形状(收到的 (1,))应该等于 logits 的形状,除了最后一个维度(收到的 (10, 30)) - ValueError: Shape mismatch: The shape of labels (received (1,)) should equal the shape of logits except for the last dimension (received (10, 30)) ValueError:形状不匹配:标签的形状(收到的(15,))应该等于逻辑的形状,除了最后一个维度(收到的(5,3)) - ValueError: Shape mismatch: The shape of labels (received (15,)) should equal the shape of logits except for the last dimension (received (5, 3)) Tensorflow fit ValueError: Shape mismatch: the shape of labels (received (16640,)) 应该等于 logits 的形状,除了最后一个维度 - Tensorflow fit ValueError: Shape mismatch: The shape of labels (received (16640,)) should equal the shape of logits except for the last dimension TensorFlow 2.0 SparseCategoricalCrossentropy valueError: Shape mismatch: 标签的形状应该等于 logits 的形状,除了最后一个 - TensorFlow 2.0 SparseCategoricalCrossentropy valueError: Shape mismatch: The shape of labels should equal the shape of logits except for the last Logit的形状和标签不匹配 - Shape of logits and labels mismatch logit和标签之间的形状不匹配 - Shape mismatch between logits and labels ValueError: `logits` 和 `labels` 必须具有相同的形状,收到 ((None, 16) vs (None, 1)) - ValueError: `logits` and `labels` must have the same shape, received ((None, 16) vs (None, 1)) 形状错误:标签的形状与对数的形状不兼容 - Shape mismacth: shape of labels is incompatible with shape of logits 排名不匹配:标签排名(收到2)应该等于logits排名减去1(收到2) - Rank mismatch: Rank of labels (received 2) should equal rank of logits minus 1 (received 2) logits 和 labels 必须具有相同的第一维,得到 logits 形状 [2048,10] 和标签形状 [32] - logits and labels must have the same first dimension, got logits shape [2048,10] and labels shape [32]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM