AI Logic

Architectures

Two-Stream ConvNets

Updated:

Architecture of Two-Stream ConvNets. Left: the overall flow (a single RGB frame goes into the 2D CNN of the spatial stream and 10 optical-flow pairs into the 2D CNN of the temporal stream, and the two scores are fused late by averaging or an SVM). Right: how the temporal-stream input is built (flow computed from consecutive frames is split into horizontal and vertical components and stacked into 2L channels).

Background and Overview

Two-Stream ConvNets (two-stream convolutional networks) is an action recognition model that splits a video into two parts, "the appearance of a single frame" and "the motion between frames (optical flow)", classifies each with a separate CNN, and combines the scores at the end. It was presented at NIPS 2014 by Simonyan and Zisserman of the University of Oxford.

At the time, feeding video directly into a CNN (stacking many frames as input) lagged far behind hand-crafted features (such as improved dense trajectories, IDT). In prior work, a network that saw only a single frame and one that saw stacked frames had almost the same accuracy, suggesting that motion was possibly not being learned.

Two-Stream ConvNets answered this with two ideas.

  • Pass motion as input instead of having the network estimate it: The temporal stream receives a stack of 10 consecutive optical-flow pairs. Because motion is explicit in the input, the network does not have to learn motion estimation.
  • Learn appearance and motion separately: The spatial stream has the same form as image classification, so weights pretrained on ImageNet can be used. Even with little video data, appearance recognition can be borrowed from images.

The main results of the paper are as follows.

  • It reached 88.0% on UCF-101 and 59.4% on HMDB-51 (averaged over 3 splits), on par with the best hand-crafted-feature methods of the time.
  • It greatly outperformed prior deep learning work (Slow Fusion, which stacks frames as input: 65.4% on UCF-101).

This "two streams of RGB and optical flow" design was inherited by later models such as TSN and I3D, and was widely used as a baseline model and as features on video datasets such as Kinetics and ActivityNet.

Theory: Classifying Appearance and Motion with Separate CNNs

Two-Stream ConvNets consists of two 2D CNNs of the same shape placed side by side (left of the figure at the top of the article). There are no intermediate connections between the two streams; only the final scores are combined.

Overall procedure

  1. Spatial stream: A single frame (RGB, 224 × 224) is taken from the video, and a CNN outputs class scores (softmax).
  2. Temporal stream: A stack of LL consecutive optical-flow pairs starting at the same time (224 × 224 × 2L2L) is fed into another CNN to obtain scores. The paper uses L=10L = 10.
  3. Late fusion: The two softmax scores are averaged, or the L2-normalized scores are concatenated and classified with a linear SVM.
  4. Testing: 25 frames are selected at equal intervals from the video, 10 inputs are made from each (the 4 corner crops, the center crop, and their horizontal flips), and all scores are averaged.

Temporal-stream input (stacked optical flow)

The optical flow dtd_t is a field of displacement vectors indicating where each pixel of frame tt moves in the next frame t+1t+1. Its horizontal component dtxd_t^x and vertical component dtyd_t^y are treated like image channels (right of the figure at the top of the article). The input Iτ∈Rw×h×2LI_\tau \in \mathbb{R}^{w \times h \times 2L} stacking LL pairs starting from frame τ\tau is as follows (Eq. 1 of the paper).

Iτ(u,v,2k−1)=dτ+k−1x(u,v),Iτ(u,v,2k)=dτ+k−1y(u,v)I_\tau(u, v, 2k-1) = d^x_{\tau+k-1}(u, v), \qquad I_\tau(u, v, 2k) = d^y_{\tau+k-1}(u, v)

Here u=1,…,wu = 1, \dots, w, v=1,…,hv = 1, \dots, h, and k=1,…,Lk = 1, \dots, L. Reading the channels at a pixel (u,v)(u, v) gives the motion at that location over LL frames.

The paper compares the following variations of how the input is built.

  • Trajectory stacking (Eq. 2): Instead of the same location, it stacks the displacements at the points pkp_k reached by following the flow, with p1=(u,v)p_1 = (u, v) and pk=pk−1+dτ+k−2(pk−1)p_k = p_{k-1} + d_{\tau+k-2}(p_{k-1}).
  • Bidirectional flow: It stacks L/2L/2 forward flows from τ\tau onward and L/2L/2 backward flows before τ\tau. The number of channels stays 2L2L.
  • Mean subtraction: When the camera moves, the whole flow shifts in one direction. The mean vector of each displacement field is therefore subtracted from it.

