tensor(4,4,2)+tensor(4,4,2)=?

两个张量相加如:tensor(4,4,2)+tensor(4,4,2)

其中,括号表示维度,刚开始误以为加起来等于tensor(4,4,4),然后算模型尺寸,就发现对不上,实际是等于tensor(4,4,2)

tensor的加法必须满足shape相同才能相加,因为是对应位置的值相加,而不是把tensor叠加起来。举例说明

import tensorflow as tf

sess = tf.Session()
x = tf.constant(2,shape=[4, 4, 2], dtype=tf.float32)
y = tf.ones(shape=[4, 4, 2], dtype=tf.float32)
a = x + y
print(sess.run(a))
print(a.get_shape())

按照我们刚才的说法 a应该等于维度是(4,4,2),每个值都是3的tensor。

我们验证以下:


Yes!

这里发现一个待解决的问题,我也是新手哦,需要指点:

import tensorflow as tf

sess = tf.Session()
x = tf.constant(2,shape=[4, 4, 2], dtype=tf.float32)
y = tf.ones(shape=[4, 4, 2], dtype=tf.float32)
a = x + y
sess.run(a)
print(a)

当我先运行a,再打印结果就不会得到具体的值,是为什么?只能得到如下结果


欢迎指导

猜你喜欢

转载自blog.csdn.net/u014264373/article/details/80530597
今日推荐