本文主要是介绍使用Matplotlib子图展示卷积神经网络中间特征图层,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以下拿 fashion_mninst
来举例
import tensorflow as tf
import matplotlib as plt
from tensorflow.keras.datasets import fashion_mnist(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
# 预处理函数
def data_scale(x, y):x = tf.cast(x, tf.float32)x = x / 255.0x = tf.reshape(x, (x.shape[0], x.shape[1], 1))x = tf.image.resize_with_pad(image=x, target_height=224,target_width=224)return x, y
# 获取 fashion_mnist 数据集
train_db = tf.data.Dataset.from_tensor_slices((x_train,y_train)).shuffle(20).map(data_scale).batch(128)# 获取一组数据
X = next(iter(train_db))[0][0]
# 将这组数据输入训练好的模型,并打印中间层特征图def show(X, k,i, name):print(X.shape)X = tf.expand_dims(X, axis=-1)# 将每个图转换为 200 * 200的像素,但这个不是图大小X = tf.image.resize(X, [200,200], method='bilinear')X_ = tf.squeeze(X)t = plt.subplot(8, 4, 4*k + i + 1)# 添加子图的标题t.title.set_text('layer %s:'%k + name + '-' + str(i))plt.imshow(X_)X = tf.expand_dims(X, axis=0)# 设置图纸大小
plt.figure(figsize=(15, 15))
# 打印前 8 层的部分特征图
for k,blk in enumerate(net.layers[0:8]):print(blk.name,'itput shape:\t',X.shape)
# show(X[0,:,:,0])X = blk(X)print(blk.name, 'output shape:\t', X.shape)# 选择其中的四个通道for i in range(4):show(X[0,:,:,i], k, i, blk.name)
# 调整子图的间隔
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots,# expressed as a fraction of the average axis width
hspace = 0.6 # the amount of height reserved for white space between subplots,# expressed as a fraction of the average axis heightplt.subplots_adjust(left=left, bottom=bottom, right=right, top=top,wspace=wspace, hspace=hspace)plt.show()
效果如下:
这篇关于使用Matplotlib子图展示卷积神经网络中间特征图层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!