tf.reshape vs tf.contrib.layers.flatten

sdi*_*abr 6 python conv-neural-network tensorflow

所以我正在运行CNN来解决分类问题.我有3个带有3个池层的转换层.P3是最后一个合并图层的输出,其尺寸为:[Batch_size,4,12,48] _,我想将该矩阵展平为[Batch_size,2304]大小矩阵,为2304 = 4*12*48.我曾经使用"选项A"(见下文)一段时间,但有一天我想尝试"选项B",这在理论上会给我相同的结果.但事实并非如此.我之前已经开过以下帖子了

tf.contrib.layers.flatten(x)是否与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
Run Code Online (Sandbox Code Playgroud)

我更倾向于使用"选项B",因为这是我在蒲公英Mane的视频中看到的那个(https://www.youtube.com/watch?v=eBbEDRsCmv4&t=631s),但我想理解为什么这3个选项会给出不同的结果.

Blu*_*Sun 7

所有三个选项的重塑方式相同:

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}))
Run Code Online (Sandbox Code Playgroud)

此代码产生相同的结果3次。您的不同结果是由其他原因引起的,而不是由重塑引起的。