tf.random_normal

从正态分布输出随机值。

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

shape:一个一维整数张量或Python数组。代表张量的形状。
mean:数据类型为dtype的张量值或Python值。是正态分布的均值。
stddev:数据类型为dtype的张量值或Python值。是正态分布的标准差
dtype: 输出的数据类型。
seed:一个Python整数。是随机种子。
name: 操作的名称(可选)

官网api地址:https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/random_normal

tf.random_uniform

从均匀分布中返回随机值。

random_uniform(
shape,# 生成的张量的形状
minval=0,
maxval=None,
dtype=tf.float32,
seed=None,
name=None
)

  

返回值的范围默认是0到1的左闭右开区间,即[0,1)。minval为指定最小边界,默认为1。maxval为指定的最大边界,如果是数据浮点型则默认为1,如果数据为整形则必须指定。

官网api地址:https://www.tensorflow.org/api_docs/python/tf/random_uniform

tf.truncated_normal

截断的正态分布函数。生成的值遵循一个正态分布,但不会大于平均值2个标准差。

truncated_normal(
shape,#一个一维整数张量或Python数组。代表张量的形状。
mean=0.0,#数据类型为dtype的张量值或Python值。是正态分布的均值。
stddev=1.0,#数据类型为dtype的张量值或Python值。是正态分布的标准差
dtype=tf.float32,#输出的数据类型。
seed=None,#一个Python整数。是随机种子。
name=None#操作的名称(可选)
)

  官网api地址:https://www.tensorflow.org/api_docs/python/tf/truncated_normal

tf.random_shuffle

沿着要被洗牌的张量的第一个维度,随机打乱。

random_shuffle(
value,# 要被洗牌的张量
seed=None,
name=None
)

  官网api地址: https://www.tensorflow.org/api_docs/python/tf/random_shuffle

附录1:生成随机数的操作的源码random_ops.py

