abracudabra.conversion.ctensor

abracudabra.conversion.ctensor#

Convert to Torch tensor.

Functions#

to_tensor(sequence, /[, device, strict])

Convert an array, series, or dataframe to a Torch tensor.

Module Contents#

abracudabra.conversion.ctensor.to_tensor(sequence, /, device=None, *, strict=False)[source]#

Convert an array, series, or dataframe to a Torch tensor.

Parameters:
  • sequence (abracudabra._annotations.Array | abracudabra._annotations.Series | torch.Tensor) – The sequence to convert.

  • device (abracudabra.device.base.Device | str | None) – The device to convert the sequence to. If None, the sequence stays on the same device.

  • strict (bool) – Whether to raise an error if the sequence is not a valid type. A NumPy/CuPy array, Pandas/cuDF series or dataframe, or Torch tensor are valid types. If False, the sequence is converted to a Torch tensor if possible, but it might raise an error if the conversion is not possible.

Returns:

A Torch tensor.

Raises:

TypeError – If the sequence is not a valid type and strict is True.

Return type:

torch.Tensor

Examples

Build a Torch tensor from a sequence

>>> import torch
>>> to_tensor([1, 2, 3])
tensor([1, 2, 3])

Build a Torch tensor from a CuPy array

>>> import cupy as cp
>>> cupy_array = cp.array([4, 5, 6])
>>> torch_tensor = to_tensor(cupy_array)
>>> print(torch_tensor.device)
tensor([4, 5, 6], device='cuda:0')