0

使用使用 Keras 的 VGG 16,我正在尝试运行三类分类问题,代码如下:

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()  

运行代码,我收到错误:

检查目标时出错:预期 dense_20 的形状为 (None, 3) 但得到的数组的形状为 (1200, 1)

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

4

1 回答 1

2

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

但是您的模型以 结尾Dense(3),它将输出诸如 (None, 3) 之类的内容。即:每个样本有3个数字。

如果你认为你的训练数据是正确的,你必须调整你的模型。

一个建议是再增加Dense(1)一层。如果结果在 0 和 1 之间,则使用“sigmoid”激活,如果结果在 -1 和 1 之间,则使用“tanh”。

总是model.summary()用来检查你的模型有什么尺寸。

于 2017-05-23T01:44:17.933 回答