TensorFlow隨機(jī)張量:tf.set_random_seed函數(shù)

2018-01-20 11:32 更新

tf.set_random_seed 函數(shù)

set_random_seed(seed)

定義在:tensorflow/python/framework/random_seed.py.

請(qǐng)參閱指南:生成常量,序列和隨機(jī)值>隨機(jī)張量

設(shè)置圖形級(jí)隨機(jī)seed.

可以從兩個(gè)seed中獲得依賴隨機(jī)seed的操作:圖形級(jí)seed和操作級(jí)seed.本節(jié)是介紹如何設(shè)置圖形級(jí)別的seed.

它與操作級(jí)別seed的交互如下:

  1. 如果既沒有設(shè)置圖層級(jí)也沒有設(shè)置操作級(jí)別的seed:則使用隨機(jī)seed進(jìn)行該操作.
  2. 如果設(shè)置了圖形級(jí)seed,但操作seed沒有設(shè)置:系統(tǒng)確定性地選擇與圖形級(jí)seed結(jié)合的操作seed,以便獲得唯一的隨機(jī)序列.
  3. 如果未設(shè)置圖形級(jí)seed,但設(shè)置了操作seed:使用默認(rèn)的圖層seed和指定的操作seed來確定隨機(jī)序列.
  4. 如果圖層級(jí)seed和操作seed都被設(shè)置:則兩個(gè)seed將一起用于確定隨機(jī)序列.

為了說明用戶可見的效果,請(qǐng)考慮以下示例:

要在會(huì)話中生成不同的序列,請(qǐng)不要設(shè)置圖層級(jí)別seed或操作級(jí)別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'

要為會(huì)話中的操作生成相同的可重復(fù)序列,請(qǐng)為操作設(shè)置seed:

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'

要使所有操作生成的隨機(jī)序列在會(huì)話中可重復(fù),請(qǐng)?jiān)O(shè)置圖形級(jí)別seed:

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'

函數(shù)參數(shù)

  • seed:整數(shù).


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)