TensorFlow四则运算之加法:tf.add() | 您所在的位置:网站首页 › 如何隔行相加 › TensorFlow四则运算之加法:tf.add() |
tensor广播(boardcast):
为了凑够元素个数,便于后续计算,这里将元素进行复制,达到某一个维度,称之为广播. 1.作用:两个张量相加 tf.math.add( x, y, name=None )输入: x是一个张量,其类型需得是:bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string. y同x一个类型。 输出: 一个张量。 2.例子: import tensorflow as tf a = tf.constant([[3, 5], [4, 8]) b = tf.constant([[1, 6], [2, 9]]) c = tf.add(a, b) sess = tf.Session() print sess.run(c) 输出: [[ 4 11] [ 6 17]]如果x和y的维度不一样,则会朝着维度较大的变量, 进行广播,使得二者能够逐元素相加。 import tensorflow as tf a = tf.constant([[3, 5]]) # 广播为[[3, 5], [3, 5]] b = tf.constant([[1, 6], [2, 9]]) c = tf.add(a, b) sess = tf.Session() print sess.run(c) 输出: [[ 4 11] [ 5 14]] import tensorflow as tf a = tf.constant([[3], [5]]) # 广播为[[3, 3], [5, 5]] b = tf.constant([[1, 6], [2, 9]]) c = tf.add(a, b) sess = tf.Session() print sess.run(c) 输出: [[ 4 9] 【3+1,3+9】 [ 7 14]] 【5+2,5+9】 3.多个tensor相加——不支持广播 tf.math.add_n( inputs, name=None )输入: inputs:一个tensor list,具有相同维度和类型。注意:这里的维度需要相同,没有广播tensor的操作了。 例子: import tensorflow as tf a = tf.constant([[3, 1], [5, 1]]) b = tf.constant([[1, 6], [2, 9]]) c = tf.add_n([a, b, a]) sess = tf.Session() print sess.run(c) 输出: [[ 7 8] [12 11]]
|
CopyRight 2018-2019 实验室设备网 版权所有 |