【问题标题】:Displaying RNN using tf.summary.image give error in python tensorflow使用 tf.summary.image 显示 RNN 在 python tensorflow 中给出错误
【发布时间】:2019-02-10 14:47:40
【问题描述】:

这是我尝试过的:

tf.reset_default_graph()
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None,n_outputs])
layers = [tf.contrib.rnn.LSTMCell(num_units=n_neurons, 
                                 activation=tf.nn.leaky_relu, use_peepholes = True)
         for layer in range(n_layers)]
multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)
rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)
tf.summary.histogram("outputs", rnn_outputs)
tf.summary.image("RNN",rnn_outputs)

我收到以下错误:

InvalidArgumentError: Tensor must be 4-D with last dim 1, 3, or 4, not [55413,4,100]
     [[Node: RNN_1 = 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/device:CPU:0"](RNN_1/tag, rnn/transpose_1)]]

请帮助我在我试图运行的 LSTM 模型中获得 rnn 的可视化。这将有助于更准确地理解 LSTM 在做什么。

【问题讨论】:

    标签: python python-3.x tensorflow tensorboard


    【解决方案1】:

    您可以将每个 RNN 输出绘制为图像,其中一个轴是时间,另一个轴是输出。这是一个小例子:

    import tensorflow as tf
    import numpy as np
    
    n_steps = 100
    n_inputs = 10
    n_neurons = 10
    n_layers = 3
    
    x = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
    layers = [tf.contrib.rnn.LSTMCell(num_units=n_neurons,
                                      activation=tf.nn.leaky_relu, use_peepholes=True)
             for layer in range(n_layers)]
    multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)
    rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, x, dtype=tf.float32)
    # Time steps in horizontal axis, outputs in vertical axis, add last dimension for channel
    rnn_out_imgs = tf.transpose(rnn_outputs, (0, 2, 1))[..., tf.newaxis]
    out_img_sum = tf.summary.image("RNN", rnn_out_imgs, max_outputs=10)
    init_op = tf.global_variables_initializer()
    with tf.Session() as sess, tf.summary.FileWriter('log') as fw:
        sess.run(init_op)
        fw.add_summary(sess.run(out_img_sum, feed_dict={x: np.random.rand(10, n_steps, n_inputs)}))
    

    你会得到一个看起来像这样的可视化:

    这里更亮的像素代表更强的激活,所以即使很难说出究竟是什么导致了什么,你至少可以看到是否有任何有意义的模式出现。

    【讨论】:

      【解决方案2】:

      您的 RNN 输出的 tf.summary.image 形状错误。张量应该是四维的,尺寸由 [batch_size, height, width, channels] 给出。

      在您的代码中,您使用 rnn_outputs 调用 tf.summary.image,其形状为 [55413, 4, 100]。假设您的图像大小为 55413 x 100 像素,并且每个像素包含 4 个通道 (RGBA),我将使用 tf.reshapernn_outputs 重塑为 [1, 55413, 100, 4]。那么你应该可以毫无错误地调用tf.summary.image

      我不认为我可以帮助你可视化 RNN 的操作,但是当我学习 RNN 和 LSTM 时,我发现 this article 非常有帮助。

      【讨论】:

        猜你喜欢
        • 2018-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-06-03
        • 1970-01-01
        • 2017-06-11
        • 2021-09-02
        • 2018-06-15
        • 1970-01-01
        相关资源
        最近更新 更多