keras/keras_core/initializers/constant_initializers.py

67 lines
2.3 KiB
Python
Raw Normal View History

2023-04-19 19:52:58 +00:00
from keras_core import operations as ops
from keras_core.api_export import keras_core_export
from keras_core.backend import standardize_dtype
2023-04-09 19:21:45 +00:00
from keras_core.initializers.initializer import Initializer
2023-04-19 19:52:58 +00:00
@keras_core_export("keras_core.initializers.Zeros")
2023-04-09 19:21:45 +00:00
class Zeros(Initializer):
"""Initializer that generates tensors initialized to 0.
Examples:
>>> # Standalone usage:
>>> initializer = Zeros()
>>> values = initializer(shape=(2, 2))
>>> # Usage in a Keras layer:
>>> initializer = Zeros()
>>> layer = Dense(3, kernel_initializer=initializer)
"""
2023-04-19 19:52:58 +00:00
def __call__(self, shape, dtype=None):
2023-04-09 19:21:45 +00:00
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only numeric or boolean dtypes
are supported. If not specified, `keras_core.backend.floatx()` is
used, which default to `float32` unless you configured it otherwise
(via `keras_core.backend.set_floatx(float_dtype)`).
**kwargs: Additional keyword arguments.
"""
dtype = standardize_dtype(dtype)
2023-04-19 19:52:58 +00:00
return ops.zeros(shape, dtype=dtype)
2023-04-09 19:21:45 +00:00
2023-04-19 19:52:58 +00:00
@keras_core_export("keras_core.initializers.Ones")
2023-04-09 19:21:45 +00:00
class Ones(Initializer):
"""Initializer that generates tensors initialized to 1.
Also available via the shortcut function `ones`.
Examples:
>>> # Standalone usage:
>>> initializer = Ones()
>>> values = initializer(shape=(2, 2))
>>> # Usage in a Keras layer:
>>> initializer = Ones()
>>> layer = Dense(3, kernel_initializer=initializer)
"""
2023-04-19 19:52:58 +00:00
def __call__(self, shape, dtype=None):
2023-04-09 19:21:45 +00:00
"""Returns a tensor object initialized as specified by the initializer.
Args:
shape: Shape of the tensor.
dtype: Optional dtype of the tensor. Only numeric or boolean dtypes
are supported. If not specified, `keras_core.backend.floatx()` is
used, which default to `float32` unless you configured it otherwise
(via `keras_core.backend.set_floatx(float_dtype)`).
**kwargs: Additional keyword arguments.
"""
dtype = standardize_dtype(dtype)
2023-04-19 19:52:58 +00:00
return ops.ones(shape, dtype=dtype)