`tf.reshape(a, [m, n])` 和 `tf.transpose(tf.reshape(a, [n, m]))` 之间的区别?

xin*_*Liu 6 python numpy matrix deep-learning tensorflow

其实我正在coursera上做deeplearning.ai的作业“Art Generation with Neural Style Transfer”。在函数中compute_layer_style_cost(a_S, a_G):

a_S = tf.reshape(a_S, [n_H*n_W, n_C])
a_G = tf.reshape(a_G, [n_H*n_W, n_C])

GS = gram_matrix(tf.transpose(a_S))
GG = gram_matrix(tf.transpose(a_G))
Run Code Online (Sandbox Code Playgroud)

为什么这段代码给出了正确的答案,但是以下代码却没有给出正确的答案:

a_S = tf.reshape(a_S, [n_C, n_H*n_W])
a_G = tf.reshape(a_G, [n_C, n_H*n_W])

GS = gram_matrix(a_S)
GG = gram_matrix(a_G)
Run Code Online (Sandbox Code Playgroud)

Max*_*xim 4

这是一个简单的示例,显示了这两个表达式之间的差异:

import tensorflow as tf
tf.InteractiveSession()

x = tf.range(0, 6)
a = tf.reshape(x, [3, 2])
b = tf.transpose(tf.reshape(x, [2, 3]))

print(x.eval())
print(a.eval())
print(b.eval())
Run Code Online (Sandbox Code Playgroud)

结果:

[0 1 2 3 4 5]

[[0 1]
 [2 3]
 [4 5]]

[[0 3]
 [1 4]
 [2 5]]
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,ab是不同的,尽管具有相同的形状。这是因为第一次重塑“分裂”x[0 1],[2 3][4 5],而第二次重塑“分裂”为[0 1 2][3 4 5]