tensorflow之常用函数(tf.Constant)

转载: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]]
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TensorFlow 中,`tf.constant` 函数用于创建一个常量张量,其函数原型为: ```python tf.constant(value, dtype=None, shape=None, name='Const') ``` 其中,各参数的含义如下: - `value`: 张量的值。可以是一个 Python 常量、一个列表、一个 NumPy 数组或一个 TensorFlow 张量。 - `dtype`: 张量的数据类型。如果不指定,则自动推断为 `value` 的数据类型。 - `shape`: 张量的形状。如果不指定,则自动推断为 `value` 的形状。 - `name`: 张量的名称。可选参数,如果不指定,则自动生成一个名称。 下面是一些示例代码,用于说明不同参数的使用方法: ```python import tensorflow as tf import numpy as np # 创建一个标量常量张量 a = tf.constant(1.0, dtype=tf.float32, name='a') print(a) # 输出 Tensor("a:0", shape=(), dtype=float32) # 创建一个向量常量张量 b = tf.constant([1, 2, 3], dtype=tf.int32, name='b') print(b) # 输出 Tensor("b:0", shape=(3,), dtype=int32) # 创建一个矩阵常量张量 c = tf.constant(np.arange(6).reshape(2, 3), dtype=tf.float32, name='c') print(c) # 输出 Tensor("c:0", shape=(2, 3), dtype=float32) ``` 在上面的代码中,我们分别创建了一个标量常量张量 `a`、一个向量常量张量 `b` 和一个矩阵常量张量 `c`。可以看到,我们可以通过 `dtype` 参数指定常量张量的数据类型,通过 `shape` 参数指定常量张量的形状,通过 `name` 参数指定常量张量的名称。如果不指定这些参数,TensorFlow 会自动推断出它们的值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值