【问题标题】:How to use Conv2D.set_weights in keras?如何在 keras 中使用 Conv2D.set_weights?
【发布时间】:2020-02-24 07:13:24
【问题描述】:

我遵循Keras:Applications 中的“使用 VGG19 从任意中间层提取特征”部分。我可以得到输入:input_1和第一层卷积:block1_conv1的权重和偏差,以及该层的输出。

from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input, decode_predictions
from keras.models import Model
import numpy as np

base_model = VGG16(weights='imagenet')
model = Model(inputs=base_model.input, outputs=base_model.get_layer('block1_conv1').output)
model.summary()

# Get weight and bias of block1_conv1
block1_conv1 = model.get_layer("block1_conv1")
weight, bias = block1_conv1.get_weights()
print("weight dtype:{}, shape:{}".format(weight.dtype, weight.shape))
print("bias length:{}".format(len(bias)))

# Get the image input
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

# Get the output of block1_conv1
block1_conv1_features = model.predict(x)
print(block1_conv1_features.size, block1_conv1_features.shape)
print(block1_conv1_features[0][0][0][:5])

现在,我想创建一个 keras.layers 的 Conv2D(keras.layers import Conv2D),设置相同的 input:x 和 weight/bias,并期望它具有相同的输出。但是我不知道该怎么做,有人可以给我一些建议吗?非常感谢。

【问题讨论】:

    标签: python keras


    【解决方案1】:
    # get the configuration the this layer or set by yourself
    config = model.get_layer('block1_conv1').get_config()
    
    conv_model = Sequential()
    conv_model.add(Conv2D(config['filters'], kernel_size=config['kernel_size'], \
        strides=config['strides'], input_shape=(224, 224, 3), \
        padding=config['padding'], data_format=config['data_format'], \
        activation=config['activation'], use_bias=config['use_bias']))
    model.set_weights([w, b])
    # calculate the layer
    out = model.predict(x)
    # compare the result
    np.array_equal(block1_conv1_features, out)
    

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 2019-08-21
      • 2019-04-15
      • 2017-12-29
      • 2018-06-30
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多