utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from torch import Tensor
  15. def _check_data_shape_to_num_outputs(
  16. preds: Tensor, target: Tensor, num_outputs: int, allow_1d_reshape: bool = False
  17. ) -> None:
  18. """Check that predictions and target have the correct shape, else raise error.
  19. Args:
  20. preds: Predicted tensor
  21. target: Ground truth tensor
  22. num_outputs: Number of outputs in multioutput setting
  23. allow_1d_reshape: Allow that for num_outputs=1 that preds and target does not need to be 1d tensors. Instead
  24. code that follows are expected to reshape the tensors to 1d.
  25. """
  26. if preds.ndim > 2 or target.ndim > 2:
  27. raise ValueError(
  28. f"Expected both predictions and target to be either 1- or 2-dimensional tensors,"
  29. f" but got {target.ndim} and {preds.ndim}."
  30. )
  31. cond1 = False
  32. if not allow_1d_reshape:
  33. cond1 = num_outputs == 1 and not (preds.ndim == 1 or preds.shape[1] == 1)
  34. cond2 = num_outputs > 1 and preds.ndim > 1 and num_outputs != preds.shape[1]
  35. if cond1 or cond2:
  36. raise ValueError(
  37. f"Expected argument `num_outputs` to match the second dimension of input, but got {num_outputs}"
  38. f" and {preds.shape[1]}."
  39. )