如何在预训练模型中更改输入

时间:2019-06-02 02:18:42

标签: tensorflow keras deep-learning conv-neural-network

我想将相关VGGFACe模型的输入从224x224x3更改为64x64x3,该模型包含相关权重的是可以直接更改它。

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

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

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

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

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

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

from keras.models import model_from_json
model.load_weights('vgg_face_weights.h5')

直接更改输入大小会出现此错误

ValueError: Negative dimension size caused by subtracting 7 from 2 for 'sequential_1/conv2d_14/convolution' (op: 'Conv2D') with input shapes: [0,2,2,512], [7,7,512,4096].

代码来自https://sefiks.com/2018/08/06/deep-face-recognition-with-keras/

2 个答案:

答案 0 :(得分:0)

最后一个最大池化层使您的初始图像达到2x2大小。然后,您要在图像上应用7x7内核的卷积,这是不可能的。

此问题的解决方案是保留网络经过训练的图像的初始尺寸(224x224)(即,将图像带到该尺寸),或者更改神经网络的配置以避免这种情况降维问题。

答案 1 :(得分:0)

为什么不将尺寸为64x64x3的图像调整为224x224x3?

import cv2
img1 = cv2.imread("img1.jpg") #this is 64x64
img1_resized= cv2.resize(img1, (224, 224))

然后,您可以将img1_resized传递给VGG-Face模型。