tf.add()大多数用法都是,单个数字和单个数字的简单相加,例如:
import tensorflow as tf
x = tf.constant(2)
y = tf.constant(1)
sess = tf.Session()
print(sess.run(tf.add(x, y)))
输出:3
但是它还有一种更重要的用法,很多文章都没有说,即按维度的相加,将一个与高维度矩阵的子维度与高维度的每一个维度相加,例如[1×1]+[1 × 3]:
import tensorflow as tf
a = tf.constant([1])
b = tf.constant([2,3,4])
with tf.Session() as sess:
print(sess.run(tf.add(b,a)))
输出:[3 4 5]
例如[1×2 × 2]+[2 × 2] :
a = tf.constant([[[1,2],
[3,4]],
[[0,0],
[0,0]]])
b = tf.constant([[2,3],
[1,0]])
with tf.Session() as sess:
print(sess.run(tf.add(b,a)))
输出:
[[[3 5]
[4 4]]
[[2 3]
[1 0]]]