torch_ecg.utils.one_hot_encode#

torch_ecg.utils.one_hot_encode(cls_array: ~numpy.ndarray | ~torch.Tensor | ~typing.Sequence[~typing.Sequence[int]], num_classes: int | None = None, dtype: type = <class 'numpy.float32'>) ndarray[source]#

Convert a categorical array to a one-hot array.

Convert a categorical (class indices) array of shape (num_samples,) to a one-hot (binary) array of shape (num_samples, num_classes).

Parameters:
  • cls_array (numpy.ndarray or torch.Tensor or Sequence[Sequence[int]]]) – Class indices array (tensor) of shape (num_samples,) (single-class case), or a list of list of class indices (multi-class case); or of shape (num_samples, num_samples) if num_classes is not None, in which case cls_array should be consistant with num_classes, and the function will return cls_array directly.

  • num_classes (int, optional) – Number of classes. If not specified, it will be inferred from the values of cls_array.

  • dtype (type, default np.float32) – Data type of the output binary array.

Returns:

Binary array of shape (num_samples, num_classes).

Return type:

numpy.ndarray

Examples

>>> cls_array = torch.randint(0, 26, size=(1000,))
>>> bin_array = one_hot_encode(cls_array)
>>> cls_array = np.random.randint(0, 26, size=(1000,))
>>> bin_array = one_hot_encode(cls_array)
>>> cls_array = [[1, 5], [2], [0, 1, 4]]
>>> bin_array = one_hot_encode(cls_array, num_classes=7)