【问题标题】:Keras Creating Image Detection incompatible shapeKeras 创建图像检测不兼容的形状
【发布时间】:2022-01-13 20:55:46
【问题描述】:

我正在做一个小项目,我想通过在卷积网络中使用预训练的 VGG16 网络对一些图像进行训练来对它们进行分类。

这些是我采取的步骤:

#Setting Conditions
img_size = (180,180)
batch_size = 600
num_classes = len(class_names)

#Using Keras built in preprocessing method which facilitates the preprocessing instead of having to do it manually.

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "Data/Train",
    validation_split = 0.2,
    subset = "training",
    seed = 1337, # creating a seed so t
    image_size = img_size,
    batch_size = batch_size,
)

valid_ds = tf.keras.preprocessing.image_dataset_from_directory(
    "Data/Train",
    validation_split = 0.2,
    subset = "validation",
    seed = 1337, # creating a seed so t
    image_size = img_size,
    batch_size = batch_size,
)

建筑模型

#Creating Model
model = Sequential()

#ADDING The VGG16 Pre trained network
model.add(VGG16(pooling ='avg',weights="imagenet", include_top=False))

#adding a dense layer
model.add(Dense(num_classes,activation = 'softmax'))

#Setting the trainable parameter for VGG16 to false, as we want to use this pretrained network, and train the new images.

model.layers[0].trainable = False

#The compile() method: specifying a loss, metrics, and an optimizer To train a model with fit(), #you need to specify a loss function, an optimizer, and optionally, some metrics to monitor.
#You pass these to the model as arguments to the compile() method

model.compile(optimizer = 'adam',loss = 'categorical_crossentropy', metrics =['accuracy'])
epoch_train = len(train_ds)
opoch_val = len(valid_ds)
numbers_epochs = 2


fit_model = model.fit(train_ds, steps_per_epoch = epoch_train,verbose = 1, validation_data = valid_ds, validation_steps = opoch_val,)

当我尝试拟合模型时,出现以下错误:

ValueError: Shapes (None, 1) and (None, 43) are incompatible

如果有专家指出我做错了什么或跳过了哪些步骤......我会非常感激!

【问题讨论】:

    标签: python tensorflow keras deep-learning image-classification


    【解决方案1】:

    如果您打算使用categorical_crossentropy 训练模型,则需要在image_dataset_from_directory 中设置label_mode='categorical。默认情况下,image_dataset_from_directory 方法假定标签被编码为整数(label_mode='int'),这意味着您应该使用sparse_categorical_crossentropy 损失。这是一个工作示例:

    import tensorflow as tf
    import pathlib
    import matplotlib.pyplot as plt
    
    dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
    data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
    data_dir = pathlib.Path(data_dir)
    
    batch_size = 32
    num_classes = 5
    train_ds = tf.keras.utils.image_dataset_from_directory(data_dir, shuffle=True, batch_size=batch_size, label_mode='categorical')
    
    model = tf.keras.Sequential()
    model.add(tf.keras.applications.VGG16(pooling ='avg',weights="imagenet", include_top=False))
    model.add(tf.keras.layers.Dense(num_classes, activation = 'softmax'))
    
    model.layers[0].trainable = False
    
    model.compile(optimizer = 'adam',loss = 'categorical_crossentropy', metrics =['accuracy'])
    numbers_epochs = 2
    fit_model = model.fit(train_ds, epochs=numbers_epochs)
    

    【讨论】:

    • 嘿!,我真的很抱歉回复晚了!这非常有帮助!非常感谢你!
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多