Tensorflow | Random |常用函数介绍

根据官网的帮助文档,介绍Random类型的函数,方便自己学习和查看。若是有幸帮到别的朋友,深感荣幸。


  • rf.random_normal

产生正态随机分布

格式:tf.random_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)

shape定义维度,mean定义均值,stddev定义方差,dtype定义类型,seed定义种子,name定义名称

例子:

import tensorflow as tf
# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# -1 and standard deviation 4.
norm = tf.random_normal(shape=[2, 3], mean=-1, stddev=4)
with tf.Session() as sess:
    print (sess.run(norm))

结果: [[ -7.80873823 -10.97159195 -11.99345589] [ 1.79066849 -4.10513306 4.37571764]]

  • tf.truncated_normal 产生标准正态分布

格式:tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

shape定义维度,mean定义均值,stddev定义方差,dtype定义类型,seed定义种子,name定义名称

例子:

import tensorflow as tf
# Create a tensor of shape [2, 3] consisting of random normal values, with mean
# 0 and standard deviation 1.
norm = tf.truncated_normal(shape=[2,3],mean=0,stddev=1)
with tf.Session() as sess:
    print (sess.run(norm))

结果: [[ 1.89490759 -1.03072059 0.2172989 ] [-0.29377019 -0.38990787 -1.09539473]]

  • tf.random_uniform 产生均匀分布

格式:tf.random_uniform(shape, minval=0.0, maxval=1.0, dtype=tf.float32, seed=None, name=None)

shape定义维度,minval区间最小值,maxval区间最大值,dtype定义类型,seed定义种子,name定义名称

例子:

import tensorflow as tf
# Create a tensor of shape [2, 3] consisting of random uniform values, with minval=1
#  and maxval =3.
norm = tf.random_uniform(shape=[2,3],minval=1,maxval=3)
with tf.Session() as sess:
    print (sess.run(norm))

结果: [[ 2.73986316 1.50323987 1.64366412] [ 1.12579513 1.52106118 1.29330397]]

-tf.random_shuffle

随机的交换位置 格式:tf.random_shuffle(value, seed=None, name=None) value是一个给定的张量,seed定义的种子,name定义名称

例子:

import tensorflow as tf
c = tf.constant([[1,2],[3,4],[5,6]])
shuff = tf.random_shuffle(value=c,seed=1,name="shuff")
with tf.Session() as sess:
    print (sess.run(shuff))

结果: [[1 2] [5 6] [3 4]]

  • tf.set_random_seed

设置种子 格式:tf.set_random_seed(seed) seed是给定的种子

例子:

import tensorflow as tf
tf.set_random_seed(1234)
a = tf.random_uniform([1])
b = tf.random_normal([1])
with tf.Session() as sess:
    print (sess.run(a))
    print (sess.run(b))

结果: [ 0.59309709] [ 0.32048994]

每次运行结果都不一致。要一致还是在定义张量的内部来设置。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券