用中文详细解释:
Fast score computation using PyTorch
I wrote a fast and memory-efficient code for the surface Dice score assuming tolerance 0. The assumption greatly simplifies the code because there is no need to compute distances between surface elements, since distant surface elements do not contribute to the score.
The RAM usage is also significantly decreased by the order of 1/number of slices, because there are no need to compute pairs of distant surface elements, and therefore, only 2 slices of the 3D mask need to be on the RAM.
The computational complexity is O(W×H×D), where W, H, D are width, hight, and depth (number of slices) of the volume, respectively. RAM requirement is O(W×H) because only 2 slices are necessary simultaneously. These do not depend on the content of the segmentation at all; how many positive values or how fragmented they are (after rle are decoded to 2D array).
I implemented with PyTorch. As a bonus, GPU can be used.
The scoreing of kidney_1_dense (1303×912×2279) took 20 minutes using the official code on my local machine, but reduced to 31 seconds with CPU and 3.1 seconds with GPU [3 minutes (CPU) and 16 seconds (GPU) with Kaggle notebook].
The score agree with the official implementation within float32 (~1e-7). Please let me know if you experience a discprancy between the scores or realise something wrong. Since I have just started this competition and just finished writing this code, there must be some bug and misunderstanding (hope they are not crutial).
Version 3:
PyTorch version back to 1.90 can be used.
1. Score computation code
The code computes for one volume, like kidney_1_dense. If you want to compute for more than one volumes, like kidney_1 and kideny_3, compute separately and take the mean.
See the original paper about the surface Dice metric
When you think about the surface Dice, imagine mask values 0/1 on 3-dimensional grid points, not in the cells (cubes or volume). Each cube in the grid has 8 corners and those corner points have the segmentation values 0 or 1. There are 256 patterns of 0/1 for 8 corners, and for each pattern they define a 2-dimmensional surface in the cube, known as the marching cubes.
https://en.wikipedia.org/wiki/Marching_cubes
True-positiveness is same as the ordinary Dice score, If both prediction and ground truth have a non-zero surface in the same cube, that cube is true positive. The 8-corner pattern does not have to be the same to be true positive.
The difference between the volume-Dice and surface-Dice is that the surface area is zero if that cube is completely inside the volume (i.e., all 8 corners have value 1). Only the boundaries contribute to the surface Dice. Also, not all boundary cubes have the same weights, the weight is the marching-cube surface area.
surface_dice=
The sum is over all cubes in the volume and S is the surface area in those cubes. ∑tp is a sum over all true positive cubes, where both prediction and ground truth have non-zero areas.
import numpy as np
import pandas as pd
import sys
import time
import torch
import torch.nn as nn
from PIL import Image
sys.path.append('/kaggle/input/sennet-score/src')
from official_metric import create_table_neighbour_code_to_surface_area
di = '/kaggle/input/blood-vessel-segmentation'
device = torch.device('cuda') # can be 'cpu'
PyTorch version dependence on index data type
torch_ver_major = int(torch.version.split('.')[0])
dtype_index = torch.int32 if torch_ver_major >= 2 else torch.long
def rle_decode(mask_rle: str, shape: tuple) -> np.array:
"""
Decode rle string
https://www.kaggle.com/code/paulorzp/run-length-encode-and-decode/script
https://www.kaggle.com/stainsby/fast-tested-rle
Args:
mask_rle: run length (rle) as string
shape: (height, width) of the mask
Returns:
array[uint8], 1 - mask, 0 - background
"""
s = mask_rle.split()
starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
img = np.zeros(shape[0] * shape[1], dtype=np.uint8)
for lo, hi in zip(starts, ends):
img[lo:hi] = 1
return img.reshape(shape)
def compute_area(y: list, unfold: nn.Unfold, area: torch.Tensor) -> torch.Tensor:
"""
Args:
y (list[Tensor]): A pair of consecutive slices of mask
unfold: nn.Unfold(kernel_size=(2, 2), padding=1)
area (Tensor): surface area for 256 patterns (256, )
Returns:
Surface area of surface in 2x2x2 cube
"""
# Two layers of segmentation masks
yy = torch.stack(y, dim=0).to(torch.float16).unsqueeze(0)
# (batch_size=1, nch=2, H, W)
# bit (0/1) but unfold requires float
# unfold slides through the volume like a convolution
# 2x2 kernel returns 8 values (2 channels * 2x2)
cubes_float = unfold(yy).squeeze(0) # (8, n_cubes)
# Each of the 8 values are either 0 or 1
# Convert those 8 bits to one uint8
cubes_byte = torch.zeros(cubes_float.size(1), dtype=dtype_index, device=device)
# indices are required to be int32 or long for area[cube_byte] below, not uint8
# Can be int32 for torch 2.0.0, int32 raise IndexError in torch 1.13.1.
for k in range(8):
cubes_byte += cubes_float[k, :].to(dtype_index) << k
# Use area lookup table: pattern index -> area [float]
cubes_area = area[cubes_byte]
return cubes_area
def compute_surface_dice_score(submit: pd.DataFrame, label: pd.DataFrame) -> float:
"""
Compute surface Dice score for one 3D volume
submit (pd.DataFrame): submission file with id and rle
label (pd.DataFrame): ground truth id, rle, and also image height, width
"""
# submit and label must contain exact same id in same order
assert (submit['id'] == label['id']).all()
assert len(label) > 0
# All height, width must be the same
len(label['height'].unique()) == 1
len(label['width'].unique()) == 1
# Surface area lookup table: Tensor[float32] (256, )
area = create_table_neighbour_code_to_surface_area((1, 1, 1))
area = torch.from_numpy(area).to(device) # torch.float32
# Slide through the volume like a convolution
unfold = torch.nn.Unfold(kernel_size=(2, 2), padding=1)
r = label.iloc[0]
h, w = r['height'], r['width']
n_slices = len(label)
# Padding before first slice
y0 = y0_pred = torch.zeros((h, w), dtype=torch.uint8, device=device)
num = 0 # numerator of surface Dice
denom = 0 # denominator
for i in range(n_slices + 1):
# Load one slice
if i < n_slices:
r = label.iloc[i]
y1 = rle_decode(r['rle'], (h, w))
y1 = torch.from_numpy(y1).to(device)
r = submit.iloc[i]
y1_pred = rle_decode(r['rle'], (h, w))
y1_pred = torch.from_numpy(y1_pred).to(device)
else:
# Padding after the last slice
y1 = y1_pred = torch.zeros((h, w), dtype=torch.uint8, device=device)
# Compute the surface area between two slices (n_cubes,)
area_pred = compute_area([y0_pred, y1_pred], unfold, area)
area_true = compute_area([y0, y1], unfold, area)
# True positive cube indices
idx = torch.logical_and(area_pred > 0, area_true > 0)
# Surface dice numerator and denominator
num += area_pred[idx].sum() + area_true[idx].sum()
denom += area_pred.sum() + area_true.sum()
# Next slice
y0 = y1
y0_pred = y1_pred
dice = num / denom.clamp(min=1e-8)
return dice.item()
2. Use the scoring function
Prediction
submission1.csv is my prediction for kidney_1_dense using trivial 2D U-Net similar to what yumeneko has shared. The score is irrelevant because this is trained with kidney_1 and applied to kidney_1 (leakage).
submit = pd.read_csv('/kaggle/input/sennet-score/submission1.csv')
submit.head(n=2)
Need height and weight columns; this is same for the official code.
def add_size_columns(df: pd.DataFrame):
"""
df (DataFrame): including id column, e.g., kidney_1_dense_0000
"""
widths = []
heights = []
subdirs = []
nums = []
for i, r in df.iterrows():
file_id = r['id']
subdir = file_id[:-5] # kidney_1_dense
file_num = file_id[-4:] # 0000
filename = '%s/train/%s/images/%s.tif' % (di, subdir, file_num)
img = Image.open(filename)
w, h = img.size
widths.append(w)
heights.append(h)
subdirs.append(subdir)
nums.append(file_num)
df['width'] = widths
df['height'] = heights
df['image_id'] = subdirs
df['slice_id'] = nums
Label for kidney_1_dense only
image_id = 'kidney_1_dense'
label = pd.read_csv(di + '/train_rles.csv')
idx = label['id'].str.startswith(image_id)
label = label[idx]
assert len(label) > 0
Add height, width columns
add_size_columns(label)
label.head(n=2)
%%time
Compute surface Dice score
score = compute_surface_dice_score(submit, label)
score
3. Compare with the official implementation
official_metric.py is a copy of the notebook (Version 24: 6 Dec 2023):
https://www.kaggle.com/code/metric/surface-dice-metric/notebook
Due to insufficient memory and my patience, I reduce the number of slices to 100.
begin, end = 1000, 1100
label = label.iloc[begin:end]
submit = submit.iloc[begin:end]
%%time
Recompute for the subvolume
score = compute_surface_dice_score(submit, label)
score
Again, this is a score with leakage (or train score).
import official_metric
This will take 2 minutes for 100 slices.
%%time
score_official = official_metric.score(label, submit,
row_id_column_name='id',
rle_column_name='rle',
tolerance=0.0,
image_id_column_name='image_id',
slice_id_column_name='slice_id')
score_official
score - score_official
Acceptable ~1e-7 difference for float32.