AI Logic

Architectures

Fully Convolutional Network (FCN)

Updated:

FCN architecture. Left: the overall flow of FCN-8s. On top of VGG-16's conv3/pool3 (1/8 of the image), conv4/pool4 (1/16), and conv5–conv7 (1/32), 1×1 convolutions output scores for 21 classes; the 1/32 scores are upsampled 2× and added to the pool4 scores, upsampled 2× again and added to the pool3 scores, then upsampled 8× into per-pixel predictions. FCN-32s and FCN-16s branch off along the way, with their mean IU (59.4, 62.4, 62.7). Right: a diagram of turning fully connected layers into convolutions, replacing the three fully connected layers of a classification network with a 7×7 convolution, a 1×1 convolution, and a 1×1 convolution for 21 classes, producing a class map from an input of any size. Below: the loss (sum of per-pixel cross-entropy)

Background and Overview

FCN (Fully Convolutional Network) is a method for semantic segmentation (the task of labeling each pixel of an image with the class of the object or region it shows) that replaces the fully connected layers of an image classification network with convolutions so it can produce location-wise predictions from images of any size, and then outputs per-pixel classes at the input size through in-network upsampling and a skip architecture that adds predictions from shallow layers. It was proposed by Long et al. at the University of California, Berkeley in 2015 (CVPR 2015).

There had been earlier work on segmentation with CNNs, but the common approach was a complex pipeline: train a small network on image patches, then layer on post-processing such as superpixels or conditional random fields. FCN simply recast AlexNet, VGG, and GoogLeNet, trained on ImageNet, into an "all-convolutional" form, fed in whole images, and fine-tuned on all-pixel ground truth, and that alone surpassed the previous best accuracy. According to the paper, this was the first work to train FCNs end to end for pixelwise prediction, starting from supervised pre-training.

The main results of the paper are:

  • It achieved 62.2% mean IU on the PASCAL VOC 2012 test set, a 20% relative improvement over the previous best (SDS at 51.6%).
  • Inference took about 175 ms per image, about 1/286 of SDS (about 50 seconds).
  • It also set new state-of-the-art results on NYUDv2 (indoor RGB-D images) and SIFT Flow (outdoor scenes).

FCN's design of "making a classification network fully convolutional and predicting per pixel" became the starting point for later segmentation networks such as U-Net and DeepLab v3.

The Problem: Per-Pixel Prediction with a Classification Network

The problem FCN solved is that strong CNNs trained for image classification could not be used as-is for per-pixel prediction.

Classification networks faced two obstacles.

  • Fully connected layers fix the input size and discard spatial information: For example, VGG-16's fully connected layers accept only 7×7×512 features, and the output is a single class for the whole image.
  • Downsampling makes the output coarse: Because pooling is stacked, the last layer has only 1/32 of the input resolution.

Earlier methods worked around this by cutting the image into patches and classifying them one at a time, or by passing shifted inputs through many times, but this repeated the same computation over heavily overlapping patches and was inefficient.

The paper points out that segmentation involves an inherent tension between "semantics (what)" and "location (where)." Global information decides "what," and local information decides "where." Deeper layers represent semantics but are coarse in location, while shallower layers are fine in location but weak in semantics. FCN uses a classification network for location-wise prediction by making it fully convolutional, and further combines deep and shallow layers to get both.

As an everyday analogy, a classification network is a worker who "looks at a photo and answers 'this is a photo of a cat.'" FCN has the same worker sweep over the photo in one pass and answer by location: "here is a cat, here is a sofa, here is the floor."

Theory: Make Everything Convolutional and Upsample Inside the Network

FCN replaces the fully connected layers of a classification network by viewing them as convolutions whose kernels cover the entire input, and restores the resulting coarse class map to pixel resolution with in-network upsampling. The right side of the figure at the top of the article shows the replacement of fully connected layers, and the left side shows the overall flow.

