隨機初始化值randint,rand,tf.random_normal,tf.random_uniform


import tensorflow as tf

import numpy as np

原型:np.random.randint(low, high=None, size=None, dtype='l')
'''
  當只有low時候,返回的值范圍是[0,low).有low和high時候,返回值范圍是[low,high).
'''
t1 = np.random.randint(2,size=10)
print(t1)
#[0 0 0 0 1 0 1 1 1 1]

t2 = np.random.randint(low=1,high=3,size=10)
print(t2)
#[2 1 2 1 2 2 2 1 1 2]

 

原型:np.random.rand(d0, d1, ..., dn),其中di表示維數
'''
    返回范圍為[0,1)均勻分布
'''
t3 = np.random.rand(3, 2)
print(t3)
#[[0.25586789 0.26593995]
# [0.00827676 0.67958833]
# [0.77343696 0.40320088]]

原型:tf.random_normal(shape,
   mean=0.0,
   stddev=1.0,
   dtype=dtypes.float32,
   seed=None,
   name=None)
'''
    根據shape返回一個張量,其中值服從均值為0,方差為1的正態分布
'''
t4 = tf.random_normal((3, 2))
print(t4)
#Tensor("random_normal:0", shape=(3, 2), dtype=float32)

with tf.Session() as sess:
    init =tf.global_variables_initializer()
    print(sess.run(t4))
#[[-0.1009187  -0.52692866]
# [ 0.75775075  0.10555366]
# [ 0.89376223 -1.5488473 ]]
原型:tf.random_uniform(shape,
   minval=0,
   maxval=None,
   dtype=dtypes.float32,
   seed=None,
   name=None)
'''
    從均勻分布中隨機取值,范圍為[minval,maxval)
'''
t5 = tf.random_uniform((3, 2),minval=1,maxval=3)
print(t5)
#Tensor("random_uniform:0", shape=(3, 2), dtype=float32)

with tf.Session() as sess:
    init =tf.global_variables_initializer()
    print(sess.run(t5))
#[[2.8821492 1.3117931]
# [2.6424809 1.5386689]
# [1.4922662 1.0668414]]

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM