回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>从<a href="https://www.tensorflow.org/api_docs/python/tf/transpose" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>Transposes <code>a</code>. Permutes the dimensions according to perm.</p>
<p>The returned tensor's dimension i will correspond to the input
dimension <code>perm[i]</code>. If <code>perm</code> is not given, it is set to (n-1...0), where
n is the rank of the input tensor. Hence by default, this operation
performs a regular matrix transpose on 2-D input Tensors.</p>
</blockquote>
<p>但我还是有点不清楚我该如何切片输入张量。E、 g.文件中也提到:</p>
<pre><code>tf.transpose(x, perm=[0, 2, 1]) ==> [[[1 4]
[2 5]
[3 6]]
[[7 10]
[8 11]
[9 12]]]
</code></pre>
<p>为什么<code>perm=[0,2,1]</code>会产生1x3x2张量?</strong></p>
<p>经过反复试验:</p>
<pre><code>twothreefour = np.array([ [[1,2,3,4], [5,6,7,8], [9,10,11,12]] ,
[[13,14,15,16], [17,18,19,20], [21,22,23,24]] ])
twothreefour
</code></pre>
<p>[出局]:</p>
<pre><code>array([[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]],
[[13, 14, 15, 16],
[17, 18, 19, 20],
[21, 22, 23, 24]]])
</code></pre>
<p>如果我转置它:</p>
<pre><code>fourthreetwo = tf.transpose(twothreefour)
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (fourthreetwo.eval())
</code></pre>
<p>我得到一个4x3x2到一个2x3x4,这听起来很合理。</p>
<p>[出局]:</p>
<pre><code>[[[ 1 13]
[ 5 17]
[ 9 21]]
[[ 2 14]
[ 6 18]
[10 22]]
[[ 3 15]
[ 7 19]
[11 23]]
[[ 4 16]
[ 8 20]
[12 24]]]
</code></pre>
<p>但是,当我使用<code>perm</code>参数输出时,我不确定我真正得到的是什么:</p>
<pre><code>twofourthree = tf.transpose(twothreefour, perm=[0,2,1])
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (threetwofour.eval())
</code></pre>
<p>[出局]:</p>
<pre><code>[[[ 1 5 9]
[ 2 6 10]
[ 3 7 11]
[ 4 8 12]]
[[13 17 21]
[14 18 22]
[15 19 23]
[16 20 24]]]
</code></pre>
<p><strong>为什么<code>perm=[0,2,1]</code>从2x3x4返回2x4x3矩阵?</strong></p>
<p>用<code>perm=[1,0,2]</code>再试一次:</p>
<pre><code>threetwofour = tf.transpose(twothreefour, perm=[1,0,2])
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
print (threetwofour.eval())
</code></pre>
<p>[出局]:</p>
<pre><code>[[[ 1 2 3 4]
[13 14 15 16]]
[[ 5 6 7 8]
[17 18 19 20]]
[[ 9 10 11 12]
[21 22 23 24]]]
</code></pre>
<p><strong>为什么<code>perm=[1,0,2]</code>从2x3x4返回3x2x4?</strong></p>
<p><strong>这是否意味着<code>perm</code>参数采用my <code>np.shape</code>并基于基于数组形状的元素转置张量?</strong></p>
<p>即:</p>
<pre><code>_size = (2, 4, 3, 5)
randarray = np.random.randint(5, size=_size)
shape_idx = {i:_s for i, _s in enumerate(_size)}
randarray_t_func = tf.transpose(randarray, perm=[3,0,2,1])
with tf.Session() as sess:
init = tf.initialize_all_variables()
sess.run(init)
tranposed_array = randarray_t_func.eval()
print (tranposed_array.shape)
print (tuple(shape_idx[_s] for _s in [3,0,2,1]))
</code></pre>
<p>[出局]:</p>
<pre><code>(5, 2, 3, 4)
(5, 2, 3, 4)
</code></pre>