无法加载VGG16模型权重

时间:2018-04-20 05:56:13

标签: python keras jupyter-notebook

我正在使用此代码制作自己的VGG16网络:

# build the VGG16 network
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))
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), dim_ordering="th"))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_1'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu', name='conv2_2'))
model.add(MaxPooling2D((2, 2), strides=(2, 2), dim_ordering="th"))

# load the weights of the VGG16 networks
f = h5py.File(weights_path)
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()
print('Model loaded.')

但是当我调用我的方法时,它会崩溃:

  

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

我设置了K.set_image_dim_ordering('th')但仍然崩溃了。请帮忙。

1 个答案:

答案 0 :(得分:0)

如果您已经下载了vgg16_weights_tf_dim_ordering_tf_kernels weights,则应该以'tf'的顺序进行下载

K.set_image_dim_ordering('tf')