Python Keras:如何部分加载重量?
如何部分加载模型权重?例如,我只想使用原始图像净重(Python Keras:如何部分加载重量?,python,tensorflow,keras,Python,Tensorflow,Keras,如何部分加载模型权重?例如,我只想使用原始图像净重(VGG19权重\u tf\u dim\u排序\u tf\u内核\u notop.h5)加载VGG19模型的block1: 此代码产生错误:ValueError:您试图将包含16层的权重文件加载到一个包含2层的模型中。来自Keras的vgg19应用程序模块默认具有imagenet的权重,因此我使用它加载我们在自定义模型中感兴趣的权重 input_shape = (224,224,3) full_vgg19 = tf.keras.applicat
VGG19权重\u tf\u dim\u排序\u tf\u内核\u notop.h5
)加载VGG19
模型的block1
:
此代码产生错误:
ValueError:您试图将包含16层的权重文件加载到一个包含2层的模型中。
来自Keras的vgg19应用程序模块默认具有imagenet的权重,因此我使用它加载我们在自定义模型中感兴趣的权重
input_shape = (224,224,3)
full_vgg19 = tf.keras.applications.VGG19(include_top=False, weights='imagenet', input_shape=input_shape)
def VGG19_part(full_vgg19, input_shape=None):
img_input = tf.keras.layers.Input(shape=input_shape)
# Block 1
x = tf.keras.layers.Conv2D(64, (3, 3),
activation='linear',
padding='same',
name='block1_conv1')(img_input)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(64, (3, 3),
activation='linear',
padding='same',
name='block1_conv2')(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
model = tf.keras.Model(img_input, x, name='vgg19')
model.set_weights(full_vgg19.get_weights()[:4])
return model
part_vgg19 = VGG19_part(full_vgg19, input_shape)
### check if the weights/bias are the same:
[(i == j).all() for i,j in zip(part_vgg19.get_weights()[:4],full_vgg19.get_weights()[:4])] # True True True True
input_shape = (224,224,3)
full_vgg19 = tf.keras.applications.VGG19(include_top=False, weights='imagenet', input_shape=input_shape)
def VGG19_part(full_vgg19, input_shape=None):
img_input = tf.keras.layers.Input(shape=input_shape)
# Block 1
x = tf.keras.layers.Conv2D(64, (3, 3),
activation='linear',
padding='same',
name='block1_conv1')(img_input)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.Conv2D(64, (3, 3),
activation='linear',
padding='same',
name='block1_conv2')(x)
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
model = tf.keras.Model(img_input, x, name='vgg19')
model.set_weights(full_vgg19.get_weights()[:4])
return model
part_vgg19 = VGG19_part(full_vgg19, input_shape)
### check if the weights/bias are the same:
[(i == j).all() for i,j in zip(part_vgg19.get_weights()[:4],full_vgg19.get_weights()[:4])] # True True True True