Comments (2)
Probably yes. if you can calculate the shortest distance to pixels of GT boundaries for 3D data.
from boundary-loss.
Yes it is very easy to do ; actually the current implementation is somewhat 3d ready. I did the last required part in private ; haven't tested/published that yet.
The surface loss implementation is literally the same ; as we multiply element wise two tensors of same shape [1]
class SurfaceLoss():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
self.nd: str = kwargs["nd"] # 'wh' for 2d case, 'whd' for 3d case
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, dist_maps: Tensor, _: Tensor) -> Tensor:
assert simplex(probs)
assert not one_hot(dist_maps)
pc = probs[:, self.idc, ...].type(torch.float32)
dc = dist_maps[:, self.idc, ...].type(torch.float32)
multipled = einsum(f"bk{self.nd},bk{self.nd}->bk{self.nd}", pc, dc)
loss = multipled.mean()
return loss
Most of the difference is for the one_hot2dist. Now, we have almost a guarantee that the spatial resolution is different between all axis, so we need to take that into account. The good news is that the function it used internally already handle that case, so it is only a matter of adding an optional parameter:
def one_hot2dist(seg: np.ndarray, resolution: Tuple[float, float, float] = None) -> np.ndarray:
assert one_hot(torch.tensor(seg), axis=0)
K: int = len(seg)
res = np.zeros_like(seg)
for k in range(K):
posmask = seg[k].astype(np.bool)
if posmask.any():
negmask = ~posmask
res[k] = distance(negmask, sampling=resolution) * negmask \
- (distance(posmask, sampling=resolution) - 1) * posmask
# The idea is to leave blank the negative classes
# since this is one-hot encoded, another class will supervise that pixel
return res
At last, I added something in my dataloader to support the different resolution ; there is many ways to do that. I personally had saved the resolution for each 3d volume in a dictionnary (trimmed the loader a lot, you get the idea):
class SliceDataset(Dataset):
def __init__(self, filenames: List[str], folders: List[Path], are_hots: List[bool],
bounds_generators: List[Callable], transforms: List[Callable], debug=False, quiet=False,
K=4, in_memory: bool = False, spacing_dict: Dict[str, Tuple[float, ...]] = None,
augment: Optional[Callable] = None, ignore_norm: bool = False,
dimensions: int = 2, debug_size: int = 10) -> None:
self.folders: List[Path] = folders
self.transforms: List[Callable[[Tuple, int], Callable[[D], Tensor]]] = transforms
assert len(self.transforms) == len(self.folders)
self.filenames: List[str] = filenames
self.K: int = K # Number of classes
self.spacing_dict: Optional[Dict[str, Tuple[float, ...]]] = spacing_dict
if self.spacing_dict:
assert len(self.spacing_dict) == len(self.filenames)
print(f"> Spacing dictionnary loaded correctly")
def __getitem__(self, index: int) -> Dict[str, Union[str, Tensor, List[Tensor], List[Tuple[slice, ...]]]]:
filename: str = self.filenames[index]
path_name: Path = Path(filename)
images: List[D]
if path_name.suffix == ".png":
images = [Image.open(files[index]) for files in self.files]
elif path_name.suffix == ".npy":
images = [np.load(files[index]) for files in self.files]
else:
raise ValueError(filename)
resolution: Tuple[float, ...]
if self.spacing_dict:
resolution = self.spacing_dict[path_name.stem]
else:
resolution = tuple([1] * self.dimensions)
# Final transforms and assertions
assert len(images) == len(self.folders) == len(self.transforms)
t_tensors: List[Tensor] = [tr(resolution, self.K)(e) for (tr, e) in zip(self.transforms, images)]
_, *img_shape = t_tensors[0].shape
final_tensors = t_tensors
# [...]
return {'filenames': filename,
'images': final_tensors[0],
'gt': final_tensors[1],
'labels': final_tensors[2:],
'spacings': torch.tensor(resolution)}
Let me know if something remains unclear, but I believe that going from 2d to 3d is pretty quick ; as long as you already have the 3D CNN obviously.
[1] My code states explicitly the expected number of dimensions with parameters, to explode in case it receives something different. This is my personal philosophy of brittleness on purpose, which allow to easily catch mistakes in the formatting of the data. The default broadcasting rules are so powerful that it often "fails silently", in the sense that it does something (not what you intended to write), but just output non-sense and can take some time to debug.
from boundary-loss.
Related Issues (20)
- Does einsum really make the code easier to understand HOT 2
- ISLES 2018 HOT 1
- Heterogeneous resolution yields non-zero boundary. HOT 5
- InvalidArgumentError: required broadcastable shapes at loc(unknown) [Op:Mul] HOT 2
- Can this loss be used for multi-label classification? HOT 4
- Create dist_map for image segmentation mask as label. HOT 2
- Is multiplication by negmask in one_hot2dist() irrelevant? HOT 2
- Question about the optional argument resolution in the dist_map_transform function HOT 1
- About the calculation of dist_map HOT 5
- how to use with sigmoid as activation function when meeting binary classification segmentation task HOT 3
- how to adjust the lambda parameter HOT 5
- How to use HausdorffLoss? HOT 1
- How to use HausdorffLoss? HOT 1
- How to one-hot encode a multi-class dataset and how to use Boundary Loss on B x N x W x H logits? HOT 2
- Only using boundary loss leads to non convergence HOT 1
- Failure of matching datasets of WMH HOT 1
- Is it possible to train the Boundary Loss code on a GPU? HOT 1
- Whether this loss function can be applied to the partition of a hollow region, that is, a region with two boundaries HOT 2
- License Request
- zero question
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from boundary-loss.