【问题标题】:Keras Error - expected activation_1 to have shape (2622,) but got array with shape (1,)Keras 错误 - 预期 activation_1 的形状为 (2622,) 但数组的形状为 (1,)
【发布时间】:2019-01-13 13:31:58
【问题描述】:

大家好,我正在尝试在 Keras 上制作预训练的 VGG16 但它一直给我错误:

ValueError:检查目标时出错:预期activation_1 有 形状 (2622,) 但得到了形状 (1,) 的数组

我试图根据这张海报创建模型:Link

另外,我从here 中获取了预训练的权重。这个重量可以在here上阅读

这是我的代码:

from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, ZeroPadding2D
from keras import backend as K


# dimensions of our images.
img_width, img_height = 224, 224

train_data_dir = 'database/train'
validation_data_dir = 'database/validation'
nb_train_samples = 2000
nb_validation_samples = 800
epochs = 50
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

# build the VGG16 network
model = applications.VGG16(weights='imagenet', include_top=False)
print('VGG Pretrained Model loaded.')

model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(256, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Conv2D(512, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))

model.add(Conv2D(4096, (7, 7), activation='relu'))
model.add(Dropout(0.5))
model.add(Conv2D(4096, (1, 1), activation='relu'))
model.add(Dropout(0.5))
model.add(Conv2D(2622, (1, 1)))
model.add(Flatten())
model.add(Activation('softmax'))

# model.load_weights('./vgg16_face_weights.h5')
#
# vgg_face_descriptor = Model(inputs=model.layers[0].input, outputs=model.layers[-2].output)

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 224,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 224)

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 = test_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=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save_weights('first_try.h5')

【问题讨论】:

  • 你有几节课?
  • @matias 我有 12 节课

标签: python-3.x keras conv-neural-network vgg-net


【解决方案1】:

'database/train''database/validation' 中可能只有一个文件夹。

请确保这两个文件夹中有2622个文件夹,这样keras才能正确生成标签。

以下示例显示标签的形状应为 (batch_size, 2622)。

# the above remains the same
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

import numpy as np

classes = 2622
batch_size = 4
y = np.zeros((batch_size, classes))
for i in range(batch_size):
    y[i, np.random.choice(classes)] = 1

model.fit(x=np.random.random((batch_size,)+input_shape), y=y, batch_size=batch_size)

model.save_weights('first_try.h5')

编辑:

要将最后一个 Conv2D 层从 2622 个过滤器更改为 12 个过滤器,同时保持加载的权重,这里有一个解决方法:

#define model and load_weights
#......

#build a new model based on the last model
conv = Conv2D(12, (1, 1))(model.layers[-4].output)
flatten = Flatten()(conv)
softmax = Activation('softmax')(flatten)
final_model = Model(inputs=model.input, outputs=softmax)

参考:Cannot add layers to saved Keras Model. 'Model' object has no attribute 'add'

【讨论】:

  • 我尝试让它只识别 12 个人(12 个文件夹)。但是 VGG-16 Pretrained 模型使用 2622 人脸。所以我想用那个重量(有 2622 面)注入我的模型。该怎么做?
猜你喜欢
  • 2019-11-18
  • 2020-02-05
  • 2018-12-16
  • 2020-05-29
  • 2020-05-14
  • 2019-05-09
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
相关资源
最近更新 更多