转载:http://blog.sina.com.cn/s/blog_e504f4340102yd4k.html
tensorflow中我们会看到这样一段代码:
import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = a + b
print result # 输出“Tensor("add:0", shape=(2,), dtype=float32) ”
sess = tf.Session()
print sess.run(result) # 输出“[ 3. 5.]”
sess.close()
那么constant的用法是什么样的?
constant( value, dtype=None, shape=None, name='Const', verify_shape=False)
tf.constant
tf.constant(value,dtype=None,shape=None,name=’Const’)
创建一个常量tensor,按照给出value来赋值,可以用shape来指定其形状。value可以是一个数,也可以是一个list。
如果是一个数,那么这个常亮中所有值的按该数来赋值。
如果是list,那么len(value)一定要小于等于shape展开后的长度。赋值时,先将value中的值逐个存入。不够的部分,则全部存入value的最后一个值。
a = tf.constant(2,shape=[2]) b = tf.constant(2,shape=[2,2]) c = tf.constant([1,2,3],shape=[6]) d = tf.constant([1,2,3],shape=[3,2])sess = tf.InteractiveSession() print(sess.run(a)) #[2 2] print(sess.run(b)) #[[2 2] # [2 2]] print(sess.run(c)) #[1 2 3 3 3 3] print(sess.run(d)) #[[1 2] # [3 3] # [3 3]]