truncated_normal(
shape,#一个一维整数张量或Python数组。代表张量的形状。
mean=0.0,#数据类型为dtype的张量值或Python值。是正态分布的均值。
stddev=1.0,#数据类型为dtype的张量值或Python值。是正态分布的标准差
dtype=tf.float32,#输出的数据类型。
seed=None,#一个Python整数。是随机种子。
name=None#操作的名称(可选)
) 官网api地址:https://www.tensorflow.org/api_docs/python/tf/truncated_normal tf.random_shuffle
沿着要被洗牌的张量的第一个维度,随机打乱。 [python] view plain copy
random_shuffle(
value,# 要被洗牌的张量
seed=None,
name=None
)
即下面这种效果:
[python] view plain copy
[[1, 2], [[5, 6],
[3, 4], ==> [1, 2],
[5, 6]] [3, 4]] 官网api地址: https://www.tensorflow.org/api_docs/python/tf/random_shuffle 附录1:生成随机数的操作的源码random_ops.py
[python] view plain copy
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Operations for generating random numbers.""" from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gen_random_ops
from tensorflow.python.ops import math_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_random_ops import * # pylint: enable=wildcard-import def _ShapeTensor(shape):
"""Convert to an int32 or int64 tensor, defaulting to int32 if empty."""
if isinstance(shape, (tuple, list)) and not shape:
dtype = dtypes.int32
else:
dtype = None
return ops.convert_to_tensor(shape, dtype=dtype, name="shape") # pylint: disable=protected-access
def random_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a normal distribution. Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
@{tf.set_random_seed}
for behavior.
name: A name for the operation (optional). Returns:
A tensor of the specified shape filled with random normal values.
"""
with ops.name_scope(name, "random_normal", [shape, mean, stddev]) as name:
shape_tensor = _ShapeTensor(shape)
mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
seed1, seed2 = random_seed.get_seed(seed)
rnd = gen_random_ops._random_standard_normal(
shape_tensor, dtype, seed=seed1, seed2=seed2)
mul = rnd * stddev_tensor
value = math_ops.add(mul, mean_tensor, name=name)
return value ops.NotDifferentiable("RandomStandardNormal") def parameterized_truncated_normal(shape,
means=0.0,
stddevs=1.0,
minvals=-2.0,
maxvals=2.0,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is more than 2 standard
deviations from the mean are dropped and re-picked. Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
means: A 0-D Tensor or Python value of type `dtype`. The mean of the
truncated normal distribution.
stddevs: A 0-D Tensor or Python value of type `dtype`. The standard
deviation of the truncated normal distribution.
minvals: A 0-D Tensor or Python value of type `dtype`. The minimum value of
the truncated normal distribution.
maxvals: A 0-D Tensor or Python value of type `dtype`. The maximum value of
the truncated normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
@{tf.set_random_seed}
for behavior.
name: A name for the operation (optional). Returns:
A tensor of the specified shape filled with random truncated normal values.
"""
with ops.name_scope(name, "parameterized_truncated_normal",
[shape, means, stddevs, minvals, maxvals]) as name:
shape_tensor = _ShapeTensor(shape)
means_tensor = ops.convert_to_tensor(means, dtype=dtype, name="means")
stddevs_tensor = ops.convert_to_tensor(stddevs, dtype=dtype, name="stddevs")
minvals_tensor = ops.convert_to_tensor(minvals, dtype=dtype, name="minvals")
maxvals_tensor = ops.convert_to_tensor(maxvals, dtype=dtype, name="maxvals")
seed1, seed2 = random_seed.get_seed(seed)
rnd = gen_random_ops._parameterized_truncated_normal(
shape_tensor,
means_tensor,
stddevs_tensor,
minvals_tensor,
maxvals_tensor,
seed=seed1,
seed2=seed2)
return rnd def truncated_normal(shape,
mean=0.0,
stddev=1.0,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose magnitude is more than 2 standard
deviations from the mean are dropped and re-picked. Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
mean: A 0-D Tensor or Python value of type `dtype`. The mean of the
truncated normal distribution.
stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
of the truncated normal distribution.
dtype: The type of the output.
seed: A Python integer. Used to create a random seed for the distribution.
See
@{tf.set_random_seed}
for behavior.
name: A name for the operation (optional). Returns:
A tensor of the specified shape filled with random truncated normal values.
"""
with ops.name_scope(name, "truncated_normal", [shape, mean, stddev]) as name:
shape_tensor = _ShapeTensor(shape)
mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
seed1, seed2 = random_seed.get_seed(seed)
rnd = gen_random_ops._truncated_normal(
shape_tensor, dtype, seed=seed1, seed2=seed2)
mul = rnd * stddev_tensor
value = math_ops.add(mul, mean_tensor, name=name)
return value ops.NotDifferentiable("ParameterizedTruncatedNormal")
ops.NotDifferentiable("TruncatedNormal") def random_uniform(shape,
minval=0,
maxval=None,
dtype=dtypes.float32,
seed=None,
name=None):
"""Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range
`[minval, maxval)`. The lower bound `minval` is included in the range, while
the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must
be specified explicitly. In the integer case, the random integers are slightly biased unless
`maxval - minval` is an exact power of two. The bias is small for values of
`maxval - minval` significantly smaller than the range of the output (either
`2**32` or `2**64`). Args:
shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the
range of random values to generate. Defaults to 0.
maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on
the range of random values to generate. Defaults to 1 if `dtype` is
floating point.
dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`.
seed: A Python integer. Used to create a random seed for the distribution.
See @{tf.set_random_seed}
for behavior.
name: A name for the operation (optional). Returns:
A tensor of the specified shape filled with random uniform values. Raises:
ValueError: If `dtype` is integral and `maxval` is not specified.
"""
dtype = dtypes.as_dtype(dtype)
if maxval is None:
if dtype.is_integer:
raise ValueError("Must specify maxval for integer dtype %r" % dtype)
maxval = 1
with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name:
shape = _ShapeTensor(shape)
minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")
seed1, seed2 = random_seed.get_seed(seed)
if dtype.is_integer:
return gen_random_ops._random_uniform_int(
shape, minval, maxval, seed=seed1, seed2=seed2, name=name)
else:
rnd = gen_random_ops._random_uniform(
shape, dtype, seed=seed1, seed2=seed2)
return math_ops.add(rnd * (maxval - minval), minval, name=name) ops.NotDifferentiable("RandomUniform") def random_shuffle(value, seed=None, name=None):
"""Randomly shuffles a tensor along its first dimension. The tensor is shuffled along dimension 0, such that each `value[j]` is mapped
to one and only one `output[i]`. For example, a mapping that might occur for a
3x2 tensor is: ```python
[[1, 2], [[5, 6],
[3, 4], ==> [1, 2],
[5, 6]] [3, 4]]
``` Args:
value: A Tensor to be shuffled.
seed: A Python integer. Used to create a random seed for the distribution.
See
@{tf.set_random_seed}
for behavior.
name: A name for the operation (optional). Returns:
A tensor of same shape and type as `value`, shuffled along its first
dimension.
"""
seed1, seed2 = random_seed.get_seed(seed)
return gen_random_ops._random_shuffle(
value, seed=seed1, seed2=seed2, name=name) def random_crop(value, size, seed=None, name=None):
"""Randomly crops a tensor to a given size. Slices a shape `size` portion out of `value` at a uniformly chosen offset.
Requires `value.shape >= size`. If a dimension should not be cropped, pass the full size of that dimension.
For example, RGB images can be cropped with
`size = [crop_height, crop_width, 3]`. Args:
value: Input tensor to crop.
size: 1-D tensor with size the rank of `value`.
seed: Python integer. Used to create a random seed. See
@{tf.set_random_seed}
for behavior.
name: A name for this operation (optional). Returns:
A cropped tensor of the same rank as `value` and shape `size`.
"""
# TODO(shlens): Implement edge case to guarantee output size dimensions.
# If size > value.shape, zero pad the result so that it always has shape
# exactly size.
with ops.name_scope(name, "random_crop", [value, size]) as name:
value = ops.convert_to_tensor(value, name="value")
size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="size")
shape = array_ops.shape(value)
check = control_flow_ops.Assert(
math_ops.reduce_all(shape >= size),
["Need value.shape >= size, got ", shape, size],
summarize=1000)
shape = control_flow_ops.with_dependencies([check], shape)
limit = shape - size + 1
offset = random_uniform(
array_ops.shape(shape),
dtype=size.dtype,
maxval=size.dtype.max,
seed=seed) % limit
return array_ops.slice(value, offset, size, name=name) def multinomial(logits, num_samples, seed=None, name=None):
"""Draws samples from a multinomial distribution. Example: ```python
# samples has shape [1, 5], where each value is either 0 or 1 with equal
# probability.
samples = tf.multinomial(tf.log([[10., 10.]]), 5)
``` Args:
logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice
`[i, :]` represents the log-odds for all classes.
num_samples: 0-D. Number of independent samples to draw for each row slice.
seed: A Python integer. Used to create a random seed for the distribution.
See
@{tf.set_random_seed}
for behavior.
name: Optional name for the operation. Returns:
The drawn samples of shape `[batch_size, num_samples]`.
"""
with ops.name_scope(name, "multinomial", [logits]):
logits = ops.convert_to_tensor(logits, name="logits")
seed1, seed2 = random_seed.get_seed(seed)
return gen_random_ops.multinomial(
logits, num_samples, seed=seed1, seed2=seed2) ops.NotDifferentiable("Multinomial") def random_gamma(shape,
alpha,
beta=None,
dtype=dtypes.float32,
seed=None,
name=None):
"""Draws `shape` samples from each of the given Gamma distribution(s). `alpha` is the shape parameter describing the distribution(s), and `beta` is
the inverse scale parameter(s). Example: samples = tf.random_gamma([10], [0.5, 1.5])
# samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
# the samples drawn from each distribution samples = tf.random_gamma([7, 5], [0.5, 1.5])
# samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
# represents the 7x5 samples drawn from each of the two distributions samples = tf.random_gamma([30], [[1.],[3.],[5.]], beta=[[3., 4.]])
# samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions. Note: Because internal calculations are done using `float64` and casting has
`floor` semantics, we must manually map zero outcomes to the smallest
possible positive floating-point value, i.e., `np.finfo(dtype).tiny`. This
means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise
should. This bias can only happen for small values of `alpha`, i.e.,
`alpha << 1` or large values of `beta`, i.e., `beta >> 1`. Args:
shape: A 1-D integer Tensor or Python array. The shape of the output samples
to be drawn per alpha/beta-parameterized distribution.
alpha: A Tensor or Python value or N-D array of type `dtype`. `alpha`
provides the shape parameter(s) describing the gamma distribution(s) to
sample. Must be broadcastable with `beta`.
beta: A Tensor or Python value or N-D array of type `dtype`. Defaults to 1.
`beta` provides the inverse scale parameter(s) of the gamma
distribution(s) to sample. Must be broadcastable with `alpha`.
dtype: The type of alpha, beta, and the output: `float16`, `float32`, or
`float64`.
seed: A Python integer. Used to create a random seed for the distributions.
See
@{tf.set_random_seed}
for behavior.
name: Optional name for the operation. Returns:
samples: a `Tensor` of shape `tf.concat(shape, tf.shape(alpha + beta))`
with values of type `dtype`.
"""
with ops.name_scope(name, "random_gamma", [shape, alpha, beta]):
shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32)
alpha = ops.convert_to_tensor(alpha, name="alpha", dtype=dtype)
beta = ops.convert_to_tensor(
beta if beta is not None else 1, name="beta", dtype=dtype)
alpha_broadcast = alpha + array_ops.zeros_like(beta)
seed1, seed2 = random_seed.get_seed(seed)
return math_ops.maximum(
np.finfo(dtype.as_numpy_dtype).tiny,
gen_random_ops._random_gamma(
shape, alpha_broadcast, seed=seed1, seed2=seed2) / beta) ops.NotDifferentiable("RandomGamma") def random_poisson(lam, shape, dtype=dtypes.float32, seed=None, name=None):
"""Draws `shape` samples from each of the given Poisson distribution(s). `lam` is the rate parameter describing the distribution(s). Example: samples = tf.random_poisson([0.5, 1.5], [10])
# samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
# the samples drawn from each distribution samples = tf.random_poisson([12.2, 3.3], [7, 5])
# samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
# represents the 7x5 samples drawn from each of the two distributions Args:
lam: A Tensor or Python value or N-D array of type `dtype`.
`lam` provides the rate parameter(s) describing the poisson
distribution(s) to sample.
shape: A 1-D integer Tensor or Python array. The shape of the output samples
to be drawn per "rate"-parameterized distribution.
dtype: The type of `lam` and the output: `float16`, `float32`, or
`float64`.
seed: A Python integer. Used to create a random seed for the distributions.
See
@{tf.set_random_seed}
for behavior.
name: Optional name for the operation. Returns:
samples: a `Tensor` of shape `tf.concat(shape, tf.shape(lam))` with
values of type `dtype`.
"""
with ops.name_scope(name, "random_poisson", [lam, shape]):
lam = ops.convert_to_tensor(lam, name="lam", dtype=dtype)
shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32)
seed1, seed2 = random_seed.get_seed(seed)
return gen_random_ops._random_poisson(shape, lam, seed=seed1, seed2=seed2)

