[英]How can I visualize the weights(variables) in cnn in Tensorflow?
訓練完cnn模型后,想可視化權重或者打印權重,怎么辦? 訓練后我什至無法打印出變量。 謝謝!
要可視化權重,可以使用tf.image_summary()
op將卷積過濾器(或過濾器的一部分)轉換為摘要原型,使用tf.train.SummaryWriter
將其寫入日志,並可視化日志使用TensorBoard 。
假設您有以下(簡化)程序:
filter = tf.Variable(tf.truncated_normal([8, 8, 3]))
images = tf.placeholder(tf.float32, shape=[None, 28, 28])
conv = tf.nn.conv2d(images, filter, strides=[1, 1, 1, 1], padding="SAME")
# More ops...
loss = ...
optimizer = tf.GradientDescentOptimizer(0.01)
train_op = optimizer.minimize(loss)
filter_summary = tf.image_summary(filter)
sess = tf.Session()
summary_writer = tf.train.SummaryWriter('/tmp/logs', sess.graph_def)
for i in range(10000):
sess.run(train_op)
if i % 10 == 0:
# Log a summary every 10 steps.
summary_writer.add_summary(filter_summary, i)
完成此操作后,您可以啟動TensorBoard以可視化/tmp/logs
,並且您將能夠看到過濾器的可視化。
請注意,此技巧將深度為3的濾鏡可視化為RGB圖像(以匹配輸入圖像的通道)。 如果您有更深的濾鏡,或者將它們解釋為顏色通道沒有意義,則可以使用tf.split()
op在深度維度上拆分濾鏡,並為每個深度生成一個圖像摘要。
就像@mrry所說的,您可以使用tf.image_summary
。 例如,對於cifar10_train.py
,您可以將此代碼放在def train()
下的某個位置。 注意如何在作用域'conv1'下訪問var
# Visualize conv1 features
with tf.variable_scope('conv1') as scope_conv:
weights = tf.get_variable('weights')
# scale weights to [0 255] and convert to uint8 (maybe change scaling?)
x_min = tf.reduce_min(weights)
x_max = tf.reduce_max(weights)
weights_0_to_1 = (weights - x_min) / (x_max - x_min)
weights_0_to_255_uint8 = tf.image.convert_image_dtype (weights_0_to_1, dtype=tf.uint8)
# to tf.image_summary format [batch_size, height, width, channels]
weights_transposed = tf.transpose (weights_0_to_255_uint8, [3, 0, 1, 2])
# this will display random 3 filters from the 64 in conv1
tf.image_summary('conv1/filters', weights_transposed, max_images=3)
如果要在一個漂亮的網格中可視化所有conv1
過濾器,則必須自己將它們組織到一個網格中。 我今天做了,所以現在我想分享將conv1可視化為網格的要點
您可以通過以下方式將值提取為numpy數組:
with tf.variable_scope('conv1', reuse=True) as scope_conv:
W_conv1 = tf.get_variable('weights', shape=[5, 5, 1, 32])
weights = W_conv1.eval()
with open("conv1.weights.npz", "w") as outfile:
np.save(outfile, weights)
請注意,您必須調整范圍(在我的情況下為'conv1'
)和變量名稱(在我的情況下為'weights'
)。
然后歸結為可視化numpy數組。 如何可視化numpy數組的一個示例是
#!/usr/bin/env python
"""Visualize numpy arrays."""
import numpy as np
import scipy.misc
arr = np.load('conv1.weights.npb')
# Get each 5x5 filter from the 5x5x1x32 array
for filter_ in range(arr.shape[3]):
# Get the 5x5x1 filter:
extracted_filter = arr[:, :, :, filter_]
# Get rid of the last dimension (hence get 5x5):
extracted_filter = np.squeeze(extracted_filter)
# display the filter (might be very small - you can resize the window)
scipy.misc.imshow(extracted_filter)
使用tensorflow 2 API
,有幾個選項:
使用get_weights()
函數提取的權重。
weights_n = model.layers[n].get_weights()[0]
使用numpy()
轉換函數提取偏差。
bias_n = model.layers[n].bias.numpy()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.