Skip to content

_ones_like

ones_like

Generate ones 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.ones_like(n)  # [[1, 1], [1, 1]]
b = fe.backend.ones_like(n, dtype="float32")  # [[1.0, 1.0], [1.0, 1.0]]

This method can be used with TensorFlow tensors:

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

This method can be used with PyTorch tensors:

p = torch.tensor([[0,1],[2,3]])
b = fe.backend.ones_like(p)  # [[1, 1], [1, 1]]
b = fe.backend.ones_like(p, dtype="float32")  # [[1.0, 1.0], [1.0, 1.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 ones with the same shape as tensor.

Raises:

Type Description
ValueError

If tensor is an unacceptable data type.

Source code in fastestimator/fastestimator/backend/_ones_like.py
def ones_like(tensor: Tensor, dtype: Union[None, str] = None) -> Tensor:
    """Generate ones 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.ones_like(n)  # [[1, 1], [1, 1]]
    b = fe.backend.ones_like(n, dtype="float32")  # [[1.0, 1.0], [1.0, 1.0]]
    ```

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

    This method can be used with PyTorch tensors:
    ```python
    p = torch.tensor([[0,1],[2,3]])
    b = fe.backend.ones_like(p)  # [[1, 1], [1, 1]]
    b = fe.backend.ones_like(p, dtype="float32")  # [[1.0, 1.0], [1.0, 1.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 ones with the same shape as `tensor`.

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