tf.reduce_sum(tensor)
方法代码和注解:
def reduce_sum(input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None):
"""Computes the sum of elements across dimensions([数] 维) of a tensor.
Reduces `input_tensor` along the dimensions given in `axis`.
Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each
entry in `axis`. If `keep_dims` is true, the reduced dimensions
are retained with length 1.
If `axis` has no entries, all dimensions are reduced, and a
tensor with a single element is returned.
For example:
```python
x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x) # 6
tf.reduce_sum(x, 0) # [2, 2, 2]
tf.reduce_sum(x, 1) # [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) # [[3], [3]]
tf.reduce_sum(x, [0, 1]) # 6
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. If `None` (the default),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
Returns:
The reduced tensor.
@compatibility(numpy)
Equivalent to np.sum
@end_compatibility
"""
return gen_math_ops._sum(
input_tensor,
_ReductionDims(input_tensor, axis, reduction_indices),
keep_dims,
name=name)
tesnor可以理解为多维数组
import tensorflow as tf
import inspect
import re
# get var_name
def varname(var):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
return m.group(1)
# print var and var_name
def printNameAndValue(var_name,var):
print("%s : %s;" % (var_name,tf.Session().run(var)))
# y : a rank 3 tensor with shape [2,3,4]
y = tf.constant([[[1,1,1,1], [1,1,1,1], [1,1,1,1]], [[1,1,1,1], [1,1,1,1], [1,1,1,1]]])
tf.reduce_sum(y, 0) # [[2 2 2 2],[2 2 2 2],[2 2 2 2]] a rank 2 tensor with shape [3,4]
tf.reduce_sum(y,1) # [[3 3 3 3],[3 3 3 3]] a rank 2 tensor with shape [2,4]
tf.reduce_sum(y,[0,1]) # [6 6 6 6] a rank 1 tensor with shape [4]
tf.reduce_sum(y,1, keep_dims=True) #[[[3 3 3 3]],[[3 3 3 3]]]; a rank 3 tensor with shape [2,1,4]
tf.reduce_sum(y,0,keep_dims=True) #[[[2 2 2 2],[2 2 2 2],[2 2 2 2]]] a rank 3 tensor with shape [1,3,4]
tf.reduce_sum(y,[0,2],keep_dims=True) # [[[8],[8],[8]]] a rank 3 tensor with shape [1,1,3]
终结:
1.对input_tensor的某些维度进行合并,keep_dims将会保留tensor的rank(维度)并设置shape对应的维度为1。
网友评论