# TensorFlow随机张量：tf.set_random_seed函数

2018-01-20 11:32 更新

## tf.set_random_seed 函数

``set_random_seed(seed)``

1. 如果既没有设置图层级也没有设置操作级别的seed：则使用随机seed进行该操作.
2. 如果设置了图形级seed,但操作seed没有设置：系统确定性地选择与图形级seed结合的操作seed,以便获得唯一的随机序列.
3. 如果未设置图形级seed,但设置了操作seed：使用默认的图层seed和指定的操作seed来确定随机序列.
4. 如果图层级seed和操作seed都被设置：则两个seed将一起用于确定随机序列.

``````a = tf.random_uniform([1])
b = tf.random_normal([1])

print("Session 1")
with tf.Session() as sess1:
print(sess1.run(a))  # generates 'A1'
print(sess1.run(a))  # generates 'A2'
print(sess1.run(b))  # generates 'B1'
print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
print(sess2.run(a))  # generates 'A3'
print(sess2.run(a))  # generates 'A4'
print(sess2.run(b))  # generates 'B3'
print(sess2.run(b))  # generates 'B4'``````

``````a = tf.random_uniform([1], seed=1)
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate the same
# sequence of values for 'a', but different sequences of values for 'b'.
print("Session 1")
with tf.Session() as sess1:
print(sess1.run(a))  # generates 'A1'
print(sess1.run(a))  # generates 'A2'
print(sess1.run(b))  # generates 'B1'
print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
print(sess2.run(a))  # generates 'A1'
print(sess2.run(a))  # generates 'A2'
print(sess2.run(b))  # generates 'B3'
print(sess2.run(b))  # generates 'B4'``````

``````tf.set_random_seed(1234)
a = tf.random_uniform([1])
b = tf.random_normal([1])

# Repeatedly running this block with the same graph will generate the same
# sequences of 'a' and 'b'.
print("Session 1")
with tf.Session() as sess1:
print(sess1.run(a))  # generates 'A1'
print(sess1.run(a))  # generates 'A2'
print(sess1.run(b))  # generates 'B1'
print(sess1.run(b))  # generates 'B2'

print("Session 2")
with tf.Session() as sess2:
print(sess2.run(a))  # generates 'A1'
print(sess2.run(a))  # generates 'A2'
print(sess2.run(b))  # generates 'B1'
print(sess2.run(b))  # generates 'B2'``````

• seed：整数.

App下载