Clean invalid values (NaN and infinite) from a NumPy array or PyTorch tensor. Args: arr (Union[np.ndarray, torch.Tensor]): Input array or tensor. Returns: Union[np.ndarray, torch.Tensor]: Processed array or tensor with NaN and infinite values removed.
(arr: Union[np.ndarray, torch.Tensor])
| 3 | import numpy as np |
| 4 | |
| 5 | def clean_invalid_values(arr: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]: |
| 6 | |
| 7 | """Clean invalid values (NaN and infinite) from a NumPy array or PyTorch tensor. |
| 8 | Args: |
| 9 | arr (Union[np.ndarray, torch.Tensor]): Input array or tensor. |
| 10 | Returns: |
| 11 | Union[np.ndarray, torch.Tensor]: Processed array or tensor with NaN and infinite values removed. |
| 12 | """ |
| 13 | |
| 14 | if isinstance(arr, torch.Tensor): |
| 15 | mask = torch.isfinite(arr) |
| 16 | elif isinstance(arr, np.ndarray): |
| 17 | mask = np.isfinite(arr) |
| 18 | else: |
| 19 | raise TypeError("Input must be a NumPy array or a PyTorch tensor.") |
| 20 | |
| 21 | arr = arr[mask] |
| 22 | |
| 23 | return arr |
| 24 | |
| 25 | def fill_invalid_values(arr: Union[np.ndarray, torch.Tensor], fill_value: float = 0.0) -> Union[np.ndarray, torch.Tensor]: |
| 26 | """ |