本文整理汇总了Python中tensorflow.keras.initializers方法的典型用法代码示例。如果您正苦于以下问题:Python keras.initializers方法的具体用法?Python keras.initializers怎么用?Python keras.initializers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras
的用法示例。
在下文中一共展示了keras.initializers方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build
# 需要导入模块: from tensorflow import keras [as 别名]
# 或者: from tensorflow.keras import initializers [as 别名]
def build(self, input_shape=None):
self.layer.input_spec = InputSpec(shape=input_shape)
if hasattr(self.layer, 'built') and not self.layer.built:
self.layer.build(input_shape)
self.layer.built = True
# initialise p
self.p_logit = self.add_weight(name='p_logit', shape=(1,),
initializer=initializers.RandomUniform(self.init_min, self.init_max),
dtype=tf.float32, trainable=True)
self.p = tf.nn.sigmoid(self.p_logit)
tf.compat.v1.add_to_collection("LAYER_P", self.p)
# initialise regularizer / prior KL term
input_dim = tf.reduce_prod(input_shape[1:]) # we drop only last dim
weight = self.layer.kernel
kernel_regularizer = self.weight_regularizer * tf.reduce_sum(tf.square(weight)) / (1. - self.p)
dropout_regularizer = self.p * tf.math.log(self.p)
dropout_regularizer += (1. - self.p) * tf.math.log(1. - self.p)
dropout_regularizer *= self.dropout_regularizer * tf.cast(input_dim, tf.float32)
regularizer = tf.reduce_sum(kernel_regularizer + dropout_regularizer)
self.layer.add_loss(regularizer)
# Add the regularisation loss to collection.
tf.compat.v1.add_to_collection(tf.compat.v1.GraphKeys.REGULARIZATION_LOSSES, regularizer)
示例2: initializer_factory
# 需要导入模块: from tensorflow import keras [as 别名]
# 或者: from tensorflow.keras import initializers [as 别名]
def initializer_factory(initializer_or_name_with_params
) -> Union[keras.initializers.Initializer, None]:
"""
Factory to construct keras initializer from its name or config
Parameters
----------
initializer_or_name_with_params
initilaizer itself, then returned as is, or the name of initializer
from keras.initializers namespace or config with name and params
to pass to constructor
Returns
-------
initializer
initializer
"""
if isinstance(initializer_or_name_with_params,
keras.initializers.Initializer):
return initializer_or_name_with_params
if initializer_or_name_with_params is None:
return None
name_with_params = initializer_or_name_with_params
name, params = _get_name_and_params(name_with_params, 'RandomNormal')
if not hasattr(keras.initializers, name):
assert ("Use names from keras.initializers class names as initializer "
"name (got {})".format(name))
initializer = getattr(keras.initializers, name)(**params)
return initializer