Tensorflow - tf常用函数使用(持续更新中)

本人较懒,故间断更新下常用的tf函数以供参考: 

一、tf.reduce_sum( )

reduce_sum( ) 个人理解是降维求和函数,在 tensorflow 里面,计算的都是 tensor,可以通过调整 axis 的维度来控制求和维度。

参数:

  • input_tensor:要减少的张量.应该有数字类型.
  • axis:要减小的尺寸.如果为None(默认),则缩小所有尺寸.必须在范围[-rank(input_tensor), rank(input_tensor))内.
  • keep_dims:如果为true,则保留长度为1的缩小尺寸.
  • name:操作的名称(可选).
  • reduction_indices:axis的废弃的名称.

返回:

该函数返回减少的张量.

numpy兼容性

相当于np.sum;

此处axis为tensor的阶数,使用该函数将消除tensor指定的阶axis,同时将该阶下的所有的元素进行累积求和操作。

看一个官方示例:

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

此函数计算一个张量的各个维度上元素的总和. 

函数中的input_tensor是按照axis中已经给定的维度来减少的;除非 keep_dims 是true,否则张量的秩将在axis的每个条目中减少1;如果keep_dims为true,则减小的维度将保留为长度1. 

如果axis没有条目,则缩小所有维度,并返回具有单个元素的张量.

 二、tf.ones_like | tf.zeros_like

tf.ones_like(tensor,dype=None,name=None)
tf.zeros_like(tensor,dype=None,name=None)
新建一个与给定的tensor类型大小一致的tensor,其所有元素为1和0,示例如下:

tensor=[[1, 2, 3], [4, 5, 6]] 
x = tf.ones_like(tensor) 
print(sess.run(x))

#[[1 1 1],
# [1 1 1]]

猜你喜欢

转载自www.cnblogs.com/Jesee/p/11455697.html
今日推荐