Skip to main content
 首页 » 编程设计

python之Tensorflow之可视化预训练网络的学习过滤器

2024年08月15日27lexus

我目前正在尝试使用 python 中的 tensorflow 可视化我的 CNN 学习的过滤器。 我发现许多版本在训练新网络时都使用 mnist 数据集,但无法将其应用于我的应用程序。 我使用自定义数据集训练了一个存储在我的磁盘上的 Estimator 对象。该模型包含层,例如

conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.sigmoid) 

并且只想可视化对维度为 (28,28,3) 的单张图片的预测。 在 tensorboard 中,这一层简称为“conv2d”,其他层称为“conv2d_2”等等,它与默认 MNIST 网络的结构基本相同,只是它使用了 sigmoid 函数。

我不知道如何实现这个——我考虑过获取权重和偏差并根据步幅和过滤器大小重新计算每一层,但我已经无法获取权重,我认为有一个更简单的解决方案。

请您参考如下方法:

I'm currently trying to visualize the learned filters of my CNN with tensorflow in python.

我认为你的意思是可视化特定层的激活?如果是这样,你只需要像这样为你想要的图像运行这一层的张量:

import matplotlib.pyplot as plt 
 
# Model definition 
... 
conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.sigmoid) 
... 
 
# Getting activations 
acts = sess.run(conv1, {input_layer: your_image}) 
 
# Visualizing every filters 
for i in range(acts.shape[3]): 
  plt.imshow(acts[:,:,:,i].squeeze()) 
  plt.show() 

如果您使用的是 Estimator,则可以使用 model_fn 中的 tf.summary.image() 直接可视化激活的演变:

# In model_fn 
... 
conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.sigmoid) 
acts_filters = tf.unstack(conv1, axis=3) 
for i, filter in enumerate(acts_filters): 
    tf.summary.image('filter' + str(i), tf.expand_dims(filter, axis=3))