09 / 14 · Convolutional Networks
Semantic segmentation
How a network labels every pixel of an image: semantic, instance and panoptic segmentation, fully convolutional networks, the U-Net encoder–decoder with skip connections, dilated convolutions in DeepLab, cross-entropy and Dice losses, IoU and mIoU, and Mask R-CNN for instances.
On this page 10
The previous note located objects with boxes. A box is a coarse answer: a road, the sky or a tumour has no useful box, and a box around a cyclist contains as much street as cyclist. Segmentation labels every pixel instead. Its output has the size of its input, which a classification backbone, built to shrink an image to one vector, cannot produce directly. This note shows how to get a full-resolution output from a convolutional network: by making it fully convolutional, by adding a decoder with skip connections, or by keeping the resolution high with dilated convolutions. It then covers the losses that train such a network and the metrics that score it, which reuse the IoU of the previous note pixel by pixel.
Notation. An image is , and its label map assigns each pixel a class , class 0 usually background. The network outputs logits at every pixel and probabilities . For a class , marks the pixels that truly belong to it. In evaluation, counts the pixels of true class predicted as class .
Semantic, instance and panoptic segmentation#
Three tasks share the name.
- Semantic segmentation assigns every pixel a class. Two cars side by side become one region of class “car”.
- Instance segmentation finds every countable object, a “thing”, and gives it its own mask. It is detection with masks instead of boxes; pixels that belong to no object are left unlabelled.
- Panoptic segmentation (Kirillov et al., 2019) combines both: every pixel gets a class, and pixels of things also get an instance id. Amorphous regions, “stuff” such as sky, road or grass, get only a class.
Semantic, instance and panoptic segmentation
The metric for panoptic segmentation, panoptic quality, matches predicted and true segments that overlap with IoU above 0.5, a threshold that makes the matching unique, and then
the mean IoU of the matched segments times an F1-like recognition score (section 4). This note is mostly about the semantic task, the base of the other two; Mask R-CNN at the end handles instances.
Baseline: classify a patch around every pixel#
A classifier can label a pixel by looking at a patch centred on it. Applied to every pixel this works, and it was the best method for segmenting neuronal membranes in electron microscopy in 2012 (Ciresan et al., 2012). It has two problems, which the U-Net paper names (Ronneberger, Fischer and Brox, 2015, section 1). It is slow: a image needs forward passes, and neighbouring patches share almost all their pixels, so almost all the computation is repeated. And the patch size is a bad compromise: a large patch gives context but needs more pooling, which blurs the location, while a small patch localizes well and sees too little to know what it is looking at.
Fully convolutional networks#
A classification network ends in fully connected layers that require a fixed input size. But a fully connected layer on a map is a convolution with a kernel and no padding: each output unit takes a weighted sum over all inputs, which is what one position of the kernel does. A convolution plays the same role for the later layers (pointwise convolutions). Rewritten this way, the network accepts any input size and returns a map of class scores instead of one vector. Fully convolutional networks (FCN, Long, Shelhamer and Darrell, 2015) take a classification backbone, convert it so, and train it end to end on per-pixel labels.
Worked example. A VGG-16 backbone has total stride 32. A image gives a map after the last pooling, and the converted layer, sliding over it without padding, gives a map of class scores, each the output the original classifier would give for one window. Each score cell stands for a block of pixels, so the map must be upsampled 32 times, and the boundaries come out blocky.
FCN upsamples with transposed convolutions, initialized to bilinear interpolation and then learned, and it fixes the blockiness with skip connections from earlier layers. FCN-32s upsamples the stride-32 scores directly. FCN-16s adds scores predicted from the stride-16 pool4 features before upsampling, and FCN-8s adds pool3 at stride 8 as well. On a subset of PASCAL VOC 2011 validation the mean IoU rose from 59.4 to 62.4 and 62.7, with pixel accuracy from 89.1% to 90.3% (Table 2); on VOC 2012 test FCN-8s reached 62.2 mean IoU, with inference under a fifth of a second per image (abstract and section 5).
U-Net: an encoder, a decoder and skip connections#
FCN adds a few scores from early layers. U-Net (Ronneberger, Fischer and Brox, 2015) gives the upsampling path as much capacity as the downsampling path and passes whole feature maps across. The encoder (the paper’s contracting path) repeats two convolutions with ReLU and a max pooling with stride 2, doubling the channels at each step, from 64 to 1024 over four poolings. The decoder (the expansive path) mirrors it: a up-convolution that doubles the resolution and halves the channels, a concatenation with the encoder’s feature map of the same resolution, and two convolutions. A final convolution maps each pixel’s 64 features to scores. The original uses unpadded convolutions, 23 convolutional layers in all, so a input tile gives a output, and large images are processed in overlapping tiles with the missing border context filled by mirroring (sections 1 and 2).
U-Net: an encoder, a decoder and skip connections
- Encoder: two convolutions, then max pooling halves the resolution and the next block doubles the channels.
- Bottleneck: on the coarsest map each unit sees most of the image, the context that decides what an object is.
- Decoder: a transposed convolution with stride 2 doubles the resolution. Its kernel size is a multiple of its stride, so it covers each output pixel exactly once and leaves no checkerboard.
- Skip connections: the encoder map of the same size is concatenated with the decoder map. It holds the exact positions of edges that pooling discarded.
- A convolution turns each pixel’s features into class logits.
The two paths answer the two halves of the baseline’s dilemma. The encoder supplies context, the skip connections supply localization, and the decoder learns to combine them. U-Net was designed for biomedical images with few labels, and its paper leans on data augmentation, elastic deformations above all, and on a loss weighted towards the thin borders between touching cells (section 3). On the PhC-U373 cell tracking data, with 35 partially annotated training images, it reached an average IoU of 92% against 83% for the second-best method, and on DIC-HeLa, with 20, 77.5% against 46% (section 4, Table 2).
The same shape turned out to fit any task whose output is an image aligned with the input. The noise predictor of a diffusion model is a U-Net with timestep embeddings and attention layers added (DDPM’s denoising network), and image-to-image GANs use it as the generator.
Dilated convolutions: context without downsampling#
The decoder recovers resolution after throwing it away. The alternative is to throw less away. A dilated (atrous) convolution with rate reads every -th input,
so a kernel with spans pixels with 9 weights, and a stack with rates grows its receptive field exponentially at constant resolution (Yu and Koltun, 2016).
DeepLab (Chen et al., 2018) uses this to change the output stride of a pretrained backbone, the ratio of the input size to the size of the final feature map. Take a stage that starts with a stride-2 layer. Set that stride to 1, and dilate every later convolution by 2 (by 4 after a second such stage). The receptive field of every later unit is unchanged: in the convolution note’s recursion , each layer now has half the jump and twice the dilation , so the product is the same. Nothing is retrained from scratch, since the weights are the same; only the map is denser. A classification ResNet has output stride 32; DeepLabv3 uses 16 for training and 8 or 16 at test time (Chen et al., 2017, sections 3.1 and 4.2).
Worked example. For a input, output stride 32 gives a map, 16 a map and 8 a map. In the last stage, a layer of the classification network at jump 32 and dilation 1 widens the receptive field by pixels, and the DeepLab layer at jump 16 and dilation 2 by as well, with four times as many output positions. The price is computation and memory: each halving of the output stride multiplies the cost of the dilated stages by 4.
To see objects at several scales, DeepLab adds atrous spatial pyramid pooling (ASPP): parallel convolutions with different rates on the same map. In DeepLabv3 at output stride 16 they are a convolution, three convolutions with , and image-level features, a global average pool broadcast back to the map; the five outputs are concatenated and mixed by a convolution. The image-level branch is needed because at large rates most taps of a kernel fall outside a small feature map, onto padding, and the kernel degenerates into a one (section 3.3). The logits are upsampled bilinearly to the image.
Dilated convolutions keep the resolution: DeepLab and ASPP
- A classification network halves the resolution five times: its last map is of the image.
- DeepLab drops the stride of the last stage and dilates its convolutions by 2: the same receptive field, at .
- ASPP looks at several scales at once with rates 6, 12 and 18, a convolution and image pooling.
- The branches are concatenated, a convolution gives scores, and bilinear upsampling returns to the image size.
DeepLabv2 reached 79.7% mean IoU on PASCAL VOC 2012 test, with a fully connected conditional random field to sharpen the boundaries (Chen et al., 2018, abstract); DeepLabv3 reached 85.7% without it, with a ResNet-101 pretrained on ImageNet and then on COCO (Chen et al., 2017, section 4.3). Later versions add a light decoder with one skip connection, combining both ideas.
Losses: per-pixel cross-entropy and Dice#
The standard loss is the cross-entropy at every pixel, averaged:
F.cross_entropy accepts logits of shape and labels of shape and does exactly this. Every pixel counts the same, so a class that covers 1% of the pixels contributes about 1% of the loss. Two common fixes weight the pixels: by inverse class frequency, or, as U-Net does, by a weight map that balances the classes () and adds weight near borders, where are the distances to the two nearest cells, and pixels (section 3).
The Dice coefficient measures overlap like IoU,
for a predicted mask and a true mask ; the second form follows from . It is the F1 score of the pixels. Replacing the masks by probabilities gives a differentiable soft Dice loss for a class,
with the predicted probability of the class at pixel ; it is computed per class and averaged over classes, usually with a small constant added to numerator and denominator so that a class absent from both prediction and truth gives 0 rather than . V-Net, which introduced it for volumetric medical images, used squares in the denominator, (Milletari, Navab and Ahmadi, 2016, section 3).
Worked example. A 4-pixel object; the background is predicted with certainty. A network that finds the object assigns it probability 0.99, one that misses it 0.01. In a 100-pixel image, the cross-entropy of the miss is and of the hit . In a 10,000-pixel image with the same object, the miss costs only : the cross-entropy of missing a small object shrinks with the image. The Dice loss does not: the hit gives and the miss , in both images, because Dice is a ratio of object-sized quantities. This is why Dice, alone or added to cross-entropy, is popular when the objects of interest are small, as in medical imaging.
The price is that the Dice loss is a ratio: its gradient for a pixel depends on all other pixels through the denominator, it is noisy when a class covers only a few pixels of a batch, and it does not give calibrated probabilities. Cross-entropy is smoother to optimize, so the sum of both is a common default.
Metrics: pixel accuracy, IoU and mIoU#
With the number of pixels of true class predicted as , and the number of pixels of class , FCN’s definitions (Long, Shelhamer and Darrell, 2015, section 5) are
The IoU of class is the IoU of the predicted and the true mask of that class: true positives, false positives and false negatives, so the denominator is . On a dataset the counts are summed over all images first and the IoU is computed once per class, so large images and frequent classes do not get extra votes per image; the mean IoU then gives every class the same weight.
Worked example. A map with background (22 pixels), an object of class 1 (9 pixels) and an object of class 2 (5 pixels). The prediction gets four pixels wrong: one background pixel called class 1, one class-1 pixel called background, one background pixel called class 2 and one class-2 pixel called background. Then
- class 0: , , , ;
- class 1: , , , ;
- class 2: , , , .
Pixel accuracy is , and . The same two errors per class cost the smallest object the most. A network that predicts background everywhere gets a pixel accuracy of and an mIoU of : pixel accuracy rewards the majority class, mIoU does not.
Pixel accuracy, IoU and mIoU on a 6 × 6 example
The size effect is general. If a disk of radius is predicted one pixel too small, its IoU is : for and for , while the pixel accuracy of the whole image barely moves. Boundaries are where segmentation networks make most of their errors, and mIoU charges those errors to small objects in full.
A one-pixel error at the boundary: IoU against pixel accuracy
An experiment: context and boundaries#
The Code section trains three small networks on synthetic images, each with one disk (class 1) and one square (class 2) of the same brightness under Gaussian noise of standard deviation 0.3; the square is drawn on top where they overlap. The two shapes can be told apart only by their outline, so a pixel’s class depends on context several pixels away. Background is 83.5% of the training pixels. Each network is trained on 640 images for 12 epochs with Adam and per-pixel cross-entropy and evaluated on 200 test images:
- a U-Net with two poolings, 8 to 32 channels, 29,659 parameters;
- the same network without skip connections, whose decoder sees only the bottleneck;
- a local network: four convolutions at full resolution, a receptive field, 7,299 parameters.
The boundary pixels, those whose label differs from one of their four neighbours, make up 11.5% of the test pixels.
| network | pixel accuracy | IoU background | IoU disk | IoU square | mIoU | boundary accuracy | interior accuracy |
|---|---|---|---|---|---|---|---|
| U-Net | 0.991 | 0.996 | 0.905 | 0.926 | 0.942 | 0.946 | 0.997 |
| no skips | 0.986 | 0.990 | 0.867 | 0.913 | 0.923 | 0.897 | 0.998 |
| local | 0.975 | 0.997 | 0.739 | 0.760 | 0.832 | 0.922 | 0.982 |
The two failures are different. The local network finds the shapes and their outlines, with the best background IoU, but inside a shape it often cannot tell which shape it is: its interior accuracy is the lowest and its disk and square IoUs are far below the others. The network without skips knows which shape it is looking at, with the best interior accuracy, but its boundaries come from an map and miss by a pixel: boundary accuracy 0.897 against 0.946. The U-Net has both. All pixel accuracies are above 0.97, while the mIoUs range from 0.832 to 0.942. With seeds 1 and 2 the U-Net reached mIoU 0.925 and 0.937 and boundary accuracy 0.936 and 0.950; the network without skips reached 0.919 and boundary accuracy 0.898 with one seed, and with the other failed to separate the classes in 12 epochs, mIoU 0.486. The local network stayed at about 0.84 with both.
Instances: Mask R-CNN#
Semantic segmentation cannot separate two touching objects of one class. Mask R-CNN (He et al., 2017) does so by adding a third output to the head of Faster R-CNN: for every proposal, besides the class and the box, a small fully convolutional branch predicts a mask for each of the classes. The loss adds a per-pixel binary cross-entropy on the mask of the proposal’s true class only, , so the classes do not compete for pixels; the classification head decides the class, and the mask branch only its shape (section 3).
Masks need precise alignment, and RoI pooling rounds the region’s coordinates to the feature grid twice, once for the region and once for its bins; at stride 16, a rounding error of half a cell is 8 pixels of the image. RoIAlign keeps the coordinates fractional and samples the feature map by bilinear interpolation. It raised the mask AP by about 3 points over RoI pooling, most of it at high IoU thresholds (section 3 and Table 2c). With a ResNet-101 feature pyramid, Mask R-CNN reached 35.7 mask AP on COCO test-dev at about 5 frames per second (Table 1). The mask is predicted inside the box at and resized to it, so its detail is limited by that grid.
What changed#
| Patch classifier per pixel | Segmentation network | |
|---|---|---|
| Computation | one forward pass per pixel | one pass per image, every layer convolutional |
| Context against localization | a fixed patch size trades one for the other | encoder for context; skip connections or dilation for localization |
| Upsampling | none needed | transposed convolutions or bilinear interpolation |
| Loss | cross-entropy per patch | per-pixel cross-entropy, often plus Dice for small classes |
| Score | accuracy | IoU per class and mIoU; PQ for panoptic |
| Instances | none | Mask R-CNN: a mask head on a detector |
Limitations#
- Labels are expensive. A pixel-accurate mask takes minutes per object to draw, so segmentation datasets are small, and the labels near boundaries are themselves uncertain by a pixel or two.
- Boundaries are the hard part. Most errors sit within a few pixels of an edge, and IoU charges them heavily on small objects; downsampling backbones lose exactly this information.
- Memory. Full-resolution feature maps are large: activations, not weights, limit the batch size, and high-resolution inputs are processed in tiles or crops.
- Class imbalance. Background and large stuff classes dominate the pixel count; without weighting or Dice, rare small classes are learned last or not at all.
- Semantic maps merge touching instances, and box-based instance methods inherit the limits of their detector.
What you should remember#
- Semantic segmentation labels every pixel with a class; instance segmentation gives each object its own mask; panoptic does both, with PQ as its metric.
- A fully connected layer on a map is a convolution; converting it makes a classifier fully convolutional, with a coarse score map at stride 32.
- U-Net: an encoder that pools and doubles channels, a decoder that upsamples and concatenates the encoder map of the same size, and a output convolution. Context comes from depth, localization from the skips.
- Dilation by with stride removed keeps the receptive field and multiplies the map’s resolution; DeepLab runs at output stride 16 or 8 and adds ASPP with rates 6, 12, 18.
- Losses: per-pixel cross-entropy, weighted for imbalance, and soft Dice , which does not shrink with the size of the image.
- per class, mIoU its mean over classes, Dice ; pixel accuracy is dominated by the majority class.
- Mask R-CNN adds a per-class mask head and RoIAlign to Faster R-CNN.
Code#
The metrics and losses of the worked examples, a check that a fully connected layer is a convolution, and the experiment of the note: three small networks trained on synthetic shapes on the CPU, with pixel accuracy, per-class IoU, mIoU and the accuracy at boundary and interior pixels. Seeds are fixed; exact numbers can differ slightly across platforms and library versions. The script runs in about 40 seconds on an otherwise idle laptop CPU, almost all of it training.
import time, torch
from torch import nn
import torch.nn.functional as F
t0 = time.time()
# 1. metrics on the worked example: 6 x 6 label maps, classes 0 (background), 1 and 2
truth = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 2], [0, 0, 0, 0, 2, 2], [0, 0, 0, 0, 2, 2]])
pred = torch.tensor([[0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 2, 2], [0, 0, 0, 2, 2, 2]])
def confusion(pred, truth, K=3):
"""C[i, j] = number of pixels of true class i predicted as class j."""
return torch.bincount(K * truth.flatten() + pred.flatten(), minlength=K * K).reshape(K, K)
def scores(C):
C = C.double()
tp = C.diag()
iou = tp / (C.sum(0) + C.sum(1) - tp) # TP / (TP + FP + FN) per class
return (tp.sum() / C.sum()).item(), iou, iou.mean().item()
C = confusion(pred, truth)
acc, iou, miou = scores(C)
print(C.tolist(), round(acc, 3), [round(v, 3) for v in iou.tolist()], round(miou, 3))
# [[20, 1, 1], [1, 8, 0], [1, 0, 4]] 0.889 [0.833, 0.8, 0.667] 0.767
print('Dice', [round(v, 3) for v in (2 * iou / (1 + iou)).tolist()]) # Dice [0.909, 0.889, 0.8]
acc0, iou0, miou0 = scores(confusion(torch.zeros_like(truth), truth))
print('all background:', round(acc0, 3), round(miou0, 3)) # all background: 0.611 0.204
# 2. losses for a 4-pixel object: cross-entropy averages over pixels, Dice is a ratio
def soft_dice_loss(p, g, eps=1e-6):
return 1 - (2 * (p * g).sum() + eps) / (p.sum() + g.sum() + eps)
for n in (100, 10_000):
g = torch.zeros(n); g[:4] = 1 # the object; background predicted with certainty (p = 0)
for name, q in (('hit', 0.99), ('miss', 0.01)):
p = torch.zeros(n); p[:4] = q
print(n, name, round(F.binary_cross_entropy(p, g).item(), 6), round(soft_dice_loss(p, g).item(), 4))
# 100 hit 0.000402 0.005 | 100 miss 0.184207 0.9802 | 10000 hit 4e-06 0.005 | 10000 miss 0.001842 0.9802
# 3. a fully connected layer on a 7 x 7 map is a 7 x 7 convolution, which also runs on larger maps
fc = nn.Linear(8 * 7 * 7, 5)
conv = nn.Conv2d(8, 5, 7)
conv.weight.data = fc.weight.data.view(5, 8, 7, 7); conv.bias.data = fc.bias.data
x = torch.randn(1, 8, 7, 7)
print((fc(x.flatten(1)) - conv(x).flatten(1)).abs().max().item() < 1e-5, conv(torch.randn(1, 8, 16, 16)).shape)
# True torch.Size([1, 5, 10, 10])
# 4. a tiny U-Net on synthetic shapes: one disk (class 1) and one square (class 2) of the same brightness, plus noise
def make_shapes(n, gen, size=32):
yy, xx = torch.meshgrid(torch.arange(size), torch.arange(size), indexing='ij')
X = torch.zeros(n, 1, size, size); Y = torch.zeros(n, size, size, dtype=torch.long)
for i in range(n):
r = torch.randint(4, 8, (1,), generator=gen).item()
cx, cy = torch.randint(r, size - r, (2,), generator=gen).tolist()
disk = (xx - cx) ** 2 + (yy - cy) ** 2 <= r * r
s = torch.randint(6, 13, (1,), generator=gen).item()
x0, y0 = torch.randint(0, size - s, (2,), generator=gen).tolist()
square = (xx >= x0) & (xx < x0 + s) & (yy >= y0) & (yy < y0 + s)
Y[i][disk] = 1; Y[i][square] = 2 # the square is drawn on top where they overlap
X[i, 0][disk | square] = 1.0
return X + 0.3 * torch.randn(X.shape, generator=gen), Y
g = torch.Generator().manual_seed(0)
Xtr, Ytr = make_shapes(640, g)
Xte, Yte = make_shapes(200, g)
print('class fractions', [round((Ytr == k).float().mean().item(), 3) for k in range(3)])
# class fractions [0.835, 0.082, 0.083]
def block(cin, cout):
return nn.Sequential(nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU(),
nn.Conv2d(cout, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU())
class UNet(nn.Module):
def __init__(self, K=3, c=8, skips=True):
super().__init__()
self.skips = skips
self.enc1, self.enc2, self.mid = block(1, c), block(c, 2 * c), block(2 * c, 4 * c)
self.up2 = nn.ConvTranspose2d(4 * c, 2 * c, 2, stride=2)
self.dec2 = block(4 * c if skips else 2 * c, 2 * c)
self.up1 = nn.ConvTranspose2d(2 * c, c, 2, stride=2)
self.dec1 = block(2 * c if skips else c, c)
self.head = nn.Conv2d(c, K, 1)
def forward(self, x):
e1 = self.enc1(x) # c x 32 x 32
e2 = self.enc2(F.max_pool2d(e1, 2)) # 2c x 16 x 16
m = self.mid(F.max_pool2d(e2, 2)) # 4c x 8 x 8
d2 = self.up2(m) # 2c x 16 x 16
d2 = self.dec2(torch.cat([d2, e2], 1) if self.skips else d2)
d1 = self.up1(d2) # c x 32 x 32
d1 = self.dec1(torch.cat([d1, e1], 1) if self.skips else d1)
return self.head(d1) # K x 32 x 32 logits
class Local(nn.Module):
"""Four 3 x 3 layers at full resolution: a 9 x 9 receptive field, too small to tell a disk from a square."""
def __init__(self, K=3, c=16):
super().__init__()
self.net = nn.Sequential(block(1, c), block(c, c), nn.Conv2d(c, K, 1))
def forward(self, x):
return self.net(x)
def train(model, epochs=12, seed=0):
torch.manual_seed(seed)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=4e-3, total_steps=epochs * 40)
for epoch in range(epochs):
model.train()
perm = torch.randperm(len(Xtr))
for i in range(0, len(Xtr), 16):
idx = perm[i:i + 16]
opt.zero_grad()
F.cross_entropy(model(Xtr[idx]), Ytr[idx]).backward() # per-pixel cross-entropy, averaged
opt.step(); sched.step()
model.eval()
with torch.no_grad():
return model(Xte).argmax(1)
# boundary pixels: the label differs from one of the four neighbours
edge = torch.zeros_like(Yte, dtype=torch.bool)
dv, dh = Yte[:, 1:, :] != Yte[:, :-1, :], Yte[:, :, 1:] != Yte[:, :, :-1]
edge[:, 1:, :] |= dv; edge[:, :-1, :] |= dv; edge[:, :, 1:] |= dh; edge[:, :, :-1] |= dh
print('boundary share', round(edge.float().mean().item(), 3)) # boundary share 0.115
print(' pixel acc IoU per class mIoU boundary acc interior acc params')
for name, make in (('U-Net', lambda: UNet()), ('no skips', lambda: UNet(skips=False)), ('local 9x9', lambda: Local())):
torch.manual_seed(0)
model = make()
P = train(model)
acc, iou, miou = scores(confusion(P, Yte))
print(f'{name:12} {acc:9.4f} {[round(v, 3) for v in iou.tolist()]} {miou:.3f} '
f'{(P[edge] == Yte[edge]).float().mean():12.3f} {(P[~edge] == Yte[~edge]).float().mean():12.3f} '
f'{sum(p.numel() for p in model.parameters()):6d}')
# pixel acc IoU per class mIoU boundary acc interior acc params
# U-Net 0.9912 [0.996, 0.905, 0.926] 0.942 0.946 0.997 29659
# no skips 0.9861 [0.99, 0.867, 0.913] 0.923 0.897 0.998 26779
# local 9x9 0.9752 [0.997, 0.739, 0.76] 0.832 0.922 0.982 7299
print(f'{time.time() - t0:.0f} s')
Next#
Every network so far learned from labels: a class per image, boxes, or a class per pixel, and a pixel-accurate label is the most expensive of them. The next note asks how much a network can learn from images alone, by solving tasks whose labels come for free, such as recognizing two augmented views of the same image, and how backbones pretrained that way transfer to classification, detection and segmentation.
References#
- J. Long, E. Shelhamer, T. Darrell. Fully convolutional networks for semantic segmentation. CVPR, 2015. Section 3 (convolutionalization, upsampling), section 4.2 and Table 2 (skip architectures), section 5 (metrics, results).
- O. Ronneberger, P. Fischer, T. Brox. U-Net: convolutional networks for biomedical image segmentation. MICCAI, 2015. Section 2 (architecture), section 3 (weighted loss, augmentation), section 4 and Table 2 (cell tracking results).
- D. C. Ciresan, L. M. Gambardella, A. Giusti, J. Schmidhuber. Deep neural networks segment neuronal membranes in electron microscopy images. NeurIPS, 2012.
- F. Yu, V. Koltun. Multi-scale context aggregation by dilated convolutions. ICLR, 2016.
- L.-C. Chen, G. Papandreou, I. Kokkinos, K. Murphy, A. L. Yuille. DeepLab: semantic image segmentation with deep convolutional nets, atrous convolution, and fully connected CRFs. IEEE Transactions on Pattern Analysis and Machine Intelligence, 40(4):834–848, 2018.
- L.-C. Chen, G. Papandreou, F. Schroff, H. Adam. Rethinking atrous convolution for semantic image segmentation. arXiv, 2017 (DeepLabv3). Section 3 (atrous convolution, output stride, ASPP with image-level features), section 4.3 (VOC 2012 test).
- F. Milletari, N. Navab, S.-A. Ahmadi. V-Net: fully convolutional neural networks for volumetric medical image segmentation. 3DV, 2016. Section 3 (the Dice loss).
- K. He, G. Gkioxari, P. Dollár, R. Girshick. Mask R-CNN. ICCV, 2017. Section 3 (mask head, RoIAlign), Tables 1 and 2c.
- A. Kirillov, K. He, R. Girshick, C. Rother, P. Dollár. Panoptic segmentation. CVPR, 2019. Section 4 (panoptic quality).
- A. Zhang, Z. C. Lipton, M. Li, A. J. Smola. Dive into Deep Learning. Cambridge University Press, 2023. Sections 14.9–14.11 (semantic segmentation, transposed convolution, fully convolutional networks).
- S. J. D. Prince. Understanding Deep Learning. MIT Press, 2023. Section 10.4.2 (upsampling), section 10.5.3 (semantic segmentation), section 11.5.3 (U-Net).
- I. Goodfellow, Y. Bengio, A. Courville. Deep Learning. MIT Press, 2016. Section 9.6 (structured outputs: pixel-wise labelling).
- Глубинное обучение 1 (Deep Learning 1), Faculty of Computer Science, HSE University. Course materials, repository xiyori/intro-to-dl-hse, branch 2025-2026: the lecture on computer vision tasks (segmentation metrics, FCN, U-Net, Mask R-CNN).