原文链接:https://blog.csdn.net/tz_zs/article/details/75948350

官方文档api 不知道为啥不能访问(已翻墙)

中文官方文档:http://www.tensorfly.cn/tfdoc/api_docs/python/constant_op.html

tensorflow生成随机数的操作 tf.random_normal & tf.random_uniform & tf.truncated_normal & tf.random_shuffle的更多相关文章

  1. tensorflow 生成随机数 tf.random_normal 和 tf.random_uniform 和 tf.truncated_normal 和 tf.random_shuffle

    ____tz_zs tf.random_normal 从正态分布中输出随机值. . <span style="font-size:16px;">random_norma ...

  2. TF之AE:AE实现TF自带数据集AE的encoder之后decoder之前的非监督学习分类—Jason niu

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #Import MNIST data from t ...

  3. TF之AE:AE实现TF自带数据集数字真实值对比AE先encoder后decoder预测数字的精确对比—Jason niu

    import tensorflow as tf import numpy as np import matplotlib.pyplot as plt #Import MNIST data from t ...

  4. 深度学习原理与框架-Tensorflow基本操作-变量常用操作 1.tf.random_normal(生成正态分布随机数) 2.tf.random_shuffle(进行洗牌操作) 3. tf.assign(赋值操作) 4.tf.convert_to_tensor(转换为tensor类型) 5.tf.add(相加操作) tf.divide(相乘操作) 6.tf.placeholder(输入数据占位

    1. 使用tf.random_normal([2, 3], mean=-1, stddev=4) 创建一个正态分布的随机数 参数说明:[2, 3]表示随机数的维度,mean表示平均值,stddev表示 ...

  5. TensorFlow随机值:tf.random_normal函数

    tf.random_normal 函数 random_normal( shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=No ...

  6. tf.reduce_sum tensorflow维度上的操作

    tensorflow中有很多在维度上的操作,本例以常用的tf.reduce_sum进行说明.官方给的api reduce_sum( input_tensor, axis=None, keep_dims ...

  7. tf.random_normal()

    tf.random_normal()函数用于从服从指定正太分布的数值中取出指定个数的值. tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf. ...

  8. tf.random_normal()函数

    tf.random_normal()函数用于从服从指定正太分布的数值中取出指定个数的值. tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf. ...

  9. tf.truncated_normal和tf.random_normal使用方法的区别

    1.tf.truncated_normal使用方法 tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=No ...

随机推荐

  1. 【Spring学习笔记-5.1】Spring容器-父子容器

    来自为知笔记(Wiz)

  2. bzoj 4842: [Neerc2016]Delight for a Cat

    Description ls是一个特别堕落的小朋友,对于n个连续的小时,他将要么睡觉要么打隔膜,一个小时内他不能既睡觉也打隔膜 ,因此一个小时内他只能选择睡觉或者打隔膜,当然他也必须选择睡觉或打隔膜, ...

  3. JavaScript之图片操作2

    在前一次,我们实现最简单的图片切换效果,这一次,依旧还是图片切换,具体效果如下: 通过点击下面的小图,上面的大图和标题随之切换.因此,我们需要三个容器分别放标题,大图和小图. <!--大图描述- ...

  4. onload属性使用方法

    onload事件属性是页面的图片文字等全部加载完毕后执行的事件 window.onload=fun1;function fun1(){    document.getElementsByTagName ...

  5. sublime text 3 3143

    下载链接:https://download.sublimetext.com/Sublime%20Text%20Build%203143%20x64%20Setup.exe 注册信息:sublime t ...

  6. Mongodb 主从同步

    第一步:我们把mongodb部署多服务器上10.12.0.3和10.14.0.1. 第二步:启动10.12.0.3上的mongodb,把该数据库指定为主数据库 先启动主: mongod --port ...

  7. C# implement java like CountDownLatch

    CountDownLatch是在java1.5被引入的,跟它一起被引入的并发工具类还有CyclicBarrier.Semaphore.ConcurrentHashMap和BlockingQueue,它 ...

  8. css border

    CSS border用于设置HTML元素(如div)的边框,包括边框的宽度.颜色和样式.本文章向码农介绍CSS border边框属性详细内容,感兴趣的码农可以参考一下. CSS 边框即CSS bord ...

  9. node实现缓存

    内容: 1.缓存基本原理 2.node实现缓存 1.缓存基本原理 第一重要.缓存策略: cache-control:用于控制缓存,常见的取值有private.no-cache.max-age.must ...

  10. angular 中怎么获取路径上的参数 参考:https://docs.angularjs.org/api/ng/service/$location

    参考: https://docs.angularjs.org/api/ng/service/$location