检查目标时出错:预期density_20具有形状(None,3),但获得形状为(1200,1)的数组 [英] Error when checking target: expected dense_20 to have shape (None, 3) but got array with shape (1200, 1)

查看:248
本文介绍了检查目标时出错:预期density_20具有形状(None,3),但获得形状为(1200,1)的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Keras的VGG 16,我试图运行一个三类分类问题,下面是代码:

With VGG 16 using Keras, I'm trying to run a three class classification problem and here is the code:

import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from keras import applications
from keras.optimizers import SGD
from keras import backend as K
K.set_image_dim_ordering('tf')
img_width, img_height = 48, 48
top_model_weights_path = 'vgg16_1.h5'
train_data_dir = 'data6/train'
validation_data_dir = 'data6/validation'
nb_train_samples = 400
nb_validation_samples = 100
epochs = 10
batch_size = 32
def save_bottlebeck_features():
   datagen = ImageDataGenerator(rescale=1. / 255)
   model = applications.VGG16(include_top=False, weights='imagenet', input_shape=(48, 48, 3))
   generator = datagen.flow_from_directory(
               train_data_dir,
               target_size=(img_width, img_height),
               batch_size=batch_size,
               class_mode='categorical',
               shuffle=False)
   bottleneck_features_train = model.predict_generator(
               generator, nb_train_samples // batch_size)
   np.save(open('bottleneck_features_train', 'wb'),bottleneck_features_train)

   generator = datagen.flow_from_directory(
               validation_data_dir,
               target_size=(img_width, img_height),
               batch_size=batch_size,
               class_mode='categorical',
               shuffle=False)
   bottleneck_features_validation = model.predict_generator(
               generator, nb_validation_samples // batch_size)
   np.save(open('bottleneck_features_validation', 'wb'),bottleneck_features_validation)

def train_top_model():
   train_data = np.load(open('bottleneck_features_train', 'rb'))
   train_labels = np.array(([0]*(nb_train_samples // 3) + [1]*(nb_train_samples // 3) + 
                            [2]*(nb_train_samples // 3)))
   validation_data = np.load(open('bottleneck_features_validation', 'rb'))
   validation_labels = np.array([0]*(nb_validation_samples // 3) + [1]*(nb_validation_samples // 3) + 
                                [2]*(nb_validation_samples // 3))
   model = Sequential()
   model.add(Flatten(input_shape=train_data.shape[1:]))
   model.add(Dense(128, activation='relu'))
   model.add(Dropout(0.5))
   model.add(Dense(3, activation='softmax'))
   sgd = SGD(lr=1e-2, decay=0.00371, momentum=0.9, nesterov=False)
   model.compile(optimizer=sgd,
         loss='categorical_crossentropy', metrics=['accuracy'])
   model.fit(train_data, train_labels,
          epochs=epochs,
          batch_size=batch_size,
   validation_data=(validation_data, validation_labels))
   model.save_weights(top_model_weights_path)

save_bottlebeck_features()
train_top_model()  

运行代码,出现错误:

检查目标时出错:预期density_20具有形状(无,3)但得到了 形状为(1200,1)的数组

Error when checking target: expected dense_20 to have shape (None, 3) but got array with shape (1200, 1)

请让我知道我必须对代码进行哪些更改才能使其正常运行.我正在Windows机器上运行的Anaconda和Python 3.5.2一起使用.

Kindly let me know what changes I have to make to the code to make it function. I'm using Anaconda with Python 3.5.2, running on a windows machine.

推荐答案

您的训练输出的形状像(None,1)---或(1200,1),其中有1200个样本,所有样本只有一个维度(每个样本都是一个数字)

Your training output is shaped like (None, 1) --- Or (1200, 1), where there are 1200 samples, all samples with only one dimension (each sample is a number)

但是您的模型以Dense(3)结尾,这将输出类似(None,3)的信息.即:每个样本有3个数字.

But your model ends with Dense(3), which will output things like (None, 3). That is: each sample has 3 numbers.

如果您认为训练数据正确,则必须调整模型.

If you think your training data is correct, you must adjust your model.

一个建议是再增加一个Dense(1)层.如果结果在0到1之间,则激活"Sigmoid";如果结果在-1和1之间,则激活"tanh".

A suggestion is add one more Dense(1) layer. With a "sigmoid" activation if the result is between 0 and 1, or a "tanh" if the result is between -1 and 1.

始终使用model.summary()检查模型的尺寸.

Always use model.summary() to check what dimensions your model have.

这篇关于检查目标时出错:预期density_20具有形状(None,3),但获得形状为(1200,1)的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