Skip to main content
 首页 » 编程设计

python之如何在Keras R中提取VGG16的top-K层

2024年09月07日9fff_TT

我正在尝试从预测图像中提取特征。 它是基于这个 article由 JJ。阿莱尔。

基本上它所做的是使用经过训练的模型并选择 top-K层并识别在其中激活的图像区域 每层。

我的模型可以下载 here (134Mb),测试猫图片可下载here .

模型看起来像这样:

> summary(model) 
___________________________________________________________________________________________________________________________________________________________________________________________________ 
Layer (type)                                                                           Output Shape                                                                  Param #                        
=================================================================================================================================================================================================== 
vgg16 (Model)                                                                          (None, 4, 4, 512)                                                             14714688                       
___________________________________________________________________________________________________________________________________________________________________________________________________ 
flatten_1 (Flatten)                                                                    (None, 8192)                                                                  0                              
___________________________________________________________________________________________________________________________________________________________________________________________________ 
dense_1 (Dense)                                                                        (None, 256)                                                                   2097408                        
___________________________________________________________________________________________________________________________________________________________________________________________________ 
dense_2 (Dense)                                                                        (None, 1)                                                                     257                            
=================================================================================================================================================================================================== 
Total params: 16,812,353 
Trainable params: 16,552,193 
Non-trainable params: 260,160 
___________________________________________________________________________________________________________________________________________________________________________________________________     

这是我的完整代码:

library(keras) 
model_file <- "data/kaggle_cats_dogs_small/model//model.hdf5" 
model <- load_model_hdf5(model_file) 
summary(model) 
 
img_path <- "data/kaggle_cats_dogs_small/test_generic/cat.5009.jpg" 
# We preprocess the image into a 4D tensor 
img <- image_load(img_path, target_size = c(150, 150)) 
img_tensor <- image_to_array(img) 
img_tensor <- array_reshape(img_tensor, c(1, 150, 150, 3)) 
# Remember that the model was trained on inputs 
# that were preprocessed in the following way: 
img_tensor <- img_tensor / 255 
dim(img_tensor) 
 
 
# Display picture --------------------------------------------------------- 
 
plot(as.raster(img_tensor[1,,,])) 
 
# Extracting layers and activation ---------------------------------------- 
# Extracts the outputs of the top 8 layers: 
layer_outputs <- lapply(model$layers[1:8], function(layer) layer$output) 
# Creates a model that will return these outputs, given the model input: 
activation_model <- keras_model(inputs = model$input, outputs = layer_outputs) 

它在最后两行代码处中断:

> layer_outputs <- lapply(model$layers[1:8], function(layer) layer$output) 
 Show Traceback 
 
 Rerun with Debug 
 Error in py_get_attr_impl(x, name, silent) :  
  AttributeError: Layer vgg16 has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `get_output_at(node_index)` instead. > # Creates a model that will return these outputs, given the model input: 
> activation_model <- keras_model(inputs = model$input, outputs = layer_outputs) 
 Show Traceback 
 
 Rerun with Debug 
 Error in py_call_impl(callable, dots$args, dots$keywords) :  
  RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("input_1_4:0", shape=(?, 150, 150, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: [] 

正确的做法是什么?

请您参考如下方法:

当此消息(多个入站节点)出现时,表示该模型已与原始输入以外的另一个输入一起使用。 (因此该模型有很多输入,尽管您只使用了一个可能的路径。即,它具有 VGG 原始输入以及您用于创建堆叠模型的另一个输入)。

要执行您想执行的操作,您必须在创建堆叠模型之前执行此操作。

一些伪代码(抱歉不熟悉 R 符号):

VGGModel <- functionToCreateVGG 
layer_outputs <- lapply(VGGModel$layers[1:8], function(layer) layer$output) 
activation_model <- keras_model(inputs = VGGModel$input, outputs = layer_outputs) 

当您在添加顶层之前执行此操作时,VGG 模型还没有多个入站节点。

现在您像以前一样将顶层堆叠到 VGG 模型上。

另一种选择是为 activation_model 创建另一个 VGG 模型(如果您没有训练 VGG 模型)。