Convolution, pooling, and activation functions all look only at a local region of the input and depend only on relative position. Writing the vector at position (i,j)(i, j) of one layer as xij\mathbf{x}_{ij} and that of the next layer as yij\mathbf{y}_{ij}, all of them take the following form.

yij=fks({xsi+δi, sj+δj}0≤δi,δj≤k)\mathbf{y}_{ij} = f_{ks}\left(\{\mathbf{x}_{si + \delta i, \, sj + \delta j}\}_{0 \le \delta i, \delta j \le k}\right)

kk is the kernel size and ss is the stride. Stacking layers of this form yields another layer of the same form, by the following rule.

fks∘gk′s′=(f∘g)k′+(k−1)s′,  ss′f_{ks} \circ g_{k's'} = (f \circ g)_{k' + (k - 1)s', \; ss'}

The paper calls a network built only from layers of this form a "fully convolutional network (FCN)." An FCN works on inputs of any size and produces outputs of correspondingly sized spatial dimensions.

FCN-VGG16 is built as follows.

  1. Discard VGG-16's final classification layer (1000 classes).
  2. Replace the fully connected layers with convolutions. fc6 becomes a 7×7 convolution and fc7 a 1×1 convolution (4096 channels each), and the pre-trained weights can be used as they are.
  3. Add a 1×1 convolution that outputs scores for PASCAL VOC's 21 classes (including background).
  4. Upsample the coarse score map at 1/32 of the input to the input size with a transposed convolution (called deconvolution, a backwards convolution, in the paper).
  5. Apply softmax cross-entropy (a multinomial logistic loss in the paper) to the per-pixel scores and sum over all pixels to get the loss.

Upsampling as "backwards convolution": Upsampling by a factor ff can be viewed as convolution with an input stride of 1/f1/f. So upsampling is done with a transposed convolution whose output stride is ff. It can be implemented simply by swapping the forward and backward passes of convolution, and its weights can be learned. The weights can be fixed to bilinear interpolation (averaging the 4 nearest values weighted by distance) or initialized that way and then learned.

Feeding an entire image at once and summing the loss over all pixels is equivalent to "treating the receptive field of each output position (the region of the input that affects that output) as a patch, and putting all of those patches together into one mini-batch." Because the patches overlap heavily, computation on the overlapping parts is shared, which is far more efficient than patch-wise training. In the paper, AlexNet takes 1.2 ms to classify a single 227×227 image, but the fully convolutional version produces a 10×10 output from a 500×500 image in 22 ms, more than 5× faster than the naive patch-by-patch approach.

Skip Architecture: Combining the "What" of Deep Layers with the "Where" of Shallow Layers

An FCN that is simply made fully convolutional (FCN-32s) has a stride of 32 pixels at its final prediction layer, so the output is not fine enough and object boundaries become blurry. The paper therefore built a skip architecture that also makes predictions from shallow layers with finer strides, and upsamples the deep layers' predictions and adds them together. The left side of the figure at the top of the article shows this architecture.

  1. FCN-32s: Output scores for 21 classes on top of conv7 (the fully connected layer fc7 made convolutional, stride 32) and upsample 32×.
  2. FCN-16s: Add a 1×1 convolution on top of pool4 (stride 16) to output scores. Upsample the conv7 scores 2×, add them to the pool4 scores, and upsample 16×.
  3. FCN-8s: Upsample the summed scores from FCN-16s by another 2×, add them to the scores on top of pool3 (stride 8), and upsample 8×.

The paper's reasoning is that finer predictions need to look at fewer pixels, so producing them from shallow layers is sufficient. Combining coarse and fine layers enables local predictions that respect the global structure of the image.

Training proceeds from coarse to fine. FCN-16s starts from the weights of the trained FCN-32s, and the layer added to pool4 is initialized to zero so that it starts out predicting the same as FCN-32s. The learning rate is reduced to 1/100. The 2× upsampling is initialized to bilinear interpolation and learned. Summation is used for fusion (taking the max made learning difficult because the gradient's path switches).

Comparison of skip architectures (736 images from the PASCAL VOC 2011 validation set, %)

ModelPixel accuracyMean per-class accuracymean IUFrequency-weighted IU
FCN-32s (last layer only trained)83.059.745.472.0
FCN-32s89.173.359.481.4
FCN-16s90.075.762.483.0
FCN-8s90.375.962.783.2

FCN-16s raises mean IU by 3.0 points and also improves the fine shape of the output. FCN-8s improves it by only 0.3 points, showing diminishing returns, so the paper does not add any shallower layers. Comparisons such as predicting only from pool4, or lowering the learning rate without adding skips, improved neither accuracy nor output fineness.

As other ways to make the output finer, the paper also considered reducing the pooling stride and passing shifted inputs through many times and combining the outputs (shift-and-stitch). For the former, setting pool5's stride to 1 requires fc6's convolution to be 14×14 to preserve the receptive field, and such large filters were hard to learn. For the latter, limited experiments found it less cost-effective than the skip architecture.

Training Procedure and Evaluation Metrics

Training settings

  • Training uses SGD with momentum (0.9) and a mini-batch of 20 images. The learning rate is a fixed value chosen by line search: 10−310^{-3} for FCN-AlexNet, 10−410^{-4} for FCN-VGG16, and 5×10−55 \times 10^{-5} for FCN-GoogLeNet. Weight Decay is 5×10−45 \times 10^{-4} or 2×10−42 \times 10^{-4}, and the learning rate for biases is doubled. According to the paper, training was sensitive to the learning rate but not very sensitive to the other settings.
  • The class-scoring layers are initialized to zero. Random initialization changed neither accuracy nor convergence speed. The Dropout from the original classification network is kept.
  • All layers are fine-tuned. Training only the last layer gave only about 70% of the performance of full fine-tuning (45.4% vs. 59.4% in the table above).
  • On a single GPU, fine-tuning FCN-32s took 3 days, and upgrading to FCN-16s and FCN-8s took about 1 day each.
  • The final upsampling layer is fixed to bilinear interpolation, and the intermediate 2× upsampling layers are initialized to bilinear interpolation and learned.

The paper reports trying several training techniques and finding none of them necessary.

  • Using only some pixels in the loss (reproducing patch-wise training): Convergence speed was almost unchanged, and it took longer because each update needed more images.
  • Correcting class imbalance: About 3/4 of the ground truth is background, a mild imbalance, but correction was unnecessary.
  • Data augmentation: Random horizontal flips and translations of up to 32 pixels were tried, with no noticeable improvement.

In contrast, more training data had a large effect: going from PASCAL VOC 2011's 1112 images to 8498 images including extra annotations raised FCN-VGG16's mean IU by 3.4 points to 59.4%.

Evaluation metrics: Let nijn_{ij} be the number of pixels of class ii predicted as class jj, ncln_{cl} the number of classes, and ti=∑jnijt_i = \sum_j n_{ij} the total number of pixels of class ii. The paper's four metrics are:

pixel accuracy=∑inii∑iti,mean per-class accuracy=1ncl∑iniiti\text{pixel accuracy} = \frac{\sum_i n_{ii}}{\sum_i t_i}, \qquad \text{mean per-class accuracy} = \frac{1}{n_{cl}} \sum_i \frac{n_{ii}}{t_i} mean IU=1ncl∑iniiti+∑jnji−nii,frequency-weighted IU=1∑ktk∑iti niiti+∑jnji−nii\text{mean IU} = \frac{1}{n_{cl}} \sum_i \frac{n_{ii}}{t_i + \sum_j n_{ji} - n_{ii}}, \qquad \text{frequency-weighted IU} = \frac{1}{\sum_k t_k} \sum_i \frac{t_i \, n_{ii}}{t_i + \sum_j n_{ji} - n_{ii}}

mean IU divides, for each class, the "correctly predicted pixels" by the "pixels in the union of ground truth and prediction," then averages over classes; today it is usually called mIoU.

Experimental Results

Comparison of classification networks (PASCAL VOC 2011 validation set, 500×500 input, NVIDIA Tesla K40c)

FCN-AlexNetFCN-VGG16FCN-GoogLeNet
mean IU39.856.042.5
Inference time50 ms210 ms59 ms
Convolutional layers81622
Parameters57M134M6M
Receptive field size of the output355404907
Maximum stride323232

Although their classification accuracy is similar, the paper's reimplementation of GoogLeNet did not reach VGG-16's segmentation accuracy (the paper's GoogLeNet was trained with less data augmentation than the original paper, with 88.4% ImageNet top-5 accuracy). The remaining experiments are based on VGG-16.

PASCAL VOC test (mean IU %)

MethodVOC 2011 testVOC 2012 testInference time
R-CNN47.9――
SDS52.651.6About 50 s
FCN-8s62.762.2About 175 ms

SDS classifies based on R-CNN's region proposals. FCN-8s improves mean IU by 20% relative, and cuts inference time to 1/114 for the CNN part alone and 1/286 overall.

On NYUDv2 (1449 indoor RGB-D images, 40 classes), an FCN-16s trained by summing, at the final layer, the predictions of two FCNs, one on RGB and one on depth information (a 3D encoding called HHA), reached 34.0% mean IU (previous methods: 28.6%). On SIFT Flow (2688 images, 33 semantic classes and 3 geometric classes), a two-headed FCN-16s achieved 85.2% pixel accuracy on the semantic classes and 94.3% on the geometric classes, matching the accuracy of models trained separately for each, in roughly the time of one.

Practical Considerations

Keep the following points in mind when using FCN.

  • Weak on fine structures: Even FCN-8s upsamples 8× at the end, so thin objects and object boundaries tend to blur. The paper also reports diminishing returns from adding shallower layers. For tasks where boundary accuracy matters, also consider U-Net, which concatenates features from each encoder stage and upsamples step by step, or the DeepLab family, which preserves resolution with dilated convolutions.
  • The amount of training data matters: In the paper, increasing the training data from 1112 to 8498 images raised mean IU by 3.4 points.
  • Handling input size: FCN accepts inputs of any size, but because it downsamples with pooling and then upsamples, the output can be misaligned for some input sizes. Make the output match the input size with tricks such as making the input height and width multiples of 32, or padding and cropping at the end.
  • Overlap in evaluation data: According to a footnote in the paper, the extra training data included images from the VOC 2011 validation set, so validation was redone on 736 non-overlapping images. The paper notes that earlier versions evaluated on the full validation set.

torchvision's fcn_resnet50 and fcn_resnet101 are not the paper's VGG-16 FCN-8s but an improved version that uses dilated convolutions in ResNet's later stages to limit downsampling to 1/8, upsamples with bilinear interpolation at the end instead of a skip architecture, and has an auxiliary output (aux). They cannot be compared directly with the paper's numbers. The output is a dictionary, and the main prediction is in out. In both cases num_classes includes the background (21 for PASCAL VOC), and "ignore" pixels such as ground-truth boundaries (255 in VOC) should be set as ignore_index in the loss.

Comparison with Other Methods

FCN is the basic form of segmentation, recasting a classification network for per-pixel prediction. Lined up by how they make the output finer, the methods compare as follows.

MethodHow the output is made finerHow shallow-layer features are usedMain strengths and weaknesses
Patch-wise classification (pre-FCN)Crop a patch around each pixel and classify it―Repeats overlapping computation many times; slow
shift-and-stitchPass shifted inputs through many times and combine the outputs―Cannot use fine information. In the FCN paper, less cost-effective than the skip architecture
FCN-8sUpsample with transposed convolutions and add shallow-layer predictionsAdd class scores on top of pool3 and pool4Simple and fast. Boundaries tend to blur
U-NetA decoder that upsamples stage by stageConcatenate features from each encoder stageFine boundaries. Easy to train even with little data
DeepLab v3Reduce downsampling with dilated convolutions― (v3+ adds a decoder)Keeps resolution while preserving the receptive field. Computationally heavier

For instance segmentation, which separates individual objects, Mask R-CNN, which adds a mask branch to a detector, is the representative method. Mask R-CNN's mask branch also uses a small FCN inside each candidate region to predict per pixel.

Guidelines for choosing:

  • Learning how segmentation works, or building a quick baseline: FCN has a simple structure and can be built from a pre-trained classification network.
  • Fine boundaries matter (e.g., medical images): A decoder like U-Net's, which concatenates shallow-layer features stage by stage, is a good fit.
  • Large images where global context should also be used: The DeepLab family is a good fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
from torchvision.models import vgg16, VGG16_Weights

'''
A small implementation of FCN-8s (VGG-16) following Sections 4.1 and 4.2 of the paper.
For simplicity, input height and width are multiples of 32, and padding 3 is added to fc6's 7×7 convolution to keep sizes aligned
'''


def bilinear_kernel(channels, kernel_size):
  '''Weights that initialize a transposed convolution to bilinear interpolation (same shape for each channel)'''
  factor = (kernel_size + 1) // 2
  center = factor - 1 if kernel_size % 2 == 1 else factor - 0.5
  og = torch.arange(kernel_size, dtype=torch.float32)
  f = 1 - (og - center).abs() / factor
  weight = torch.zeros(channels, channels, kernel_size, kernel_size)
  weight[range(channels), range(channels)] = f[:, None] * f[None, :]
  return weight


class FCN8s(nn.Module):
  def __init__(self, num_classes=21):
    super().__init__()
    vgg = vgg16(weights=VGG16_Weights.IMAGENET1K_V1)
    self.to_pool3 = vgg.features[:17]          # conv1–conv3, pool3 (1/8)
    self.to_pool4 = vgg.features[17:24]        # conv4, pool4 (1/16)
    self.to_pool5 = vgg.features[24:]          # conv5, pool5 (1/32)

    # Turn fully connected layers fc6 and fc7 into convolutions, reusing the pre-trained weights with only their shape changed
    fc6, fc7 = vgg.classifier[0], vgg.classifier[3]
    self.fc6 = nn.Conv2d(512, 4096, 7, padding=3)
    self.fc6.weight.data.copy_(fc6.weight.data.view(4096, 512, 7, 7))
    self.fc6.bias.data.copy_(fc6.bias.data)
    self.fc7 = nn.Conv2d(4096, 4096, 1)
    self.fc7.weight.data.copy_(fc7.weight.data.view(4096, 4096, 1, 1))
    self.fc7.bias.data.copy_(fc7.bias.data)
    self.drop = nn.Dropout2d(0.5)              # Keep the Dropout from the original classification network

    # 1×1 convolutions that output scores for 21 classes, all initialized to zero
    self.score_fr = nn.Conv2d(4096, num_classes, 1)
    self.score_pool4 = nn.Conv2d(512, num_classes, 1)
    self.score_pool3 = nn.Conv2d(256, num_classes, 1)
    for layer in (self.score_fr, self.score_pool4, self.score_pool3):
      nn.init.zeros_(layer.weight)
      nn.init.zeros_(layer.bias)

    # 2× upsampling is initialized to bilinear interpolation and learned; the final 8× is fixed to bilinear interpolation
    self.up2_a = nn.ConvTranspose2d(num_classes, num_classes, 4, stride=2, padding=1, bias=False)
    self.up2_b = nn.ConvTranspose2d(num_classes, num_classes, 4, stride=2, padding=1, bias=False)
    self.up8 = nn.ConvTranspose2d(num_classes, num_classes, 16, stride=8, padding=4, bias=False)
    for up in (self.up2_a, self.up2_b, self.up8):
      up.weight.data.copy_(bilinear_kernel(num_classes, up.kernel_size[0]))
    self.up8.weight.requires_grad_(False)

  def forward(self, x):                        # x: (N, 3, H, W), H and W are multiples of 32
    pool3 = self.to_pool3(x)
    pool4 = self.to_pool4(pool3)
    h = self.to_pool5(pool4)
    h = self.drop(torch.relu(self.fc6(h)))
    h = self.drop(torch.relu(self.fc7(h)))
    h = self.up2_a(self.score_fr(h)) + self.score_pool4(pool4)    # Upsample 1/32 by 2× and add pool4 (FCN-16s)
    h = self.up2_b(h) + self.score_pool3(pool3)                    # Upsample 2× again and add pool3 (FCN-8s)
    return self.up8(h)                         # (N, 21, H, W): per-pixel scores


model = FCN8s(num_classes=21)
criterion = nn.CrossEntropyLoss(ignore_index=255)   # Per-pixel cross-entropy, ignoring VOC boundaries (255)
# The paper's FCN-VGG16 settings: fixed learning rate 1e-4, momentum 0.9, Weight Decay 5e-4, mini-batch of 20 images
# (The paper does not say whether the loss is averaged or summed over pixels; here it is averaged)
optimizer = torch.optim.SGD([p for p in model.parameters() if p.requires_grad],
                            lr=1e-4, momentum=0.9, weight_decay=5e-4)

# Example of one step (data loading omitted)
images = torch.randn(2, 3, 320, 480)
masks = torch.randint(0, 21, (2, 320, 480))
model.train()                                  # Dropout is active
loss = criterion(model(images), masks)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                   # Disable Dropout
with torch.no_grad():
  pred = model(images).argmax(1)               # (N, H, W): per-pixel classes

# torchvision's pre-trained FCN (an improved version with ResNet-50 and dilated convolutions; output is a dict, main output in 'out')
from torchvision.models.segmentation import fcn_resnet50, FCN_ResNet50_Weights
tv_model = fcn_resnet50(weights=FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1).eval()
with torch.no_grad():
  out = tv_model(images)['out']                # (N, 21, H, W)

FAQ

Q. What does "fully convolutional" mean?
A.

It means every layer of the network is a layer that "looks only at a local region of the input and depends only on relative position," like convolution, pooling, and activation functions. Because there are no fully connected layers, the input size is not fixed, and the network can output predictions sized to the input (location-wise predictions). The fully connected layers of a classification network can also be replaced, keeping their pre-trained weights, by viewing them as convolutions whose kernels cover the entire input (7×7 for VGG-16's fc6).

Q. What are the differences between FCN-32s, FCN-16s, and FCN-8s?
A.

They differ in the stride of the final prediction (how many pixels apart predictions are made). FCN-32s simply upsamples the 1/32 prediction 32×, FCN-16s adds the prediction from pool4 (1/16), and FCN-8s additionally adds the prediction from pool3 (1/8) before upsampling. Their mean IU on the paper's validation set was 59.4%, 62.4%, and 62.7%.

Q. What is the "deconvolution" FCN uses for upsampling?
A.

A layer now usually called a transposed convolution, which swaps the forward and backward passes of convolution. A transposed convolution with stride ff acts as upsampling that enlarges the input ff times. In FCN, its weights are initialized to bilinear interpolation; the intermediate 2× upsampling is learned, and the final upsampling stays fixed to bilinear interpolation. It is different from "deconvolution" in the sense of undoing a convolution with an inverse.

References

  1. Long, J., Shelhamer, E., & Darrell, T. (2015). Fully Convolutional Networks for Semantic Segmentation. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 3431–3440. arXiv:1411.4038.
  2. Shelhamer, E., Long, J., & Darrell, T. (2017). Fully Convolutional Networks for Semantic Segmentation. IEEE Transactions on Pattern Analysis and Machine Intelligence, 39(4), 640–651. arXiv:1605.06211.
  3. PyTorch. torchvision.models.segmentation.fcn_resnet50.