我一直在尝试检索VGG16的隐藏层,并在Keras中显示要素地图。我想要做的是获取block1_conv1
功能图并显示它。但不幸的是,我收到以下错误:
TypeError: Invalid dimensions for image data
请在下面找到代码:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
from keras.models import Model
import matplotlib.pyplot as plt
import numpy as np
from keras import backend as K
img_path = "bombiliki.jpeg"
img = image.load_img (img_path, target_size=(224,224))
imgArr = image.img_to_array (img)
imgArr = np.expand_dims(imgArr, axis=0)
img = preprocess_input (imgArr)
model = VGG16(weights='imagenet', include_top=False)
layer_name = 'block1_conv1'
interMediateOutput = Model(inputs=model.inputs, outputs=model.get_layer(layer_name).output)
features = interMediateOutput.predict (img)
print ("Shape of the feature is ", features.shape)
pic = features[:,:,:,1]
print ("pic shape ", pic.shape)
data = np.asarray(pic)
print ("Data Dimension is ", data.ndim)
plt.imshow (pic)
plt.show()
输出:
('Shape of the feature is ', (1, 224, 224, 64))
('pic shape ', (1, 224, 224))
('Data Dimension is ', 3)
Traceback (most recent call last):
File "vgg16.py", line 28, in <module>
plt.imshow (pic)
File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3205, in imshow
**kwargs)
File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/__init__.py", line 1855, in inner
return func(ax, *args, **kwargs)
File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 5487, in imshow
im.set_data(X)
File "/home/navals/anaconda2/envs/musarni/lib/python2.7/site-packages/matplotlib/image.py", line 653, in set_data
raise TypeError("Invalid dimensions for image data")
TypeError: Invalid dimensions for image data
答案 0 :(得分:2)
predict
方法将返回形状为(n_samples, model_output_shape...)
的输出。因此,如果您给它一个样本,则必须对给定样本进行预测:
pic = features[0]
特别是在您的示例中,如果要选择特定过滤器的输出,则需要将其索引指定为第四轴:
pic = features[0, :, :, desired_filter_index]
您可以轻松地绘制它们:
plt.imshow(pic)