当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python tf.compat.v1.keras.initializers.TruncatedNormal用法及代码示例


生成截断正态分布的初始化程序。

继承自:truncated_normal_initializer

用法

tf.compat.v1.keras.initializers.TruncatedNormal(
    mean=0.0, stddev=0.05, seed=None, dtype=tf.dtypes.float32
)

参数

  • mean python 标量或标量张量。要生成的随机值的平均值。
  • stddev python 标量或标量张量。要生成的随机值的标准差。
  • seed 一个 Python 整数。用于创建随机种子。有关行为,请参见tf.compat.v1.set_random_seed
  • dtype 默认数据类型,如果在调用初始化程序时没有提供 dtype 参数,则使用该类型。仅支持浮点类型。

迁移到 TF2

警告:这个 API 是为 TensorFlow v1 设计的。继续阅读有关如何从该 API 迁移到本机 TensorFlow v2 等效项的详细信息。见TensorFlow v1 到 TensorFlow v2 迁移指南有关如何迁移其余代码的说明。

虽然它是一个旧的 compat.v1 api,但 tf.compat.v1.keras.initializers.TruncatedNormal 与即刻执行和 tf.function 兼容。

要切换到本机 TF2,请切换到使用 tf.keras.initializers.TruncatedNormal(不是从 compat.v1 ),如果需要更改默认 dtype,请使用 tf.keras.backend.set_floatx(float_dtype) 或在调用初始化程序时传递 dtype,而不是在构造初始化程序时传递它。

随机种子行为:另请注意,如果您将种子传递给 TF2 初始化程序 API,它将在每次初始化时重用相同的种子(与 TF1 初始化程序不同)

到原生 TF2 的结构映射

前:

initializer = tf.compat.v1.keras.initializers.TruncatedNormal(
  mean=mean,
  stddev=stddev,
  seed=seed,
  dtype=dtype)

weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))

后:

initializer = tf.keras.initializers.TruncatedNormal(
  mean=mean,
  # seed=seed,  # Setting a seed in the native TF2 API
                # causes it to produce the same initializations
                # across multiple calls of the same initializer.
  stddev=stddev)

weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))

如何映射参数

TF1 参数名称 TF2 参数名称 注意
mean mean 没有更改默认值
stddev stddev 没有更改默认值
seed seed 不同的随机数生成语义(在未来版本中更改)。如果设置,TF2 版本将使用无状态随机数生成,即使在多次调用初始化程序实例时也会产生完全相同的初始化。 compat.v1 版本每次都会生成新的初始化。如果您每次都需要不同的初始化,请不要设置种子。相反,如果您需要确定性,可以使用 tf.random.set_seed 设置全局 tf 种子,或者使用单独的初始化程序实例和不同的种子来初始化每个权重。
dtype dtype TF2 原生 api 仅将其作为 __call__ arg,而不是构造函数 arg。
partition_info - (TF1 中的 __call__ arg)不支持

fixed-seed 行为差异示例

compat.v1 固定种子行为:

initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor:shape=(), dtype=bool, numpy=False>

后:

initializer = tf.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor:shape=(), dtype=bool, numpy=True>

这些值与random_normal_initializer 中的值相似,但与平均值相差超过两个标准差的值将被丢弃并重新绘制。这是神经网络权重和过滤器的推荐初始化程序。

相关用法


注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.compat.v1.keras.initializers.TruncatedNormal。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。