我想将高斯层模型添加到预训练的vgg16网络中(在卷积层1之后),并在通过图像时使嘈杂的层处于活动状态(我希望在通过噪声层后获得层的激活)推断阶段)。
我设法编译了一个“新”模型,其中添加了高斯层。我也有用于传递图像并获得对它们的激活的代码(使用model.predict(img))。我的问题是,现在当我将图像通过高斯噪声层传递时,激活不会从事先通过该层改变。我已经读过高斯噪声层通常用于训练中(而不是测试-对我来说很重要),但我也读过您可以“欺骗”一层以使您相信自己处于训练状态并且仍然拥有高斯噪声噪音活跃。我不知道该如何实际实施。
在这里,我用高斯噪声层创建新模型:
# load the model
model = VGG16(weights='imagenet')
# summarize the model
model.summary()
# loop over layers and add noise - create a new model
for i in range(1,len(model.layers)): # loop over all layers
#print ('Working on '+layer_names[i])
layer1 = model.layers[i]
if i==1: # adding the noise
noise = GaussianNoise(0.85)
x = noise(layer1.output)
if i<len(model.layers)-1: # reconnecting the layers
layer2 = model.layers[i+1]
x = layer2(x)
if i==len(model.layers)-1:
predictors = x # this is the last layer
# Create a new model
model2 = Model(input=model.input, output=predictors)
model2.summary()
这是我希望如何激活所有层(包括高斯层)的示例。
layer_names = ['block1_conv1',model2.layers[2].name,'block1_conv2','block2_conv1','block2_conv2','block3_conv1','block3_conv2','block3_conv3',\
'block4_conv1','block4_conv2','block4_conv3','block5_conv1','block5_conv2','block5_conv3','fc1','fc2','predictions'];
for i in range(1,len(layer_names)): # loop over all layers
print ('Working on '+layer_names[i])
layer_name = layer_names[i]
intermediate_layer_model = Model(inputs=model2.input,outputs=model2.get_layer(layer_name).output)
# load the image with the required shape
img = image.load_img('test.BMP', target_size=(224,224)) # plot with img
# convert the image to an array
img = image.img_to_array(img)
# expand dimensions so that it represents a single 'sample'
img = np.expand_dims(img, axis=0)
# prepare the image (e.g. scale pixel values for the vgg)
img = preprocess_input(img)
# Now get the activations to this image
intermediate_output = intermediate_layer_model.predict(img)
从block1_cov1层与gaussian_noise层接收到输出后,输出(intermediate_output)应该有所不同,但不是。我猜这是因为高斯噪声层没有激活,但是我不知道如何改变它。我知道我的代码不是很理想(只是开始与Keras一起使用),但是对于如何将噪声引入预训练的网络并使其通过网络“传播”的任何帮助,我们将不胜感激。