DropConnect is a regularization method that curbs overfitting by randomly setting the weights (connections) of a fully connected layer to 0 during training. It was presented at ICML 2013 by Wan et al.
Dropout randomly sets the outputs (units) of a layer to 0. When a unit is dropped, none of the weights leaving that unit are used. DropConnect refines the unit of dropping from units to individual weights. Every unit remains, but each receives input only from a randomly selected subset of the units in the previous layer. The paper positions DropConnect as "a generalization of Dropout to the entire connectivity structure of a layer."
As an analogy, Dropout is like "some members missing each meeting," while DropConnect is like "everyone attending, but some of the communication channels between members being cut at random."
Like Dropout, the paper treats DropConnect as a method for fully connected layers only. In the experiments, it was applied to the fully connected layer following convolutional feature extraction and evaluated on image classification with MNIST, CIFAR-10, SVHN, and NORB.
Theory (training and inference)
The explanation follows the equations in Sections 2 and 3 of the paper. With input v (n-dimensional), weights W (d×n), and activation function a, the output of an ordinary fully connected layer is as follows (the bias is folded into W by appending an input with value 1).
r=a(u)=a(Wv)
Dropout drops output units (⋆ is the element-wise product and p is the keep probability).
r=m⋆a(Wv),mj∼Bernoulli(p)
DropConnect drops weights one by one with a mask M of the same shape as the weight matrix. One training step proceeds as follows.
Compute the features v=g(x;Wg) with the preceding layers (convolutional layers in the paper).
For each element of the weights and biases, decide whether to keep it with probability p. The mask is resampled for each training example.
Mij∼Bernoulli(p)
Compute the output with the dropped weights.
r=a((M⋆W)v)
Produce the prediction o with a softmax layer and compute the cross-entropy loss.
Update the weights with backpropagation. In the DropConnect layer, the mask is also applied to the gradient, so only the weights used in the forward pass are updated.
W←W−η(M⋆∇WA)
When the activation function satisfies a(0)=0 (as tanh and ReLU do), Dropout is the special case of "zeroing entire rows of M." Dropping output unit j is the same as dropping all weights entering that unit (row j of W). DropConnect removes this row structure and drops weights individually.
At inference, the ideal would be to average the output over all possible masks, but there are 2∣M∣ masks, which is intractable. Dropout uses the approximation of "averaging before the activation function" (scaling the weights by p), but the paper points out that this is not mathematically correct for functions such as ReLU. For example, if u follows a standard normal distribution and a(u)=max(u,0), then a(E[u])=0 but E[a(u)]=1/2π≈0.4.
DropConnect therefore approximates the pre-activation value ui=∑jWijvjMij with a Gaussian of the same mean and variance (moment matching).
EM[u]=pWv,VM[u]=p(1−p)(W⋆W)(v⋆v)
Z values are drawn from this Gaussian, each is passed through the activation function, and the average is passed to the next layer. The paper's experiments use Z=1000.
Why it curbs overfitting
The paper explains why DropConnect works from two perspectives.
It averages over many networks: Each mask M defines a network with a different connectivity. The output of DropConnect can be viewed as the average of the outputs of 2∣M∣ networks, weighted by the mask probabilities (a mixture model). While sharing weights, a different network is trained each time, which prevents any single network from memorizing the training data.
Model complexity shrinks in proportion to p: The paper derives an upper bound on the model's complexity on the training data (Rademacher complexity) and shows that it is linear in the keep probability p. With p=0 the input has no effect on the output, so the complexity is 0; with p=1 it equals that of the ordinary model. The same bound applies to Dropout as well.
The difference from Dropout is the granularity of dropping. In Dropout, dropping one unit removes all weights connected to it at once. DropConnect drops each weight independently, so there are far more possible mask combinations.
Experimental results
Comparison from the original paper of using nothing in the fully connected layer (none), Dropout, and DropConnect. Values are test error rates (%, lower is better), averaged over 5 independently trained single models, with p=0.5.
Dataset
Setting
None
Dropout
DropConnect
MNIST
2 fully connected layers (800 units each), ReLU
1.62
1.28
1.20
MNIST
Same, sigmoid
1.78
1.38
1.55
MNIST
Same, tanh
1.65
1.58
1.36
CIFAR-10
Small CNN + 64-unit fully connected layer
23.5
19.7
18.7
CIFAR-10
Large CNN + 128-unit fully connected layer
11.18
11.52
11.10
SVHN
Same feature extractor + 512-unit fully connected layer
2.26
2.25
2.23
NORB
Same feature extractor + 512-unit fully connected layer
4.48
3.96
4.14
(Only the CIFAR-10 small-network row is the value of a single model.)
Often equal to or slightly better than Dropout: DropConnect was best for MNIST with ReLU and tanh and for CIFAR-10, while Dropout was better for MNIST with sigmoid and for NORB. Which one wins depends on the data and model.
The gap is small with lots of training data: On SVHN (about 600,000 training images), all three were almost the same. The paper attributes this to the large amount of training data.
Averaging multiple models helps further: Averaging the outputs of 5 models reduced the error of the large CIFAR-10 network to 9.41% (10.22% for none, 9.83% for Dropout), surpassing the state of the art at the time.
A keep probability around 0.5 works well: In MNIST experiments varying p, both Dropout and DropConnect performed best around 0.5. Inference by Gaussian sampling also beat scaling the weights by p, but this benefit appeared only for DropConnect.
Practical considerations
The mask must be resampled for each training example, which uses a lot of memory. According to the paper, sharing one mask across the whole mini-batch (128 examples) did not regularize enough. With a mask per example, however, the mask size becomes "number of weights × batch size." For a 4096 × 4096 fully connected layer and a batch size of 128, storing the masks as floating-point numbers takes 8 GB. The paper kept this to 256 MB with a dedicated GPU implementation that stores each mask entry as a single bit.
Use it for fully connected layers: Like Dropout, the paper presents it as suited only to fully connected layers. For convolutional layers, Spatial Dropout and DropBlock are used.
Do not apply it to the output (softmax) layer weights: In the paper's models, DropConnect is applied to the fully connected layer between feature extraction and the softmax layer.
Training becomes slower: In the MNIST experiments, the model without regularization overfit quickly, while Dropout and DropConnect converged slowly. DropConnect converged even more slowly than Dropout but reached a lower final test error. Plan for more training epochs.
Decide on the inference method: Inference as in the paper draws Z samples from a Gaussian per unit, which increases inference cost. If convenience matters, scaling the weights by p as in Dropout (the mean approximation) can also be used, but in the paper's MNIST experiments sampling gave better results for DropConnect.
PyTorch has no built-in layer: torch.nn has no DropConnect layer, so write it yourself as in the code example below.
Comparison with other methods
Dropout and three of its variants, compared from the same perspectives.
(In every case p is the keep probability. PyTorch's Dropout-family layers are implemented by scaling by 1/(1−pdrop) during training and doing nothing at inference.)
For regularizing fully connected layers, a practical approach is to start with the simple Dropout and try DropConnect when more accuracy is needed. DropConnect costs more memory and computation because of the per-example masks.
In convolutional layers, neighboring pixels have similar values, so neither Dropout nor DropConnect works well. Choose Spatial Dropout or DropBlock, which drop channels or regions as a whole.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
class DropConnectLinear(nn.Module):
"""DropConnect layer from the paper: r = a((M ⋆ W) v). The activation function a is included in the layer.
keep_prob is the probability p of keeping a weight (same as the paper; the opposite of p in PyTorch's Dropout).
"""
def __init__(self, in_features, out_features, keep_prob=0.5, num_samples=1000):
super().__init__()
self.linear = nn.Linear(in_features, out_features)
self.p = keep_prob
self.num_samples = num_samples # Number of Gaussian samples Z at inference
def forward(self, v): # v: (batch, in_features)
W, b = self.linear.weight, self.linear.bias # W: (out_features, in_features)
if self.training:
# Training: create weight and bias masks for each example
M = torch.bernoulli(torch.full((v.size(0), *W.shape), self.p, device=v.device))
m_b = torch.bernoulli(torch.full((v.size(0), b.numel()), self.p, device=v.device))
u = torch.einsum("bdn,bn->bd", M * W, v) + m_b * b
return F.relu(u)
# Inference: approximate u with a Gaussian (moment matching), draw Z samples, and average a(u)
mean = self.p * (v @ W.t() + b) # E[u] = pWv
var = self.p * (1 - self.p) * ((v ** 2) @ (W ** 2).t() + b ** 2) # V[u] = p(1−p)(W⋆W)(v⋆v)
eps = torch.randn(self.num_samples, *mean.shape, device=v.device)
u = mean + var.sqrt() * eps
return F.relu(u).mean(dim=0)
# Model: convolutional feature extractor, DropConnect fully connected layer, then softmax layer (no dropping)
class Net(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(),
)
self.dropconnect = DropConnectLinear(64 * 4 * 4, 150, keep_prob=0.5)
self.classifier = nn.Linear(150, num_classes)
def forward(self, x):
return self.classifier(self.dropconnect(self.features(x)))
model = Net()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
criterion = nn.CrossEntropyLoss()
# Training: model.train() drops weights at random
model.train()
images = torch.randn(32, 1, 28, 28) # Dummy mini-batch shaped like MNIST
labels = torch.randint(0, 10, (32,))
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward() # Gradients of dropped weights are 0, so only the used weights are updated
optimizer.step()
# Inference: model.eval() switches to inference by Gaussian sampling
model.eval()
with torch.no_grad():
predicted = model(images).argmax(dim=1)
FAQ
Q. Should I use Dropout or DropConnect?
A.
Dropout is the easy first choice: it is built into PyTorch and adds no memory. In the original paper's experiments, DropConnect was equal to or slightly better than Dropout in many settings, but Dropout was better for MNIST with sigmoid and for NORB, so which one wins depends on the data and model. Try DropConnect when overfitting in fully connected layers is noticeable and there is memory and compute to spare.
Q. How do I use DropConnect in PyTorch?
A.
torch.nn has no DropConnect layer, so write it yourself. As in the code example, during training create a mask of the same shape as the weights for each example with torch.bernoulli and multiply it into the weights; at inference, draw several values from the Gaussian approximation and average them. Creating a mask per example increases memory, so watch the batch size when the fully connected layer is large.
Q. Is it enough to just scale the weights by p at inference?
A.
It can be used, but accuracy may be lower than with the paper's method. Scaling the weights by p is an approximation that averages before the activation function, and for functions like ReLU it deviates from the average taken after the activation. In the original paper's MNIST experiments, inference by Gaussian sampling gave better results for DropConnect. When inference speed matters, check the accuracy gap against the p-scaling method on validation data before choosing.