编程语言
首页 > 编程语言> > python – tf.reshape vs tf.contrib.layers.flatten

python – tf.reshape vs tf.contrib.layers.flatten

作者:互联网

所以我正在运行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”,因为这是我在蒲公英马恩(https://www.youtube.com/watch?v=eBbEDRsCmv4&t=631s)的视频中看到的那个,但我想理解为什么这3个选项给出了不同的结果.

解决方法:

所有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次.你的不同结果是由其他东西造成的,而不是由重塑造成的.

标签:python,tensorflow,conv-neural-network
来源: https://codeday.me/bug/20190522/1153089.html