Как использовать Conv2D.set_weights в керасе? - PullRequest
0 голосов
/ 24 февраля 2020

Я следую за разделом «Извлечение объектов из произвольного промежуточного слоя с помощью VGG19» в Keras: Applications . Я могу получить input: 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])

Теперь я хочу создать Conv2D (keras.layers import Conv2D) из keras .layers, установите один и тот же вход: x и weight / bias и ожидайте, что он будет иметь одинаковый результат. Но я не знаю, как это сделать, может кто-нибудь дать мне какое-нибудь предложение? Большое спасибо.

1 Ответ

0 голосов
/ 19 марта 2020
# 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...