Skip to content

_get_shape

get_shape

Find shape of a given tensor.

This method can be used with Numpy data:

n = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
b = fe.backend.get_shape(n)  # [3,2,2]

This method can be used with TensorFlow tensors:

t = tf.constant([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
b = fe.backend.get_shape(t)  # [3,2,2]

This method can be used with PyTorch tensors:

p = torch.tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
b = fe.backend.get_shape(p)  # [3,2,2]

Parameters:

Name Type Description Default
tensor Array

The tensor to find shape of.

required

Returns:

Type Description
Tuple[int, ...]

Shape of the given 'tensor'.

Raises:

Type Description
ValueError

If tensor is an unacceptable data type.

Source code in fastestimator/fastestimator/backend/_get_shape.py
def get_shape(tensor: Array) -> Tuple[int, ...]:
    """Find shape of a given `tensor`.

    This method can be used with Numpy data:
    ```python
    n = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
    b = fe.backend.get_shape(n)  # [3,2,2]
    ```

    This method can be used with TensorFlow tensors:
    ```python
    t = tf.constant([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
    b = fe.backend.get_shape(t)  # [3,2,2]
    ```

    This method can be used with PyTorch tensors:
    ```python
    p = torch.tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
    b = fe.backend.get_shape(p)  # [3,2,2]
    ```

    Args:
        tensor: The tensor to find shape of.

    Returns:
        Shape of the given 'tensor'.

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