【问题标题】:ValueError: logits and labels must have the same shapeValueError:logits 和标签必须具有相同的形状
【发布时间】:2021-02-02 17:03:27
【问题描述】:
  • 我在 Keras 中有一个 多层感知器 网络,其中包含两个隐藏层。

  • 在尝试训练网络时,我在 fit_generator 中遇到错误:

错误:

ValueError: logits 和 labels 必须具有相同的形状 ((None, 2) vs (None, 1))

我的代码是:

import numpy as np
import keras
from keras import layers
from keras import Sequential
# Define Window size (color images)
img_window = (32,32,3)

# Flatten the Window shape
input_shape = np.prod(img_window)
print(input_shape)

# Define MLP with two hidden layers(neurons)
simpleMLP = Sequential(
    [layers.Input(shape=img_window),
     layers.Flatten(), # Flattens the input, conv2D to 1 vector , which does not affect the batch size.
     layers.Dense(input_shape//2 ,activation="relu"),
     layers.Dense(input_shape//2 ,activation="relu"),
     layers.Dense(2,activation="sigmoid"),
     ]
)
# After model is "built" call its summary() menthod to display its contents
simpleMLP.summary()

# Initialization
# Size of the batches of data, adjust it depends on RAM
batch_size = 128
epochs = 5
# Compile MLP model with 3 arguments: loss function, optimizer, and metrics function to judge model performance
simpleMLP.compile(loss="binary_crossentropy",optimizer="adam",metrics=["binary_accuracy"])  #BCE

# Create ImagedataGenerator to splite training, validation dataset
from keras.preprocessing.image import ImageDataGenerator

train_dir = '/content/train'
train_datagen = ImageDataGenerator(
    rescale=1./255, # rescaling factor
    shear_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True,
    fill_mode='nearest')

valid_dir = '/content/valid'
valid_datagen =ImageDataGenerator(
    rescale=1./255,
    shear_range=0.1,
    zoom_range=0.1,
    horizontal_flip=True,
    fill_mode='nearest')


train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size=img_window[:2],
    batch_size=batch_size,
    class_mode='binary',
    color_mode='rgb'
    )

validation_generator = valid_datagen.flow_from_directory(
    valid_dir,
    target_size=img_window[:2],
    batch_size=batch_size,
    class_mode='binary',
    color_mode='rgb')

# Train the MLP model
simpleMLP.fit_generator((
    train_generator, 
    steps_per_epoch= 8271 // batch_size,
    epochs=5,
    validation_data=validation_generator,
    validation_steps= 2072 // batch_size)

你能告诉我如何解决这个问题吗?提前致谢。

【问题讨论】:

    标签: keras neural-network classification


    【解决方案1】:

    你的问题很简单,你有形状标签(N, 1),损失定义为binary_crossentropy。这意味着您应该在最后一层有一个输出节点。但是你有一个输出两个类的模型。

    simpleMLP = Sequential(
        [...
         layers.Dense(2,activation="sigmoid"),
         ]
    )
    

    只需将其更改为,

    simpleMLP = Sequential(
        [...
         layers.Dense(1,activation="sigmoid"),
         ]
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2020-09-30
      • 2021-07-27
      • 2021-10-28
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多