【bug解决】AttributeError: module ‘tensorflow‘ has no attribute ‘truncated_normal‘

目录

一、问题描述

二、问题分析

三、进一步分析函数

总结


一、问题描述

想要在tensorflow中产生正态分布的随机数,网上找到的资料是这样的:

import tensorflow as tf

c = tf.truncated_normal(shape=[2, 3], mean=0, stddev=1)

with tf.Session() as sess:
    print(sess.run(c))

# c = tf.compat.v1.random.truncated_normal(shape=[2, 3], mean=0, stddev=1)
# print(c)

但是运行后会有如下报错:

D:\ANACON\envs\L2RPN\python.exe "E:/Undergraduate/Situation Awareness/LeNet-5_learning.py" 
Traceback (most recent call last):
  File "E:\Undergraduate\Situation Awareness\LeNet-5_learning.py", line 3, in <module>
    c = tf.truncated_normal(shape=[2, 3], mean=0, stddev=1)
AttributeError: module 'tensorflow' has no attribute 'truncated_normal'

进程已结束,退出代码1

即:


二、问题分析

这是Tensorflow版本不同造成的,我用的是2.0,最新版本改了函数名和使用方法。具体如下:

import tensorflow as tf

# c = tf.truncated_normal(shape=[2, 3], mean=0, stddev=1)
# with tf.Session() as sess:
#     print(sess.run(c))

c = tf.compat.v1.random.truncated_normal(shape=[2, 3], mean=0, stddev=1)
print(c)

运行结果:

tf.Tensor(
[[-0.18886028 -0.737174    1.5540563 ]
 [ 1.5035461   0.23027402 -0.67294544]], shape=(2, 3), dtype=float32)

问题解决


三、进一步分析函数

tf.truncated_normal(shape, mean, stddev)

这个函数产生正态分布,均值和标准差自己设定。这是一个截断的产生正态分布的函数,生成的值服从具有指定平均值和标准偏差的正态分布,换句话说,产生的值如果与均值的差值大于两倍的标准差则丢弃重新选择。和一般的正态分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的。

在正态分布的曲线中:
横轴区间(μ-σ,μ+σ)内的面积为68.268949%
横轴区间(μ-2σ,μ+2σ)内的面积为95.449974%
横轴区间(μ-3σ,μ+3σ)内的面积为99.730020%

X落在(μ-3σ,μ+3σ)以外的概率小于千分之三,在实际问题中常认为相应的事件是不会发生的,基本上可以把区间(μ-3σ,μ+3σ)看作是随机变量X实际可能的取值区间,这称之为正态分布的“3σ”原则。
在tf.truncated_normal中如果x的取值在区间(μ-2σ,μ+2σ)之外则重新进行选择。这样保证了生成的值都在均值附近。

释义:截断的产生正态分布的随机数,即随机数与均值的差值若大于两倍的标准差,则重新生成。

  • shape,生成张量的维度
  • mean,均值
  • stddev,标准差


总结

tensorflow版本不同,函数名可能会有不同,用法也会略有差别,要注意辨别。 

猜你喜欢

转载自blog.csdn.net/mzy20010420/article/details/127739587