我正在尝试根据图片和文字对产品进行分类,但遇到错误
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)不兼容
任何人都可以帮我解决错误。在此先感谢..
答案 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以获取更多信息