Python 检查目标时出错:预期dense_3 具有形状(3,) 但得到形状为(1,) 的数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49392972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error when checking target: expected dense_3 to have shape (3,) but got array with shape (1,)
提问by Ciprian Andrei Focsaneanu
I am working on training a VGG16-like model in Keras, on a 3 classes subset from Places205, and encountered the following error:
我正在使用来自 Places205 的 3 个类子集在 Keras 中训练一个类似 VGG16 的模型,并遇到以下错误:
ValueError: Error when checking target: expected dense_3 to have shape (3,) but got array with shape (1,)
I read multiple similar issues but none helped me so far. The error is on the last layer, where I've put 3 because this is the number of classes I'm trying right now.
我阅读了多个类似的问题,但到目前为止没有一个对我有帮助。错误在最后一层,我在那里放了 3,因为这是我现在正在尝试的类数。
The code is the following:
代码如下:
import keras from keras.datasets
import cifar10 from keras.preprocessing.image
import ImageDataGenerator from keras.models
import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K import os
# Constants used
img_width, img_height = 224, 224
train_data_dir='places\train'
validation_data_dir='places\validation'
save_filename = 'vgg_trained_model.h5'
training_samples = 15
validation_samples = 5
batch_size = 5
epochs = 5
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height) else:
input_shape = (img_width, img_height, 3)
model = Sequential([
# Block 1
Conv2D(64, (3, 3), activation='relu', input_shape=input_shape, padding='same'),
Conv2D(64, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
# Block 2
Conv2D(128, (3, 3), activation='relu', padding='same'),
Conv2D(128, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
# Block 3
Conv2D(256, (3, 3), activation='relu', padding='same'),
Conv2D(256, (3, 3), activation='relu', padding='same'),
Conv2D(256, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
# Block 4
Conv2D(512, (3, 3), activation='relu', padding='same'),
Conv2D(512, (3, 3), activation='relu', padding='same'),
Conv2D(512, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
# Block 5
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
# Top
Flatten(),
Dense(4096, activation='relu'),
Dense(4096, activation='relu'),
Dense(3, activation='softmax') ])
model.summary()
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# no augmentation config train_datagen = ImageDataGenerator() validation_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')
model.fit_generator(
train_generator,
steps_per_epoch=training_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_samples // batch_size)
model.save_weights(save_filename)
回答by Kamil Kaczmarek
The problem is with your label-data shape. In a multiclass problem you are predicting the probabibility of every possible class, so must provide label data in (N, m) shape, where N is the number of training examples, and m is the number of possible classes (3 in your case).
问题在于您的标签数据形状。在多类别问题中,您要预测每个可能类别的概率,因此必须提供 (N, m) 形状的标签数据,其中 N 是训练示例的数量,m 是可能类别的数量(在您的情况下为 3) .
Keras expects y-data in (N, 3) shape, not (N,) as you've problably provided, that's why it raises an error.
Keras 期望 (N, 3) 形状的 y 数据,而不是您可能提供的 (N,) 形状,这就是它引发错误的原因。
Use e.g. OneHotEncoderto convert your label data to one-hot encoded form.
使用例如OneHotEncoder将您的标签数据转换为单热编码形式。
回答by Peter
As mentioned by others, Keras expects "one hot" encoding in multiclass problems.
正如其他人所提到的,Keras 期望在多类问题中使用“one hot”编码。
Keras comes with a handy function to recode labels:
Keras 带有一个方便的功能来重新编码标签:
print(train_labels)
[1. 2. 2. ... 1. 0. 2.]
print(train_labels.shape)
(2000,)
Recode labels using to_categorical
to get the correct shape of inputs:
使用to_categorical
重新编码标签以获得正确的输入形状:
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
print(train_labels)
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 1.]
...
[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]]
print(train_labels.shape)
(2000, 3) # viz. 2000 observations, 3 labels as 'one hot'
Other importent things to change/check in multiclass (compared to binary classification):
在多类中更改/检查的其他重要事项(与二进制分类相比):
Set class_mode='categorical'
in the generator()
function(s).
class_mode='categorical'
在generator()
函数中设置。
Don't forget that the lastdense layer must specify the number of labels (or classes):
不要忘记最后一个密集层必须指定标签(或类)的数量:
model.add(layers.Dense(3, activation='softmax'))
Make sure that activation=
and loss=
is chosen so to suit multiclass problems, usually this means activation='softmax'
and loss='categorical_crossentropy'
.
确保选择activation=
和loss=
以适应多类问题,通常这意味着activation='softmax'
和loss='categorical_crossentropy'
。
回答by Doctor Strange
Had the same issue. To solve the problem you can simply change in validation_generator and train_generator the class mode from 'binary' to 'categorical' - that's because you have 3 classes-which is not binary.
有同样的问题。要解决这个问题,您可以简单地在 validation_generator 和 train_generator 中将类模式从“二进制”更改为“分类”-那是因为您有 3 个类-不是二进制的。
回答by Vinay Verma
Problem : expected dense_3 to have shape (3,) but got array with shape (1,)
问题:预期dense_3 具有形状(3,) 但得到形状为(1,) 的数组
If you are using it for classification the the number of variables should be correct in the parameter for adding a dense layer.
如果您使用它进行分类,则添加密集层的参数中的变量数量应该是正确的。
variables_for_classification=5 #change it as per your number of categories
model.add(Dense(variables_for_classification, activation='softmax'))
model.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1,callbacks=[EarlyStopping(monitor='val_loss', patience=3, min_delta=0.0001)])
To make it more clear. As I was using the LSTM to predict the category of the news and the categories were 5- business,tech,politics,sports,entertainment
为了更清楚。当我使用 LSTM 来预测新闻的类别时,类别是 5-商业、科技、、体育、娱乐
In that dense function when I put 5 it worked correctly.
在那个密集的函数中,当我输入 5 时它工作正常。
回答by Tinashe Tivatyi
The reason for this is you would have used 'binary' class_mode in the fit_generator() method for a multi class problem. Change that to 'categorical' and the error goes.
这样做的原因是您会在 fit_generator() 方法中使用“binary”class_mode 来解决多类问题。将其更改为“分类”,错误就会消失。
回答by Engineer Ahmed IT
if take these errors u just need to specify the last with numbers of the classes > as an example u have 6 classes u have to make that :
如果出现这些错误,您只需要指定最后一个类的编号> 例如,您有 6 个类,您必须这样做:
model.add(Dense(6, activation='softmax'))
u can use this
你可以用这个
num_classes=...
and the last layers will be
最后一层将是
model.add(Dense(num_classes, activation='softmax'))
回答by disha Doshi
I also got the same error and solved it by setting class_mode
as categorical
instead of binary
我也遇到了同样的错误并通过设置class_mode
为categorical
而不是binary
回答by Mondaa
The problem is with the shape of the labels of the data "Y".
The shape you have for the labels are (m,) and this will not work with the:
问题在于数据“Y”的标签形状。
标签的形状是 (m,) 并且这不适用于:
loss = "binary_crossentropy"
I believe if you don't want to play with the shape of the labels, then use:
我相信如果你不想玩标签的形状,那么使用:
loss = "sparse_categorical_crossentropy"