深入浅出TensorFlow2函数——tf.random.normal

tf.random.normal是TensorFlow2中的一个函数,用于生成符合正态分布的随机张量。该函数接受参数如形状、均值、标准差、数据类型和随机种子,返回指定形状的张量,其值填充自定义正态分布。设置种子可以确保结果的可重复性。例子展示了如何使用该函数生成不同情况的随机张量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类目录:《深入浅出TensorFlow2函数》总目录


语法
tf.random.normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.dtypes.float32,
    seed=None,
    name=None
)
参数
  • shape:输出张量的形状,为一个一维整数张量或Python数组。
  • mean 正态分布的平均值。类型为张量或dtype,可与stddev一起广播。
  • stddev:正态分布的标准偏差。类型为张量或dtype,可与mean一起广播。
  • dtype:输出的浮点类型:float16bfloat16float32float64,默认为float32
  • seed:[int] 用于为创建分布的随机种子。可参考tf.random.set_seed
  • name:[可选] 操作的名称。
返回值

用随机正态分布值填充的指定形状的张量。

实例
tf.random.normal([2,2], 0, 1, tf.float32, seed=1)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-1.3768897 , -0.01258316],
      [-0.169515   ,  1.0824056 ]], dtype=float32)>
函数实现
@tf_export("random.normal", v1=["random.normal", "random_normal"])
@dispatch.add_dispatch_support
@deprecation.deprecated_endpoints("random_normal")
def random_normal(shape,
                  mean=0.0,
                  stddev=1.0,
                  dtype=dtypes.float32,
                  seed=None,
                  name=None):
  """Outputs random values from a normal distribution.
  Example that generates a new set of random values every time:
  >>> tf.random.set_seed(5);
  >>> tf.random.normal([4], 0, 1, tf.float32)
  <tf.Tensor: shape=(4,), dtype=float32, numpy=..., dtype=float32)>
  Example that outputs a reproducible result:
  >>> tf.random.set_seed(5);
  >>> tf.random.normal([2,2], 0, 1, tf.float32, seed=1)
  <tf.Tensor: shape=(2, 2), dtype=float32, numpy=
  array([[-1.3768897 , -0.01258316],
        [-0.169515   ,  1.0824056 ]], dtype=float32)>
  In this case, we are setting both the global and operation-level seed to
  ensure this result is reproducible.  See `tf.random.set_seed` for more
  information.
  Args:
    shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
    mean: A Tensor or Python value of type `dtype`, broadcastable with `stddev`.
      The mean of the normal distribution.
    stddev: A Tensor or Python value of type `dtype`, broadcastable with `mean`.
      The standard deviation of the normal distribution.
    dtype: The float type of the output: `float16`, `bfloat16`, `float32`,
      `float64`. Defaults to `float32`.
    seed: A Python integer. Used to create a random seed for the distribution.
      See
      `tf.random.set_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 = tensor_util.shape_tensor(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)
    tensor_util.maybe_set_static_shape(value, shape)
    return value
tf.random_normal函数是一个用于生成服从正态分布的随机数的函数。它的参数包括shape、mean、stddev、dtype、seed和name。其中,shape参数用于指定输出张量的形状,mean参数用于指定正态分布的均值,默认为0,stddev参数用于指定正态分布的标准差,默认为1.0,dtype参数用于指定输出的数据类型,默认为tf.float32,seed参数用于设置随机数种子,是一个整数,当设置之后,每次生成的随机数都一样,name参数用于指定操作的名称。 以下是一个使用tf.random_normal函数生成100个服从正态分布的随机数的例子: norm = tf.random_normal([100]) with tf.Session() as sess: norm_data = norm.eval() print(norm_data[:10]) 输出结果为:[-2.1284895 -0.4170771 -0.8462604 2.8098361 0.06967747 1.3854322 -1.4105673 0.93468976 -0.40508598 -0.3559054 ] 可以使用matplotlib库中的hist函数将生成的随机数绘制成直方图: import matplotlib.pyplot as plt plt.hist(norm_data) plt.show() 这样可以可视化正态分布的数据分布情况。 另外,tf.constant函数是用于创建一个常量张量的函数,它的参数包括value、dtype、shape、name和verify_shape。其中,value参数可以是单个的数,也可以是一个列表,dtype参数用于指定创建的变量的类型,默认是int,shape参数用于指定张量的形状,name参数用于指定操作的名称,verify_shape参数用于控制是否验证形状。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [tf.random_normal()函数](https://blog.csdn.net/weixin_30278237/article/details/95614943)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [tf.random_normal函数](https://blog.csdn.net/qq_45176548/article/details/116327341)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [TensorFlow常用函数:创建张量(tf.constant),及一些特殊张量的创建。zeros,ones,fill,正态分布:random...](https://download.csdn.net/download/weixin_38688969/14910936)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值