AI Logic

Regularization

DropConnect

Updated:

Dropout vs. DropConnect. Dropout (left) drops units at random, and all lines connected to a dropped unit disappear; at inference the weights are scaled by p. DropConnect (right) keeps every unit and drops weights (connections) one by one at random (dashed lines); at inference the input to each unit is approximated by a Gaussian, Z samples are drawn, passed through the activation function, and averaged

Background and overview

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\boldsymbol{v} (nn-dimensional), weights WW (d×nd \times n), and activation function aa, the output of an ordinary fully connected layer is as follows (the bias is folded into WW by appending an input with value 1).

r=a(u)=a(Wv)\boldsymbol{r} = a(\boldsymbol{u}) = a(W\boldsymbol{v})

Dropout drops output units (⋆\star is the element-wise product and pp is the keep probability).

r=m⋆a(Wv),mj∼Bernoulli(p)\boldsymbol{r} = \boldsymbol{m} \star a(W\boldsymbol{v}), \qquad m_j \sim \mathrm{Bernoulli}(p)

DropConnect drops weights one by one with a mask MM of the same shape as the weight matrix. One training step proceeds as follows.

  1. Compute the features v=g(x;Wg)\boldsymbol{v} = g(\boldsymbol{x}; W_g) with the preceding layers (convolutional layers in the paper).
  2. For each element of the weights and biases, decide whether to keep it with probability pp. The mask is resampled for each training example. Mij∼Bernoulli(p)M_{ij} \sim \mathrm{Bernoulli}(p)
  3. Compute the output with the dropped weights. r=a((M⋆W) v)\boldsymbol{r} = a\big((M \star W)\,\boldsymbol{v}\big)
  4. Produce the prediction o\boldsymbol{o} with a softmax layer and compute the cross-entropy loss.
  5. 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)W \leftarrow W - \eta\,(M \star \nabla_W A)

When the activation function satisfies a(0)=0a(0) = 0 (as tanh and ReLU do), Dropout is the special case of "zeroing entire rows of MM." Dropping output unit jj is the same as dropping all weights entering that unit (row jj of WW). 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∣2^{|M|} masks, which is intractable. Dropout uses the approximation of "averaging before the activation function" (scaling the weights by pp), but the paper points out that this is not mathematically correct for functions such as ReLU. For example, if uu follows a standard normal distribution and a(u)=max⁡(u,0)a(u) = \max(u, 0), then a(E[u])=0a(\mathbb{E}[u]) = 0 but E[a(u)]=1/2π≈0.4\mathbb{E}[a(u)] = 1/\sqrt{2\pi} \approx 0.4.

DropConnect therefore approximates the pre-activation value ui=∑jWijvjMiju_i = \sum_j W_{ij} v_j M_{ij} with a Gaussian of the same mean and variance (moment matching).

EM[u]=p Wv,VM[u]=p(1−p) (W⋆W)(v⋆v)\mathbb{E}_M[\boldsymbol{u}] = p\,W\boldsymbol{v}, \qquad \mathbb{V}_M[\boldsymbol{u}] = p(1-p)\,(W \star W)(\boldsymbol{v} \star \boldsymbol{v})

ZZ 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=1000Z = 1000.

Why it curbs overfitting

The paper explains why DropConnect works from two perspectives.

  • It averages over many networks: Each mask MM defines a network with a different connectivity. The output of DropConnect can be viewed as the average of the outputs of 2∣M∣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 pp: 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 pp. With p=0p = 0 the input has no effect on the output, so the complexity is 0; with p=1p = 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.5p = 0.5.

DatasetSettingNoneDropoutDropConnect
MNIST2 fully connected layers (800 units each), ReLU1.621.281.20
MNISTSame, sigmoid1.781.381.55
MNISTSame, tanh1.651.581.36
CIFAR-10Small CNN + 64-unit fully connected layer23.519.718.7
CIFAR-10Large CNN + 128-unit fully connected layer11.1811.5211.10
SVHNSame feature extractor + 512-unit fully connected layer2.262.252.23
NORBSame feature extractor + 512-unit fully connected layer4.483.964.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 pp, both Dropout and DropConnect performed best around 0.5. Inference by Gaussian sampling also beat scaling the weights by pp, 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 ZZ samples from a Gaussian per unit, which increases inference cost. If convenience matters, scaling the weights by pp 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.

MethodWhat is droppedNumber of keep/drop decisions per sampleTypical layersAt inference
DropoutUnits (output elements), one at a timeNumber of unitsFully connected layersUse all, scale weights by pp
DropConnectWeights (connections), one at a timeNumber of weights (inputs × outputs)Fully connected layersApproximate with a Gaussian and average samples
Spatial DropoutWhole feature-map channelsNumber of channelsConvolutional layersUse all, scale by pp (same as Dropout)
DropBlockSquare regions of the feature mapNumber of pixels (pick seeds, expand to blocks)Convolutional layersDo nothing (magnitude normalized during training)

(In every case pp is the keep probability. PyTorch's Dropout-family layers are implemented by scaling by 1/(1−pdrop)1/(1-p_{\text{drop}}) 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.

References

  1. L. Wan, M. Zeiler, S. Zhang, Y. LeCun, and R. Fergus, "Regularization of Neural Networks using DropConnect," Proceedings of the 30th International Conference on Machine Learning (ICML), PMLR 28(3), 2013.
  2. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, "Dropout: A Simple Way to Prevent Neural Networks from Overfitting," Journal of Machine Learning Research, 15(56), 1929–1958, 2014.
  3. G. E. Hinton, N. Srivastava, A. Krizhevsky, I. Sutskever, and R. R. Salakhutdinov, "Improving neural networks by preventing co-adaptation of feature detectors," arXiv:1207.0580, 2012.