Network shape (Figure 1 and Chapter 5 of the paper)

The two streams have the same shape, a network close to AlexNet called CNN-M-2048.

LayerSpatial streamTemporal stream
conv17×7, 96 filters, stride 2, normalization, poolingSame
conv25×5, 256 filters, stride 2, normalization, pooling5×5, 256 filters, stride 2, pooling (no normalization)
conv3–53×3, 512 filters, stride 1 (pooling after conv5)Same
full6, full74096 and 2048 units, each with dropoutSame
OutputSoftmaxSoftmax

All hidden layers use ReLU activations, and max pooling is 3×3 with stride 2. The second normalization layer was removed from the temporal stream to reduce memory.

Training

  • Spatial stream: Pretrained on ImageNet (ILSVRC-2012), and only the last classification layer is trained on video.
  • Temporal stream: Trained from scratch on video only. Because video data is scarce, UCF-101 and HMDB-51 are used together via multi-task learning. Two dataset-specific softmax layers are placed on top of the last fully connected layer, and each loss is computed only on videos from its dataset and summed.
  • Common settings: Mini-batch SGD with momentum 0.9. A mini-batch is formed by choosing one frame from each of 256 videos, randomly cropping to 224 × 224, and flipping horizontally. When training from scratch, the learning rate starts at 10−210^{-2}, drops to 10−310^{-3} at 50K iterations and to 10−410^{-4} at 70K, and training stops at 80K.

Optical flow is computed and stored before training. The paper used the GPU version of OpenCV (0.06 s per pair) and, by linearly rescaling the horizontal and vertical components to 0–255 and compressing them as JPEG, reduced the flow for UCF-101 from 1.5TB to 27GB.

Why Splitting into Two Works

1. Making motion explicit in the input eases learning

When many frames are stacked and fed into a CNN, motion has to be estimated implicitly in the network's first layer. In the paper's experiments, Slow Fusion, which stacks 11 RGB frames, reached 56.4% on UCF-101 when trained from scratch, only slightly better than 52.3% for a single frame. The optical-flow temporal stream, also trained from scratch, reached 81.0%. The paper concludes that multi-frame information is important, but so is passing it to the CNN in an appropriate form.

2. It generalizes hand-crafted features

The first-layer filters of the temporal stream had learned to compute spatial derivatives of the flow (how motion changes across locations) and temporal derivatives (how motion changes over time). The former works much like the hand-crafted MBH (motion boundary histogram) feature. HOF (histogram of flow orientations) can also be expressed with a single convolution layer plus ReLU and pooling. The temporal stream can be viewed as a learned generalization of such features.

3. Appearance and motion complement each other

The spatial stream looks at "what is in the scene" (tools, places, etc.), and the temporal stream at "how things moved". For example, the spatial stream confused "hammering" and "head massage", which both show people's faces prominently, while the temporal stream confused "hammering" and "brushing teeth", where the hand moves up and down. Because the two make different mistakes, combining the scores raises accuracy.

As an everyday analogy, it is like assigning one person to look at photos and another to watch slow-motion footage that records only movement, and then reconciling their two answers at the end.

Connecting the two streams in the middle (placing a shared fully connected layer on top of full6 or full7) is also conceivable, but in the paper it overfit and was unusable, so the softmax scores are combined late instead.

Experimental Results

The paper evaluates on UCF-101 (101 classes, about 13,000 videos) and HMDB-51 (51 classes, about 6,800 videos). Both have three train/test splits; designs are compared on split 1, and then the average over the three splits is compared with prior work.

How to train the spatial stream (UCF-101 split 1; Table 1a of the paper)

Training settingDropout 0.5Dropout 0.9
From scratch42.5%52.3%
Pretrained + fine-tune all70.8%72.8%
Pretrained + last layer only72.7%59.9%

Training from scratch on UCF-101 alone overfit, and ImageNet pretraining helped greatly. Fine-tuning the whole network was barely different from training only the last layer.

How to build the temporal-stream input (UCF-101 split 1, trained from scratch; Table 1b of the paper)

InputNo mean subtractionMean subtraction
Single flow (L=1L = 1)―73.9%
Optical flow stacking (L=5L = 5)―80.4%
Optical flow stacking (L=10L = 10)79.9%81.0%
Trajectory stacking (L=10L = 10)79.6%80.2%
Optical flow stacking (L=10L = 10, bidirectional)―81.2%

Stacking several pairs was much better than a single pair. The gain from 5 to 10 pairs was small, and L=10L = 10 was used thereafter.

