執(zhí)行tf.reduce_sum(tensor)后,tensor會降維,比如本來是3維張量,會變成2維張量。
三維張量的方向為:

重點考慮下4維張量,首先定義一個4維張量,由2個3維張量組成,每個3維張量形狀為3行4列深度為2。
import numpy as np
import tensorflow as tf
const4 = tf.constant(np.arange(0, 48, 1).reshape(2, 3, 4, 2))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(const4))
輸出結(jié)果:
[[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]]
[[ 8 9]
[10 11]
[12 13]
[14 15]]
[[16 17]
[18 19]
[20 21]
[22 23]]]
[[[24 25]
[26 27]
[28 29]
[30 31]]
[[32 33]
[34 35]
[36 37]
[38 39]]
[[40 41]
[42 43]
[44 45]
[46 47]]]]
幾何圖可以如下示意:

axis=0
# shape = (2, 3, 4, 2)
sum1 = tf.reduce_sum(const4, axis=0)

axis=1
# shape = (2, 3, 4, 2)
sum1 = tf.reduce_sum(const4, axis=1)

axis=2
# shape = (2, 3, 4, 2)
sum1 = tf.reduce_sum(const4, axis=2)

axis=3
# shape = (2, 3, 4, 2)
sum1 = tf.reduce_sum(const4, axis=3)

小結(jié):
1、shape屬性中的每個維度分別與axis=0,axis=1、axis=2、axis=3……對應。
2、對于3維張量,shape = (hights, weights, depths);對于4維張量,shape = (channels, hights, weights, depths)
3、shape降維規(guī)律:假設(shè)原本shape=(a,b,c,d),當axis=0,則變化后的shape_new=(b,c,d);當axis=1,則變化后的shape_new=(a,c,d);當axis=2,則變化后的shape_new=(a,b,d);當axis=3,則變化后的shape_new=(a,b,c)。
4、執(zhí)行tf.reduce_sum()時,在對應的方向進行相加,然后按照對應的方向把獲得的幾個張量進行組合,然后在空間中旋轉(zhuǎn)使得維度滿足(3)中的規(guī)律。
5、關(guān)鍵是掌握axis的方向(1、2)和輸出的維度(3),對于(4)中如何旋轉(zhuǎn)的可以忽略。