Skip to main content
 首页 » 编程设计

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

2025年01月19日9kevingrace

其实,我正在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)) 

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

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) 

请您参考如下方法:

这是一个简单的例子,显示了这两个表达式之间的区别:

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()) 

结果:

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

如您所见,a 和 b 虽然形状相同,但不同。这是因为第一个 reshape 将 x“拆分”为 [0 1]、[2 3] 和 [4 5],而第二个 reshape 为 [0 1 2] 和 [3 4 5]。