我最近开始玩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 模型提供的默认图像?
如果我对深度学习没有足够的理解,我很抱歉,但是请有人向我解释一下。谢谢
最佳答案
(1,224,224,3)
的 4 个维度是 batch_size
、image_width
、image_height
和 image_channels
分别。 (1,224,224,3)
表示 VGG16
模型接受形状为 224x224 的
和三个 channel (RGB)。1
批量大小(一次一张图像)
有关什么是批处理
以及批处理大小
的更多信息,您可以查看 this交叉验证的问题。
回到VGG16
,架构的输入是(1, 224, 224, 3)
。这是什么意思?为了将图像输入网络,您需要:
- 对其进行预处理以达到 (224, 224) 和 3 channel (RGB) 的形状
- 将其转换为形状为 (224, 224, 3) 的实际矩阵
- 将各种图像分组到需要网络大小的批处理中(在本例中,批处理大小为 1,但需要向矩阵添加一个维度,以获得 (1, 224, 224 , 3)
完成此操作后,您可以将图像输入到模型中。
Keras 提供了一些实用函数来完成这些任务。下面我展示了 Extract features with VGG16 from Usage examples for image classification models 中所示代码片段的修改版本。在文档中。
为了让它实际工作,您需要一个任意大小的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)
您可以一路添加打印来查看发生了什么,但这里有一个简短的摘要:
image.load_img()
加载一个 PIL 图像,该图像已经是 RGB 格式并且已经将其 reshape 为 (224, 224)image.img_to_array()
正在将此图像转换为形状为 (224, 224, 3) 的矩阵。如果访问 x[0, 0, 0],您将获得第一个像素的红色分量,作为 0 到 255 之间的数字np.expand_dims(x, axis=0)
正在添加第一个维度。 x 之后的形状为(1, 224, 224, 3)
preprocess_input
正在进行 imagenet 训练架构所需的额外预处理。从它的文档字符串(运行help(preprocess_input)
)你可以看到它:will convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling
这似乎是 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)]]
看起来不错!
关于python - Keras:VGG16 中的 model.inputs 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395427/