Increasing training data for the temporal stream on HMDB-51 (split 1; Table 2 of the paper)

Training settingAccuracy
Train on HMDB-51 only46.6%
Pretrain on UCF-101, then fine-tune49.0%
Add 78 non-overlapping classes from UCF-10152.8%
Multi-task learning on UCF-101 and HMDB-5155.4%

Combining the two streams (UCF-101 split 1; Table 3 of the paper; spatial stream pretrained + last layer only)

Temporal streamFusionAccuracy
BidirectionalAveraging85.6%
UnidirectionalAveraging85.9%
Unidirectional, multi-taskAveraging86.2%
Unidirectional, multi-taskLinear SVM87.0%

Fusion improved accuracy by about 6 points over the temporal stream alone and about 14 points over the spatial stream alone.

Comparison with prior work (average over 3 splits; Table 4 of the paper)

MethodUCF-101HMDB-51
Improved dense trajectories (IDT)85.9%57.2%
IDT + higher-dimensional encodings87.9%61.1%
IDT + stacked Fisher vectors―66.8%
Slow Fusion (CNN with stacked frames)65.4%―
Spatial stream only73.0%40.5%
Temporal stream only83.7%54.6%
Two-Stream (fusion by averaging)86.9%58.0%
Two-Stream (fusion by SVM)88.0%59.4%

On UCF-101 it matched the best hand-crafted-feature method and greatly outperformed prior deep learning work. On HMDB-51 it did not yet reach stacked Fisher vectors (66.8%).

Practical Considerations

Keep the following points in mind when using Two-Stream ConvNets.

  • It sees only a short time span: The temporal stream sees 10 flow pairs at a time. In the summary in the I3D paper, this corresponds to about 0.4 seconds of 25 fps video. The flow of an action that unfolds over several seconds cannot be captured; at test time the scores of 25 frames are merely averaged. TSN addressed this weakness by sampling at intervals across the whole video.
  • Appearance and motion stay separate until the end: The two streams are only combined late, so the correspondence between appearance and motion, such as "the object at this location moved this way", cannot be learned. The paper itself lists the absence of pooling along trajectories as future work.
  • Camera motion handling remains simple: Only the mean displacement is subtracted, so camera motion such as zoom or rotation remains.

Computing optical flow is expensive and dominates inference time. The paper precomputes and stores the flow before training. Measurements in the C3D paper report that Brox's optical flow processes only about 1.2 frames per second even on GPU, 274 times slower than C3D (about 314 frames per second). For real-time applications, consider models that do not use flow, such as TSM or SlowFast.

Comparison with Other Models

Comparing video action recognition models from the same viewpoints gives the following.

ModelConvolutionHow motion is capturedTemporal rangeOptical flowPretraining
Two-Stream ConvNets2DA separate CNN sees stacked flow inputAbout 10 frames + averaging at testRequiredSpatial: ImageNet, temporal: none
C3D3D (3×3×3)Learned from RGB via 3D convolution16 framesNot neededSports-1M
TSN2DTwo streams + consensus of per-segment snippetsWhole video (sparse sampling)Used (RGB only also possible)ImageNet
I3D3D (inflated 2D)3D convolution + flow stream64 framesUsed (RGB only also possible)ImageNet + Kinetics
TSM2DShifts part of the feature channels in time8–16 framesNot neededImageNet
SlowFast3D (partly 2D)Two pathways at low and high frame ratesA 64-frame clipNot neededNone (trained from scratch)

Rough guidelines for choosing:

  • To learn the basic ideas of video recognition or to get a baseline for comparison: Two-Stream ConvNets is the starting point. The idea of separating appearance and motion lives on in the two streams of TSN and I3D and the two pathways of SlowFast.
  • When accuracy comes first and there is time to compute optical flow: Two-stream I3D, including pretraining on Kinetics, is a strong choice.
  • To reduce computation or run in real time: Choose TSM or SlowFast, which do not use optical flow.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
