ValueError:图层权重形状(3、3、3、64)与提供的权重形状(64、3、3、3)不兼容 [英] ValueError: Layer weight shape (3, 3, 3, 64) not compatible with provided weight shape (64, 3, 3, 3)

查看:943
本文介绍了ValueError:图层权重形状(3、3、3、64)与提供的权重形状(64、3、3、3)不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to Classify products based on images and text, but running into errors

 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,在 set_weights'提供的重量形状'+ str(w.shape)) ValueError:图层权重形状(3、3、3、64)与提供的权重形状(64、3、3、3)不兼容

error: File "C:\Python\lib\site-packages\keras\engine\topology.py", line 1217, in set_weights 'provided weight shape ' + str(w.shape)) ValueError: Layer weight shape (3, 3, 3, 64) not compatible with provided weight shape (64, 3, 3, 3)

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

can any one please help me to resolve the error. Thanks in Advance..

推荐答案

问题似乎出在线路上

model.layers[k].set_weights(weights)

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

Keras initializes weights differently with different backends. If you are using theano as a backend, then weights will be initialized acc. to kernels_first and if you are using tensorflow as a backend, then weights will be initialized acc. to kernels_last.

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

So, the problem in you case seems to be that you are using tensorflow but are loading weights from a file which was created using theano as backend. The solution is to reshape your kernels using the keras conv_utils

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

检查 查看全文

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