ValueError:图层重量形状(3,3,3,64)与提供的重量形状不兼容(64,3,3,3)

时间:2018-01-16 14:34:14

标签: python keras

我正在尝试根据图片和文字对产品进行分类,但遇到错误

 img_width, img_height = 224, 224
# build the VGG16 network
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=(img_width, img_height,3), name='image_input'))

model.add(Convolution2D(64, (3, 3), activation='relu', name='conv1_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, (3, 3), activation='relu', name='conv1_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))


# set trainable to false in all layers
for layer in model.layers:
    if hasattr(layer, 'trainable'):
        layer.trainable = False

return model

WEIGHTS_PATH='E:/'
weight_file = ''.join((WEIGHTS_PATH, '/vgg16_weights.h5'))
f = h5py.File(weight_file,mode='r')
for k in range(f.attrs['nb_layers']):
    if k >= len(model.layers):
        # we don't look at the last (fully-connected) layers in the savefile
        break
    g = f['layer_{}'.format(k)]
    weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
    model.layers[k].set_weights(weights)
f.close()
return model

load_weights_in_base_model(get_base_model())

错误:    文件" C:\ Python \ lib \ site-packages \ keras \ engine \ topology.py",第1217行,in   set_weights'提供重量形状' + str(w.shape)) ValueError:图层重量形状(3,3,3,64)与提供的重量形状(64,3,3,3)不兼容

任何人都可以帮我解决错误。在此先感谢..

1 个答案:

答案 0 :(得分:2)

问题似乎与行

有关
model.layers[k].set_weights(weights)

Keras使用不同的后端以不同方式初始化权重。如果您使用theano作为后端,则会根据acc初始化权重。到kernels_first并且如果您使用tensorflow作为后端,那么权重将被初始化为acc。到kernels_last

因此,您遇到的问题似乎是您正在使用tensorflow但是正在使用theano作为后端创建的文件加载权重。解决方案是使用keras conv_utils

重塑内核
from keras.utils.conv_utils import convert_kernel
reshaped_weights = convert_kernel(weights)
model.layers[k].set_weights(reshaped_weights)

检查this以获取更多信息