本文主要是介绍Tensorflow2.6.0实现VGG16卷积层特征图可视化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.参考博文:
这里非常感谢这位博主,让我对特征可视化有了进一步的了解:
https://blog.csdn.net/Forrest97/article/details/105895087
2.实验效果:
3.结果分析:
通过我画出来的一部分图,可以看出,随着卷积层数的加深,特征图越来越特化,像这张图片,更多的是提取图片中狗的眼睛和鼻子;而浅层更多的是提取图像的边缘和轮廓。所以随着网络的加深,图像的特征越来越特化,同时越来越难理解。
4.代码实现:
import os
import matplotlib
import tensorflow
import numpy as np
import matplotlib.pyplot as plt
from keras.preprocessing import image
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg16 import preprocess_input,decode_predictions
#加载模型
def load_model():model_vgg16=tensorflow.keras.applications.vgg16.VGG16(weights='imagenet')return model_vgg16#查询卷积层的名称
def block_layers_16():model_vgg16=load_model()layer_outputs = [layer.output for layer in model_vgg16.layers[:20]] #前20个conv输出model = Model(inputs=model_vgg16.input, outputs=layer_outputs) #构建能够输出前20个conv层的模型return modeldef featureVisualiztion(img_path):block_name=[layer.name for layer in load_model().layers[1:5]]model_vgg16 = block_layers_16()#将图像缩放到固定大小img=image.load_img(img_path,target_size=(224,224))#将图片转换为向量img=image.img_to_array(img)#对其维度进行扩充img=np.expand_dims(img,axis=0)#对输入到网络的图像进行处理output_img=preprocess_input(img)#预测图像features=model_vgg16.predict(output_img)feature1_shape=np.shape(features[0])print(feature1_shape)# model_vgg16.summary()#显示前五层的特征图for step,feature in enumerate(features[1:5]):#特征图的通道数//16=画图的行数rows=feature.shape[-1]//16subplots=np.zeros((int(feature.shape[1]*rows),int(16*feature.shape[1])))for row in range(rows):for col in range(16):#每一个通道的特征图feature_image=feature[0,:,:,row*16+col]subplots[row*feature.shape[1]:(row+1)*feature.shape[1],col*feature.shape[1]:(col+1)*feature.shape[1]]=feature_imagescale=1.0/feature.shape[1]plt.figure(figsize=(scale*subplots.shape[1],scale*subplots.shape[0]))plt.title(block_name[step])plt.grid(False)plt.imshow(subplots,aspect='auto',cmap='viridis')plt.show()if __name__ == '__main__':print('Pycharm')featureVisualiztion('images/dog.jpg')
这篇关于Tensorflow2.6.0实现VGG16卷积层特征图可视化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!