首页 > 解决方案 > Keras:VGG16 中的 model.inputs 是什么

问题描述

我最近开始玩 keras 和 vgg16,我正在使用 keras.applications.vgg16。

但是在这里我提出了一个问题,model.inputs因为我看到其他人在https://github.com/keras-team/keras/blob/master/examples/conv_filter_visualization.py中使用它,尽管它没有初始化它

    ...
    input_img = model.input
    ...
    layer_output = layer_dict[layer_name].output
    if K.image_data_format() == 'channels_first':
        loss = K.mean(layer_output[:, filter_index, :, :])
    else:
        loss = K.mean(layer_output[:, :, :, filter_index])

    # we compute the gradient of the input picture wrt this loss
    grads = K.gradients(loss, input_img)[0]

我检查了 keras 网站,但它只说这是一个形状为 (1,224,224,3) 的输入张量,但我仍然不明白那到底是什么。那是来自 ImageNet 的图像吗?还是 keras 为 keras 模型提供的默认图像?

如果我对深度学习没有足够的了解,我很抱歉,但是请有人向我解释一下。谢谢

标签: pythontensorflowkeras

解决方案


的 4个维度(1,224,224,3)分别是batch_sizeimage_width和。意味着该模型接受批量大小(一次一张图像)形状和三个通道(RGB)。image_heightimage_channels(1,224,224,3)VGG161224x224

有关 abatch和 abatch size是什么的更多信息,您可以查看交叉验证问题。

回到VGG16,架构的输入是(1, 224, 224, 3)。这是什么意思?为了将图像输入网络,您需要:

  1. 对其进行预处理以达到 (224, 224) 和 3 通道 (RGB) 的形状
  2. 将其转换为实际的形状矩阵 (224, 224, 3)
  3. 将需要网络大小的batch中的各种图像组合在一起(在这种情况下,batch size为1,但是您需要在矩阵中添加一个维度,以获得(1, 224, 224, 3)

完成此操作后,您可以将图像输入到模型中。

Keras 提供了很少的实用功能来完成这些任务。下面我展示了文档中图像分类模型的使用示例中使用 VGG16 提取特征中显示的代码片段的修改版本。

为了让它真正工作,你需要一个jpg名为elephant.jpg. 您可以运行以下 bash 命令获取它:

wget https://upload.wikimedia.org/wikipedia/commons/f/f9/Zoorashia_elephant.jpg -O elephant.jpg   

为了清楚起见,我将在图像预处理和模型预测中拆分代码:

加载图像

import numpy as np
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_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)

您可以沿途添加打印以查看发生了什么,但这里有一个简短的摘要:

  1. image.load_img()加载一个 PIL 图像,已经是 RGB 并且已经将其重塑为 (224, 224)
  2. image.img_to_array()正在将此图像转换为形状矩阵 (224, 224, 3)。如果您访问, x[0, 0, 0] 您将获得第一个像素的红色分量,作为 0 到 255 之间的数字
  3. np.expand_dims(x, axis=0)正在添加第一个维度。x 之后是有形状的(1, 224, 224, 3)
  4. preprocess_input正在执行 imagenet 训练架构所需的额外预处理。从它的 docstring (run help(preprocess_input)) 你可以看到它:

    将图像从 RGB 转换为 BGR,然后将相对于 ImageNet 数据集的每个颜色通道归零,而不进行缩放

这似乎是 ImageNet 训练集的标准输入。

预处理就是这样,现在您只需在预训练模型中输入图像并获得预测

预测

y_hat = base_model.predict(x)
print(y_hat.shape) # res.shape (1, 1000)

y_hat包含模型分配给该图像的 1000 个 imagenet 类中的每一个的概率。

为了获得类名和可读的输出,keras 也提供了一个实用函数:

from keras.applications.vgg16 import decode_predictions
decode_predictions(y_hat)

输出,对于Zoorashia_elephant.jpg我之前下载的图像:

[[('n02504013', 'Indian_elephant', 0.48041093),
  ('n02504458', 'African_elephant', 0.47474155),
  ('n01871265', 'tusker', 0.03912963),
  ('n02437312', 'Arabian_camel', 0.0038948185),
  ('n01704323', 'triceratops', 0.00062475674)]]

这看起来不错!


推荐阅读