tensorflow-----张量的归约

张量的归约是常见的张量降维方法,通常归约函数都有一个维度作为参数,沿着该维度来执行指定的操作。如果axis为None,那么将归约的张量降维到一个标。

常见的归约函数:
(1)tf.reduce_sum(input_tensor, axis=None, keepdims=False, name=None)
沿着维度axis计算该维度所有元素的和。如果keepdims=True,那么维度被保留。如果axis没有指定,归约为标量。

tensorflow-----张量的归约_第1张图片

import tensorflow as tf

x = tf.constant([[1,1,1], [1,1,1]]#shape=(2,3)
a = tf.reduce_sum(x)#没有指定维度,归约为标量,a = 6

b = tf.reduce_sum(x,axis=0)#沿着维度0进行归约
#b = [2,2,2]#shape = (3)

c = tf.reduce_sum(x, axis=1)#沿着维度1进行归约
#c = [3,3]

d = tf.reduce_sum(x, axis=1, keepdims=True)#沿着维度1进行归约,保留该维度,长度为1
#d = [[3], [3]]
#d.shape = (2,1)。由x.shape=(2,3)变为d.shape=(2,1)
e = tf.reduce_sum(x, axis=[0,1])#先沿着维度0进行归约求和,然后再沿着维度1进行归约求和
'''
[[1,1,1],
 [1,1,1]]  ==>  [2,2,2]  ==>  6
'''

(2)tf.reduce_min(input_tensor, axis=None, keepdims=False)
取维度axis上所有元素中的最小元素。
(3)tf.reduce_max(input_tensor, axis=None, keepdims=False)
取维度axis上所有元素中的最大元素。
(4)tf.reduce_prod(input_tensor, axis=None, keepdims=False)
计算维度axis上所有元素的乘积。
(5)tf.reduce_mean(input_tensor, axis=None, keepdims=False)
计算维度axis上所有元素的平均值。
(6)tf.reduce_all(input_tensor, axis=None, keepdims=False)
计算维度axis上所有元素的“逻辑与运算”。

import tensorflow as tf

x = tf.constant([[True, True], [False, False]]

a = tf.reduce_all(x) #[False]
b = tf.reduce_all(x, axis=0) #[False, False]
c = tf.reduce_all(x, axis=1) #[True, False]

(7)(6)tf.reduce_any(input_tensor, axis=None, keepdims=False)
计算维度axis上所有元素的“逻辑或运算”。

import tensorflow as tf

x = tf.constant([[True, True], [False, False]]

a = tf.reduce_any(x) #[True]
b = tf.reduce_all(x, axis=0) #[True, True]
c = tf.reduce_all(x, axis=1) #[True, False]

(8)tf.reduce_join(input_tensor, axis=None, keepdims=False)
沿着给定的维度axis,对字符串进行连接操作

import tensorflow as tf

x = tf.constant([['a', 'b'], ['c', 'd']]

a = tf.reduce_join(x) #['abcd']
b = tf.reduce_all(x, axis=0) #['ac', 'bd']
c = tf.reduce_all(x, axis=1) #['ab', 'cd']

(9)tf.count_nonzero(input_tensor, axis=None, keepdims=False)
计算维度axis上所有非零元素的个数。

你可能感兴趣的:(tensorflow)