作为Tensorflow中常见的一种计算方式,规约计算在操作时会有降维的功能。在所有规约计算系列的操作函数中,都是以reduce开头来命名,以函数名所命名的手段来降维。
每个函数都有axis参数,即沿哪个方向使用函数名所命名的方法对输入的tensor进行降维。axis的默认值是None,即把input_tensor降到0维,即一个数。对于二维input_tensor而言,axis = 0时,按列计算,axis = 1时,按行计算。
tf.reduce_sum(input_tensor,axis = None,keep_dims = False,name = None,reduction_indices = None),该函数用于计算输入tensor的元素之和,或者按照axis指定的轴进行求和。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[1,2,3],[4,5,6]])with tf.Session() as sess:print(sess.run(tf.reduce_sum(a)))print(sess.run(tf.reduce_sum(a,0)))print(sess.run(tf.reduce_sum(a,1)))
tf.reduce_prod(input_tensor,axis = None,keep_dims = False,name = None,reduction_indices = None),该函数用于计算输入tensor的元素乘积,或者按照axis指定的轴进行求乘积。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[1,2,3],[4,5,6]])with tf.Session() as sess:print(sess.run(tf.reduce_prod(a)))print(sess.run(tf.reduce_prod(a,0)))print(sess.run(tf.reduce_prod(a,1)))
tf.reduce_min(input_tensor,axis = None,keep_dims = False,name = None,rediction_indices = None),该函数用于求输入tensor中的最小值。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[1,2,3],[4,5,6]])
b = tf.constant([[6,5,5],[3,2,1]])with tf.Session() as sess:print(sess.run(tf.reduce_min(a)))print(sess.run(tf.reduce_min(b)))
tf.reduce_max(input_tensor,axis = None,keep_dims = False,name = None,rediction_indices = None),该函数用于求输入tensor中的最大值。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[1,2,3],[4,5,6]])
b = tf.constant([[6,5,5],[3,2,1]])with tf.Session() as sess:print(sess.run(tf.reduce_max(a)))print(sess.run(tf.reduce_max(b)))
tf.reduce_mean(input_tensor,axis = None,keep_dims = False,name = None,rediction_indices = None),该函数用于求输入tensor中的元素平均值。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[1,2,3],[1,5,6]])with tf.Session() as sess:print(sess.run(tf.reduce_mean(a)))
tf.reduce_all(input_tensor,axis = None,keep_dims = False,name = None,reduction_indices = None),该函数用于对tensor中的各个元素求逻辑与。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[True,True,False],[False,True,True]])with tf.Session() as sess:print(sess.run(tf.reduce_all(a)))print(sess.run(tf.reduce_all(a,0)))print(sess.run(tf.reduce_all(a,1)))
tf.reduce_any(input_tensor,axis = None,keep_dims = False,name = None,reduction_indices = None),该函数用于对tensor中的各个元素求逻辑或。
示例代码如下:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()a = tf.constant([[True,True,False],[False,True,True]])with tf.Session() as sess:print(sess.run(tf.reduce_any(a)))print(sess.run(tf.reduce_any(a,0)))print(sess.run(tf.reduce_any(a,1)))