【问题标题】:Error when checking target: expected dense_8 to have shape (2,) but got array with shape (1,)检查目标时出错:预期 dense_8 的形状为 (2,) 但得到的数组的形状为 (1,)
【发布时间】:2019-07-07 09:39:53
【问题描述】:

我是迁移学习的新手,我正在研究 2 个类别的图像分类。我正在使用 InceptionV3 对这些图像进行分类。我的数据 为 .jpg 格式。并且文件夹结构采用以下格式。因为我有 2 个类别,所以我也给出了“binary_crossentropy”。但面临问题。

父文件夹/train/categorie1
父文件夹/train/categorie2

父文件夹/test/categorie1
父文件夹/test/categorie2

from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K

# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)

x = Dense(512, activation='relu')(x)
x = Dense(32, activation='relu')(x)
# and a logistic layer -- we have 2 classes
predictions = Dense(2, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)


for layer in base_model.layers:
    layer.trainable = False

# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 249 layers and unfreeze the rest:
for layer in model.layers[:249]:
   layer.trainable = False
for layer in model.layers[249:]:
   layer.trainable = True

model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'C:/Users/Desktop/Transfer/train/',
        target_size=(64, 64),
        batch_size=5,
        class_mode='binary')

test_set = test_datagen.flow_from_directory(
        'C:/Users/Desktop/Transfer/test/',
        target_size=(64, 64),
        batch_size=5,
        class_mode='binary')

model.fit_generator(
        training_set,
        steps_per_epoch=1000,
        epochs=10,
        validation_data=test_set,
        validation_steps=100)

【问题讨论】:

    标签: machine-learning deep-learning computer-vision artificial-intelligence


    【解决方案1】:

    替换这一行

    predictions = Dense(2, activation='softmax')(x)
    

    与:

    predictions = Dense(1, activation='sigmoid')(x)
    

    或将您的目标编码为列,例如[1,0,1] 等同于[[0,1],[1,0],[0,1]]

    【讨论】:

    • 为什么是 1?它应该是 2 对吗?我有2个类别。如果我错了,请纠正我
    • 两个类别的表示方式可能不同,如我在示例中所示。一种方法是仅使用两个数字 {0,1},其中 0 是第一个类别,1 是第二个类别。另一种方法是使用编码,其中 [1,0] 是第一类,[0,1] 是第二类。希望对您有所帮助,如果没有,请确保您了解 softmax 和 sigmoid 之间的区别,以及什么是分类交叉熵。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 2019-01-16
    • 1970-01-01
    • 2021-06-30
    • 2019-03-28
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多