TensorFlow生成常量,序列和随机值

2020-07-23 16:55 更新
注意:接受 Tensor 参数的函数也可以接受任何接受的内容 tf.convert_to_tensor.

常数值张量

TensorFlow 提供了几种可用于生成常量的操作.

序列

随机张量

TensorFlow 有几个 ops 用来创建不同分布的随机张量.随机操作是有状态的,并在每次评估时创建新的随机值.

seed 这些函数中的关键字参数与图级随机种子一起作用.使用 tf.set_random_seed 或使用 op 级别的种子更改图形级别的种子将会更改这些操作的底层种子.设置图形级别或操作级种子,都会为所有操作生成随机种子.有关 tf.set_random_seed 操作级和图级随机种子之间的交互的详细信息,请参阅.

例子:

# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# -1 and standard deviation 4.
norm = tf.random_normal([2, 3], mean=-1, stddev=4)

# Shuffle the first dimension of a tensor
c = tf.constant([[1, 2], [3, 4], [5, 6]])
shuff = tf.random_shuffle(c)

# Each time we run these ops, different results are generated
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))

# Set an op-level seed to generate repeatable sequences across sessions.
norm = tf.random_normal([2, 3], seed=1234)
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))
sess = tf.Session()
print(sess.run(norm))
print(sess.run(norm))

随机值的另一个常见用法是变量的初始化.另请参阅变量如何.

# Use random uniform values in [0, 1) as the initializer for a variable of shape
# [2, 3]. The default type is float32.
var = tf.Variable(tf.random_uniform([2, 3]), name="var")
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
print(sess.run(var))
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号