【问题标题】:tf.reshape vs tf.contrib.layers.flattentf.reshape 与 tf.contrib.layers.flatten
【发布时间】:2018-08-30 14:12:23
【问题描述】:

所以我正在运行一个 CNN 来解决分类问题。我有 3 个卷积层和 3 个池化层。 P3 是最后一个池化层的输出,其维度为:[Batch_size, 4, 12, 48],我想将该矩阵展平为[Batch_size, 2304] 大小的矩阵,即2304 = 4*12*48。我一直在使用“选项 A”(见下文)一段时间,但有一天我想尝试“选项 B”,理论上这会给我同样的结果。然而,它没有。我之前检查过以下线程

Is tf.contrib.layers.flatten(x) the same as tf.reshape(x, [n, 1])?

但这只会增加更多的混乱,因为尝试“选项 C”(取自上述线程)给出了一个新的不同结果。

P3 = tf.nn.max_pool(A3, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding='VALID')

P3_shape = P3.get_shape().as_list()

P = tf.contrib.layers.flatten(P3)                             <-----Option A

P = tf.reshape(P3, [-1, P3_shape[1]*P3_shape[2]*P3_shape[3]]) <---- Option B

P = tf.reshape(P3, [tf.shape(P3)[0], -1])                     <---- Option C

我更倾向于选择“选项 B”,因为这是我在 Dandelion Mane (https://www.youtube.com/watch?v=eBbEDRsCmv4&t=631s) 的视频中看到的,但我想了解为什么这 3 个选项会给出不同的结果。

【问题讨论】:

    标签: python tensorflow conv-neural-network


    【解决方案1】:

    所有 3 个选项都以相同的方式重塑:

    import tensorflow as tf
    import numpy as np
    
    p3 = tf.placeholder(tf.float32, [None, 1, 2, 4])
    
    p3_shape = p3.get_shape().as_list()
    
    p_a = tf.contrib.layers.flatten(p3)                                  # <-----Option A
    
    p_b = tf.reshape(p3, [-1, p3_shape[1] * p3_shape[2] * p3_shape[3]])  # <---- Option B
    
    p_c = tf.reshape(p3, [tf.shape(p3)[0], -1])                          # <---- Option C
    
    print(p_a.get_shape())
    print(p_b.get_shape())
    print(p_c.get_shape())
    
    with tf.Session() as sess:
        i_p3 = np.arange(16, dtype=np.float32).reshape([2, 1, 2, 4])
        print("a", sess.run(p_a, feed_dict={p3: i_p3}))
        print("b", sess.run(p_b, feed_dict={p3: i_p3}))
        print("c", sess.run(p_c, feed_dict={p3: i_p3}))
    

    这段代码产生了 3 次相同的结果。您的不同结果是由其他原因造成的,而不是由重塑造成的。

    【讨论】:

    • 感谢 BlueSun。我正在查看成本函数,但没有得到相同的结果,但当然这是由于其他原因,那就是我使用 tf.contrib.layers.xavier_initializer()接下来两个全连接层的权重初始化,但不使用任何种子。修复种子就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 2017-02-01
    • 1970-01-01
    • 2018-12-28
    • 2018-09-30
    • 2021-01-25
    • 1970-01-01
    相关资源
    最近更新 更多