MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / _calculate

Function _calculate

monai/metrics/average_precision.py:86–113  ·  view source on GitHub ↗
(y_pred: torch.Tensor, y: torch.Tensor)

Source from the content-addressed store, hash-verified

84
85
86def _calculate(y_pred: torch.Tensor, y: torch.Tensor) -> float:
87 if not (y.ndimension() == y_pred.ndimension() == 1 and len(y) == len(y_pred)):
88 raise AssertionError("y and y_pred must be 1 dimension data with same length.")
89 y_unique = y.unique()
90 if len(y_unique) == 1:
91 warnings.warn(f"y values can not be all {y_unique.item()}, skip AP computation and return `Nan`.")
92 return float("nan")
93 if not y_unique.equal(torch.tensor([0, 1], dtype=y.dtype, device=y.device)):
94 warnings.warn(f"y values must be 0 or 1, but in {y_unique.tolist()}, skip AP computation and return `Nan`.")
95 return float("nan")
96
97 n = len(y)
98 indices = y_pred.argsort(descending=True)
99 y = y[indices].cpu().numpy() # type: ignore[assignment]
100 y_pred = y_pred[indices].cpu().numpy() # type: ignore[assignment]
101 npos = ap = tmp_pos = 0.0
102
103 for i in range(n):
104 y_i = cast(float, y[i])
105 if i + 1 < n and y_pred[i] == y_pred[i + 1]:
106 tmp_pos += y_i
107 else:
108 tmp_pos += y_i
109 npos += tmp_pos
110 ap += tmp_pos * npos / (i + 1)
111 tmp_pos = 0
112
113 return ap / npos
114
115
116def compute_average_precision(

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…