Skip to content

_zeros_like

zeros_like

Generate zeros shaped like tensor with a specified dtype.

This method can be used with Numpy data:

n = np.array([[0,1],[2,3]])
b = fe.backend.zeros_like(n)  # [[0, 0], [0, 0]]
b = fe.backend.zeros_like(n, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]

This method can be used with TensorFlow tensors:

t = tf.constant([[0,1],[2,3]])
b = fe.backend.zeros_like(t)  # [[0, 0], [0, 0]]
b = fe.backend.zeros_like(t, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]

This method can be used with PyTorch tensors:

p = torch.tensor([[0,1],[2,3]])
b = fe.backend.zeros_like(p)  # [[0, 0], [0, 0]]
b = fe.backend.zeros_like(p, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]

Parameters:

Name Type Description Default
tensor Tensor

The tensor whose shape will be copied.

required
dtype Union[None, str]

The data type to be used when generating the resulting tensor. If None then the tensor dtype is used.

None

Returns:

Type Description
Tensor

A tensor of zeros with the same shape as tensor.

Raises:

Type Description
ValueError

If tensor is an unacceptable data type.

Source code in fastestimator/fastestimator/backend/_zeros_like.py
def zeros_like(tensor: Tensor, dtype: Union[None, str] = None) -> Tensor:
    """Generate zeros shaped like `tensor` with a specified `dtype`.

    This method can be used with Numpy data:
    ```python
    n = np.array([[0,1],[2,3]])
    b = fe.backend.zeros_like(n)  # [[0, 0], [0, 0]]
    b = fe.backend.zeros_like(n, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]
    ```

    This method can be used with TensorFlow tensors:
    ```python
    t = tf.constant([[0,1],[2,3]])
    b = fe.backend.zeros_like(t)  # [[0, 0], [0, 0]]
    b = fe.backend.zeros_like(t, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]
    ```

    This method can be used with PyTorch tensors:
    ```python
    p = torch.tensor([[0,1],[2,3]])
    b = fe.backend.zeros_like(p)  # [[0, 0], [0, 0]]
    b = fe.backend.zeros_like(p, dtype="float32")  # [[0.0, 0.0], [0.0, 0.0]]
    ```

    Args:
        tensor: The tensor whose shape will be copied.
        dtype: The data type to be used when generating the resulting tensor. If None then the `tensor` dtype is used.

    Returns:
        A tensor of zeros with the same shape as `tensor`.

    Raises:
        ValueError: If `tensor` is an unacceptable data type.
    """
    if tf.is_tensor(tensor):
        return tf.zeros_like(tensor, dtype=dtype)
    elif isinstance(tensor, torch.Tensor):
        return torch.zeros_like(tensor, dtype=STRING_TO_TORCH_DTYPE[dtype])
    elif isinstance(tensor, np.ndarray):
        return np.zeros_like(tensor, dtype=dtype)
    else:
        raise ValueError("Unrecognized tensor type {}".format(type(tensor)))