tf 数值定义与计算

1、tf 数值定义

1)生成一个给定值的常量(tf.constant)

# 语法
tf.constant(value, dtype, shape, name)
# 举例,可随意赋值,自定义shape
A_const = tf.constant([[1, 2, 3, 4, 5, 6]], shape=[3,2])
# 输出
[[1 2]
 [3 4]
 [5 6]]

# 语法
tf.fill(dims, value, name)
# 样例 
A_const = tf.fill([3, 4], 3.2) #等价于 A_const = tf.constant(3.2, dtype='float32', shape=[3, 4])
# 输出
[[3.2 3.2 3.2 3.2]
 [3.2 3.2 3.2 3.2]
 [3.2 3.2 3.2 3.2]]

2)生成全0数组 && 生成全1数组(tf.zeros,tf.ones)&& 生成一个与给定tensor类型、形状一致的常量,其所有元素为0或1(tf.zeros_like,tf.ones_like)

# 语法
tf.zeros(shape, dtype, name) 
tf.ones(shape, dtype, name) 
# 生成两行三列的全0数组
A_const = tf.zeros([2, 3], dtype='int32')
# 生成两行三列的全1数组
B_const = tf.ones([2, 3], dtype='int32')

# 语法
tf.zeros_like(tensor, dtype, name)
tf.ones_like(tensor, dtype, name)
# 例子
A_const = tf.constant([[1, 2, 3], [4, 5, 6]])
A_zeros = tf.zeros_like(A_const, dtype='int32')
A_ones = tf.ones_like(A_const, dtype='int32')

3)生成序列(tf.range,tf.linspace)

# 序列tf.range类似于numpy的arange
A_const = tf.range(1, 10, 0.5) # 从1到10,步长为0.5
# 输出
[1.  1.5 2.  2.5 3.  3.5 4.  4.5 5.  5.5 6.  6.5 7.  7.5 8.  8.5 9.  9.5]

# 序列tf.linspace类似于numpy的linspace,需要注意start和end类型必须是`bfloat16`, `half`, `float32`, `float64`中的一个
A_const = tf.linspace(10.0, 12.0, 4, name="linspace") # 从10.0到12.0等间隔输出4个数字
# 输出
[10.       10.666667 11.333333 12.      ]

 

 

2、tf 数值计算

1)tf.reduce_mean

x = tf.constant([[1., 1.], [2., 2.]])
o1 = tf.reduce_mean(x)  # 1.5
o2 = tf.reduce_mean(x, 0)  # [1.5, 1.5]
o3 = tf.reduce_mean(x, 1)  # [1.,  2.]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值