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.]