我如何可视化第一个卷积滤镜

时间:2017-06-20 10:09:02

标签: python tensorflow

我试图将第一个卷积滤镜的一些图像可视化,如链接http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb,但我遇到了一些错误

InvalidArgumentError (see above for traceback): Tensor must be 4-D with last dim 1, 3, or 4, not [10,123,123,16]
 [[Node: RelU_1/layer1 = ImageSummary[T=DT_FLOAT, bad_color=Tensor<type: uint8 shape: [4] values: 255 0 0...>, max_images=3, _device="/job:localhost/replica:0/task:0/cpu:0"](RelU_1/layer1/tag, RelU_1/h_1/_21)]]

我的一些代码:

w1 = tf.Variable(tf.random_normal([5, 5, 1, 16],stddev=0.1), name = 'w1')
b1 = tf.Variable(tf.zeros([16]), name = 'b1'

def model(data):    
  with tf.name_scope('conv1'):
    conv1 = tf.nn.conv2d(data, w1 , [1, 2, 2, 1], padding='VALID', name = "c1")
  with tf.name_scope('RelU_1'):
    hidden_1 = tf.nn.relu(conv1 + b1, name = 'h1')
    tf.summary.image('layer1',hidden_1, max_outputs=3)
.....



with tf.Session(graph=graph) as sess:

  merged = tf.summary.merge_all()
  train_writer = tf.summary.FileWriter("logs/" ,sess.graph)

  for step in range(num_steps):  
        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)       
        batch_data = train_dataset[offset:(offset + batch_size), :, :, :]      
        batch_labels = train_labels[offset:(offset + batch_size), :]                                     
        feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels, keep_prob:0.8}
        summary,_, l, predictions = sess.run([ merged,optimizer, loss, train_prediction ], feed_dict=feed_dict)
        train_writer.add_summary(summary, step)

1 个答案:

答案 0 :(得分:0)

首先获取w1

的值
values = sess.run(w1)
print "The shape should be [5,5,1,16] and actually is :",values.shape

显示数据

vis_square(values.transpose(3,0,1,2).reshape(16,5,5))
plt.show()

vis_square代码

def vis_square(data):
    """Take an array of shape (n, height, width) or (n, height, width, 3)
       and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""

    # normalize data for display
    data = (data - data.min()) / (data.max() - data.min())

    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = (((0, n ** 2 - data.shape[0]),
               (0, 1), (0, 1))                 # add some space between filters
               + ((0, 0),) * (data.ndim - 3))  # don't pad the last dimension (if there is one)
    data = np.pad(data, padding, mode='constant', constant_values=1)  # pad with ones (white)

    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])

    plt.imshow(data); plt.axis('off')

输出图像

以下是输出图像的示例

enter image description here