Example implementation of Two-Stream ConvNets (Simonyan & Zisserman 2014, Figure 1, Section 3.1, Chapter 5)
Spatial stream: a single RGB frame (N, 3, 224, 224)
Temporal stream: a stack of L optical-flow pairs (N, 2L, 224, 224)
"""


def stack_flows(flows):
  """Eq. 1: flows is (L, 2, H, W) (horizontal dx and vertical dy of each pair).
  Subtract the mean vector from each displacement field (to weaken camera motion) and arrange into 2L channels."""
  flows = flows - flows.mean(dim=(2, 3), keepdim=True)
  L, _, H, W = flows.shape
  return flows.reshape(2 * L, H, W)   # channel order is dx_1, dy_1, dx_2, dy_2, ...


class StreamConvNet(nn.Module):
  """Close to CNN-M-2048 (Figure 1). The temporal stream removes the second normalization layer (Chapter 5)."""

  def __init__(self, in_ch, num_classes, second_norm=True, p_drop=0.5):
    super().__init__()
    lrn = lambda: nn.LocalResponseNorm(size=5, alpha=1e-4, beta=0.75, k=2.0)  # same settings as AlexNet
    pool = lambda: nn.MaxPool2d(3, stride=2)                                    # 3x3, stride 2
    self.features = nn.Sequential(
      nn.Conv2d(in_ch, 96, 7, stride=2), nn.ReLU(inplace=True), lrn(), pool(),
      nn.Conv2d(96, 256, 5, stride=2, padding=1), nn.ReLU(inplace=True),
      lrn() if second_norm else nn.Identity(), pool(),
      nn.Conv2d(256, 512, 3, padding=1), nn.ReLU(inplace=True),
      nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True),
      nn.Conv2d(512, 512, 3, padding=1), nn.ReLU(inplace=True), pool(),
    )
    self.classifier = nn.Sequential(
      nn.Flatten(),
      nn.LazyLinear(4096), nn.ReLU(inplace=True), nn.Dropout(p_drop),   # full6
      nn.Linear(4096, 2048), nn.ReLU(inplace=True), nn.Dropout(p_drop),  # full7
      nn.Linear(2048, num_classes),
    )

  def forward(self, x):
    return self.classifier(self.features(x))   # pre-softmax scores


class TwoStream(nn.Module):
  def __init__(self, num_classes, L=10):
    super().__init__()
    self.spatial = StreamConvNet(3, num_classes)
    # strong dropout because it is trained from scratch (0.9 in Table 1b of the paper)
    self.temporal = StreamConvNet(2 * L, num_classes, second_norm=False, p_drop=0.9)

  def forward(self, rgb, flow_stack):
    # late fusion: average the two softmax scores (the other option is a linear SVM)
    p_spatial = F.softmax(self.spatial(rgb), dim=1)
    p_temporal = F.softmax(self.temporal(flow_stack), dim=1)
    return (p_spatial + p_temporal) / 2


model = TwoStream(num_classes=101)
model.eval()   # disable dropout (use model.train() for training; the two streams are trained separately)
rgb = torch.randn(2, 3, 224, 224)
flow = torch.stack([stack_flows(torch.randn(10, 2, 224, 224)) for _ in range(2)])
with torch.no_grad():
  print(model(rgb, flow).shape)   # torch.Size([2, 101])

FAQ

Q. What does each of the two streams in Two-Stream ConvNets look at?
A.

The spatial stream looks at "what is in the scene" (objects, places, etc.) from a single frame (RGB), and the temporal stream looks at "how things moved" from an input stacking 10 consecutive optical-flow pairs. Both are 2D CNNs of the same shape, and only their final softmax scores are combined by averaging or a linear SVM.

Q. Why does the temporal-stream input have 20 channels?
A.

Each optical-flow pair has two channels, the horizontal displacement dxd^x and the vertical displacement dyd^y, and L=10L = 10 pairs are stacked, giving 2L=202L = 20 channels (Eq. 1 of the paper). The first convolution layer looks at all 20 channels together, so it can learn how motion changes across locations and over time.

Q. How do Two-Stream ConvNets and I3D differ?
A.

The two streams of Two-Stream ConvNets are 2D CNNs, and the temporal stream sees only 10 flow pairs at a time. I3D uses, for each of the two streams, a 3D CNN made by inflating the filters of a 2D CNN (Inception-v1) along the time axis, and sees 64 frames together. With additional pretraining on Kinetics, it reached 98.0% on UCF-101.

References

  1. Simonyan, K., & Zisserman, A. (2014). Two-Stream Convolutional Networks for Action Recognition in Videos. NIPS 2014. arXiv:1406.2199.
  2. Karpathy, A., Toderici, G., Shetty, S., Leung, T., Sukthankar, R., & Fei-Fei, L. (2014). Large-scale Video Classification with Convolutional Neural Networks. CVPR 2014.
  3. Tran, D., Bourdev, L., Fergus, R., Torresani, L., & Paluri, M. (2015). Learning Spatiotemporal Features with 3D Convolutional Networks. ICCV 2015. arXiv:1412.0767.