【发布时间】: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,并期望它具有相同的输出。但是我不知道该怎么做,有人可以给我一些建议吗?非常感谢。
【问题讨论】: