Utility Functions#
This module contains simple utility functions to facilitate conversions between NumPy arrays and PyTorch tensors, and shape validation.
Functions#
- objectrl.utils.utils.totorch(x: ndarray, dtype: dtype = torch.float32, device: str | device = 'cuda') Tensor[source]#
Converts a NumPy array or other compatible object to a PyTorch tensor.
- Parameters:
x (array-like) – Input data to convert.
dtype (torch.dtype, optional) – Desired data type of the output tensor. Default is torch.float32.
device (str or torch.device, optional) – Device to store the tensor on. Default is “cuda”.
- Returns:
A tensor containing the same data as x, on the specified device and with the specified dtype.
- Return type:
torch.Tensor
- objectrl.utils.utils.tonumpy(x: Tensor) ndarray[source]#
Converts a PyTorch tensor to a NumPy array. Automatically moves the tensor to CPU and detaches it from the computation graph.
- Parameters:
x (torch.Tensor) – Input tensor.
- Returns:
NumPy array with the same data as the input tensor.
- Return type:
numpy.ndarray
- objectrl.utils.utils.toint(x: Tensor) int[source]#
Converts a PyTorch tensor to an integer.
- Parameters:
x (torch.Tensor) – Input tensor.
- Returns:
Integer value of the input tensor.
- Return type:
int
- objectrl.utils.utils.dim_check(tensor1: Tensor, tensor2: Tensor) None[source]#
Asserts that two tensors have the same shape. Useful for debugging shape mismatches in model inputs/outputs.
- Parameters:
tensor1 (torch.Tensor) – First tensor.
tensor2 (torch.Tensor) – Second tensor.
- Raises:
AssertionError – If the shapes of the two tensors do not match.
Function Details#
- totorch(x, dtype=torch.float32, device=”cuda”) -> torch.Tensor
Converts a NumPy array or compatible object into a PyTorch tensor with specified dtype and device.
- tonumpy(x) -> numpy.ndarray
Converts a PyTorch tensor to a NumPy ndarray, moving it to CPU and detaching from the computation graph.
- toint(x) -> int
Converts a PyTorch tensor containing a single value to a Python integer.
- dim_check(tensor1, tensor2) -> None
Asserts that two tensors have the same shape. Raises AssertionError if they differ.
Example Usage#
import numpy as np
import torch
arr = np.array([1, 2, 3])
tensor = totorch(arr, dtype=torch.float32, device="cpu")
back_to_np = tonumpy(tensor)
integer_value = toint(torch.tensor(5))
dim_check(tensor, torch.ones_like(tensor)) # no error