Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify MeanEnsemble to accumulate results in-place. #8141

Draft
wants to merge 4 commits into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions monai/transforms/post/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,17 +679,21 @@ def __init__(self, weights: Sequence[float] | NdarrayOrTensor | None = None) ->
self.weights = torch.as_tensor(weights, dtype=torch.float) if weights is not None else None

def __call__(self, img: Sequence[NdarrayOrTensor] | NdarrayOrTensor) -> NdarrayOrTensor:
img_ = self.get_stacked_torch(img)
if self.weights is not None:
self.weights = self.weights.to(img_.device)
shape = tuple(self.weights.shape)
for _ in range(img_.ndimension() - self.weights.ndimension()):
shape += (1,)
weights = self.weights.reshape(*shape)
out_pt = None
total_weight = 0.0

for i, pred in enumerate(img):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may need check the the type for img what if it's a single array. Something like the change here:

if isinstance(img, Sequence) and isinstance(img[0], np.ndarray):
img = [torch.as_tensor(i) for i in img]
elif isinstance(img, np.ndarray):
img = torch.as_tensor(img)
out: torch.Tensor = torch.stack(img) if isinstance(img, Sequence) else img # type: ignore
return out

pred = torch.as_tensor(pred)
if out_pt is None:
out_pt = torch.zeros_like(pred)

if self.weights is not None:
weight = self.weights[i].to(pred.device)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you handle whether self.weights has the same shape with the img?


img_ = img_ * weights / weights.mean(dim=0, keepdim=True)
out_pt += pred * weight
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If self.weights is None, this line will show error. You may need set a default value or move the computation in the for-loop.

total_weight += weight

out_pt = torch.mean(img_, dim=0)
out_pt /= total_weight
return self.post_convert(out_pt, img)


Expand Down
Loading