Neural Nearest Neighbors Networks

Tobias Plötz, Stefan Roth

Introduction

The ongoing surge of convolutional neural networks (CNNs) has revolutionized many areas of machine learning and its applications by enabling unprecedented predictive accuracy. Most network architectures focus on local processing by combining convolutional layers and element-wise operations. In order to draw upon information from a sufficiently broad context, several strategies, including dilated convolutions or hourglass-shaped architectures , have been explored to increase the receptive field size. Yet, they trade off context size for localization accuracy. Hence, for many dense prediction tasks, e. g. in image analysis and restoration, stacking ever more convolutional blocks has remained the prevailing choice to obtain bigger receptive fields .

In contrast, traditional algorithms in image restoration increase the receptive field size via non-local processing, leveraging the self-similarity of natural signals. They exploit that image structures tend to re-occur within the same image , giving rise to a strong prior for image restoration . Hence, methods like non-local means or BM3D aggregate information across the whole image to restore a local patch. Here, matching patches are usually selected based on some hand-crafted notion of similarity, e. g. the Euclidean distance between patches of input intensities. Incorporating this kind of non-local processing into neural network architectures for image restoration has only very recently been considered . These methods replace the filtering of matched patches with a trainable network, while the feature space on which kk-nearest neighbors selection is carried out is taken to be fixed. But why should we rely on a predefined matching space in an otherwise end-to-end trainable neural network architecture? In this paper, we demonstrate that we can improve non-local processing considerably by also optimizing the feature space for matching.

The main technical challenge is imposed by the non-differentiability of the KNN selection rule. To overcome this, we make three contributions. First, we propose a continuous deterministic relaxation of the KNN rule, which allows differentiating the output w. r. t. pairwise distances in the input space, such as between image patches. The strength of the novel relaxation can be controlled by a temperature parameter whose gradients can be obtained as well. Second, from our relaxation we develop a novel neural network layer, called neural nearest neighbors block (N3\text{N}^{3} block), which enables end-to-end trainable non-local processing based on the principle of self-similarity. Third, we demonstrate that the accuracy of image denoising and single image super-resolution (SISR) can be improved significantly by augmenting strong local CNN architectures with our novel N3\text{N}^{3} block, also outperforming strong non-local baselines. Moreover, for the task of correspondence classification, we obtain significant improvements by simply augmenting a recent neural network baseline with our N3\text{N}^{3} block, showing its effectiveness on set-valued data.

Related Work

An important branch of image restoration techniques is comprised of non-local methods , driven by the concept of self-similarity. They rely on similar structures being more likely to encounter within an image than across images . For denoising, the non-local means algorithm averages noisy pixels weighted by the similarity of local neighborhoods. The popular BM3D method goes beyond simple averaging by transforming the 3D stack of matching patches and employing a shrinkage function on the resulting coefficients. Such transform domain filtering is also used in other image restoration tasks, e. g. single image super-resolution . More recently, Yang and Sun propose to learn the domain transform and activation functions. Lefkimmiatis goes further by chaining multiple stages of trained non-local modules. All of these methods, however, keep the standard KNN matching in fixed feature spaces. In contrast, we propose to relax the non-differentiable KNN selection rule in order to obtain a fully end-to-end trainable non-local network.

Recently, non-local neural networks have been proposed for higher-level vision tasks such as object detection or pose estimation and, with a recurrent architecture, for low-level vision tasks . While also learning a feature space for distance calculation, their aggregation is restricted to a single weighted average of features, a strategy also known as (soft) attention. Our differentiable nearest neighbors selection generalizes this; our method can recover a single weighted average by setting k=1k{=}1. As such, our novel N3\text{N}^{3} block can potentially benefit other methods employing weighted averages, e. g. for visual question answering and more general learning tasks like modeling memory access or sequence modeling . Weighted averages have also been used for building differentiable relaxations of the kk-nearest neighbors classifier . Note that the crucial difference to our work is that we propose a differentiable relaxation of the KNN selection rule where the output is a set of neighbors, instead of a single aggregation of the labels of the neighbors. Without using relaxations, Weinberger and Saul learn the distance metric underlying KNN classification using a max-margin approach. They rely on predefined target neighbors for each query item, a restriction that we avoid.

Image denoising. Besides improving the visual quality of noisy images, the importance of image denoising also stems from the fact that image noise severely degrades the accuracy of downstream computer vision tasks, e. g. detection . Moreover, denoising has been recognized as a core module for density estimation and serves as a sub-routine for more general image restoration tasks in a flurry of recent work, e. g. . Besides classical approaches , CNN-based methods have shown strong denoising accuracy over the past years.

Differentiable k-Nearest Neighbors

We first detail our continuous and differentiable relaxation of the kk-nearest neighbors (KNN) selection rule. Here, we will make few assumptions on the data to derive a very general result that can be used with many kinds of data, including text or sets. In the next section, we will then define a non-local neural network layer based on our relaxation. Let us start by precisely defining KNN selection. Assume that we are given a query item qq, a database of candidate items (xi)iI(x_{i})_{i\in I} with indices I={1,,M}I=\{1,\ldots,M\} for matching, and a distance metric d(,)d(\cdot,\cdot) between pairs of items. Assuming that qq is not in the database, dd yields a ranking of the database items according to the distance to the query. Let πq:II\pi_{q}:I\rightarrow I be a permutation that sorts the database items by increasing distance to qq:

The KNN of qq are then given by the set of the first kk items w. r. t. the permutation πq\pi_{q}

The KNN selection rule is deterministic but not differentiable. This effectively hinders to derive gradients w. r. t. the distances d(,)d(\cdot,\cdot). We will alleviate this problem in two steps. First, we interpret the deterministic KNN rule as a limit of a parametric family of discrete stochastic sampling processes. Second, we derive continuous relaxations for the discrete variables, thus allowing to backpropagate gradients through the neighborhood selection while still preserving the KNN rule as a limit case.

KNN rule as limit distribution. We proceed by interpreting the KNN selection rule as the limit distribution of kk categorical distributions that are constructed as follows. As in Neighborhood Component Analysis , let Cat(w1  α1,t)\text{Cat}(w^{1}\ |\ \alpha^{1},t) be a categorical distribution over the indices II of the database items, obtained by deriving logits αi1\alpha^{1}_{i} from the negative distances to the query item d(q,xi)d(q,x_{i}), scaled with a temperature parameter tt. The probability of w1w^{1} taking a value iIi\in I is given by:

Here, we treat w1w^{1} as a one-hot coded vector and denote with w1=iw^{1}=i that the ii-th entry is set to one while the others are zero. In the limit of t0t\to 0, Cat(w1  α1,t)\text{Cat}(w^{1}\ |\ \alpha^{1},t) will converge to a deterministic (“Dirac delta”) distribution centered at the index of the database item with smallest distance to qq. Thus we can regard sampling from Cat(w1  α1,t)\text{Cat}(w^{1}\ |\ \alpha^{1},t) as a stochastic relaxation of 1-NN . We now generalize this to arbitrary kk by proposing an iterative scheme to construct further conditional distributions Cat(wj+1  αj+1,t)\text{Cat}(w^{j+1}\ |\ \alpha^{j+1},t). Specifically, we compute αj+1\alpha^{j+1} by setting the wjw^{j}-th entry of αj\alpha^{j} to negative infinity, thus ensuring that this index cannot be sampled again:

The updated logits are used to define a new categorical distribution for the next index to be sampled:

From the index vectors wjw^{j}, we can define the stochastic nearest neighbors {X1,,Xk}\{X^{1},\ldots,X^{k}\} of qq using

When the temperature parameter tt approaches zero, the distribution over the {X1,,Xk}\{X^{1},\dots,X^{k}\} will be a deterministic distribution centered on the kk nearest neighbors of qq. Using these stochastic nearest neighbors directly within a deep neural network is problematic, since gradient estimators for expectations over discrete variables are known to suffer from high variance . Hence, in the following we consider a continuous deterministic relaxation of the discrete random variables.

Continuous deterministic relaxation. Our basic idea is to replace the one-hot coded weight vectors with their continuous expectations. This will yield a deterministic and continuous relaxation of the stochastic nearest neighbors that still converges to the hard KNN selection rule in the limit case of t0t\to 0. Concretely, the expectation wˉ1\bar{w}^{1} of the first index vector w1w^{1} is given by

We can now relax the update of the logits (Eq. 5) by using the expected weight vector instead of the discrete sample as

The updated logits are then used in turn to calculate the expectation over the next index vector:

Analogously to Eq. 7, we define continuous nearest neighbors {Xˉ1,,Xˉk}\{\bar{X}^{1},\ldots,\bar{X}^{k}\} of qq using the wˉj\bar{w}^{j} as

In the limit of t0t\to 0, the expectation wˉ1\bar{w}^{1} of the first sampled index vector will approach a one-hot encoding of the index of the closest neighbor. As a consequence, the logit update in Eq. 9 will also converge to the hard update from Eq. 5. By induction it follows that the other wˉj\bar{w}^{j} will converge to a one-hot encoding of the closest indices of the jj-th nearest neighbor. In summary, this means that our continuous deterministic relaxation still contains the hard KNN selection rule as a limit case.

Discussion. Figure 1 shows the relation between the deterministic KNN selection, stochastic nearest neighbors, and our proposed continuous nearest neighbors. Note that the continuous nearest neighbors are differentiable w. r. t. the pairwise distances as well as the temperature tt. This allows making the temperature a trainable parameter. Moreover, the temperature can depend on the query item qq, thus allowing to learn for which query items it is beneficial to average more uniformly across the database items, i. e. by choosing a high temperature, and for which query items the continuous nearest neighbors should be close to the discrete nearest neighbors, i. e. by choosing a low temperature. Both cases have their justification. A more uniform averaging effectively allows to aggregate information from many neighbors at once. On the other hand, the more distinct neighbors obtained with a low temperature allow to first non-linearly process the information before eventually fusing it.

From Eq. 11 it becomes apparent that the continuous nearest neighbors effectively take kk weighted averages over the database items. Thus, prior work such as non-local networks , differentiable relaxations of the KNN classifier , or soft attention-based architectures can be realized as a special case of our architecture with k=1k=1. We also experimented with a continuous relaxation of the stochastic nearest neighbors based on approximating the discrete distributions with Concrete distributions . This results in a stochastic sampling of weighted averages as opposed to our deterministic nearest neighbors. For the dense prediction tasks considered in our experiments, we found the deterministic variant to give significantly better results, see Sec. 5.1.

Neural Nearest Neighbors Block

In the previous section we made no assumptions about the source of query and database items. Here, we propose a new network block, called neural nearest neighbors block (N3\text{N}^{3} block, Fig. 2(a)), which integrates our continuous and differentiable nearest neighbors selection into feed-forward neural networks based on the concept of self-similarity, i. e. query set and database are derived from the same features (e. g., feature patches of an intermediate layer within a CNN). An N3\text{N}^{3} block consists of two important parts. First, an embedding network takes the input and produces a feature embedding as well as temperature parameters. These are used in a second step to compute continuous nearest neighbors feature volumes that are aggregated with the input. We interleave N3\text{N}^{3} blocks with existing local processing networks to form neural nearest neighbors networks (N3\text{N}^{3}Net) as shown in Fig. 2(b). In the following, we take a closer look at the components of an N3\text{N}^{3} block and their design choices.

Embedding network. A first branch of the embedding network calculates a feature embedding E=fE(Y)E=f_{\text{E}}(Y). For image data, we use CNNs to parameterize fEf_{\text{E}}; for set input we use multi-layer perceptrons. The pairwise distance matrix DD can now be obtained by Dij=d(Ei,Ej)D_{ij}=d(E_{i},E_{j}), where EiE_{i} denotes the embedding of the ii-th item and dd is a differentiable distance function. We found that the Euclidean distance works well for the tasks that we consider. In practice, for each query item, we confine the set of potential neighbors to a subset of all items, e. g. all image patches in a certain local region. This allows our N3\text{N}^{3} block to scale linearly in the number of items instead of quadratically. Another network branch computes a tensor T=fT(Y)T=f_{\text{T}}(Y) containing the temperature tt for each item. Note that fEf_{\text{E}} and fTf_{\text{T}} can potentially share weights to some degree. We opted for treating them as separate networks as this allows for an easier implementation.

Continuous nearest neighbors selection. From the distance matrix DD and the temperature tensor TT, we compute kk continuous nearest neighbors feature volumes N1,,NkN_{1},\dots,N_{k} from the input features YY by applying Eqs. 8, 9, 10 and 11 to each item. Since YY and each NiN_{i} have equal dimensionality, we could use any element-wise operation to aggregate the original features YY and the neighbors. However, a reduction at this stage would mean a very early fusion of features. Hence, we instead simply concatenate YY and the NiN_{i} along the feature dimension, which allows further network layers to learn how to fuse the information effectively in a non-linear way.

N3\text{N}^{3} block for image data. The N3\text{N}^{3} block described above is very generic and not limited to a certain input domain. We now describe minor technical modifications when applying the N3\text{N}^{3} block to image data. Traditionally, non-local methods in image processing have been applied at the patch-level, i. e. the items to be matched consist of image patches instead of pixels. This has the advantage of using a broader local context for matching and aggregation. We follow this reasoning and first apply a strided im2col operation on EE before calculating pairwise distances. The temperature parameter for each patch is obtained by taking the corresponding center pixel in TT. Each nearest neighbor volume NiN_{i} is converted from the patch domain to the image domain by applying a col2im operation, where we average contributions of different patches to the same pixel.

Experiments

We now analyze the properties of our novel N3\text{N}^{3}Net and show its benefits over state-of-the-art baselines. We use image denoising as our main test bed as non-local methods have been well studied there. Moreover, we evaluate on single image super-resolution and correspondence classification.

Gaussian image denoising. We consider the task of denoising a noisy image D\mathbf{D}, which arises by corrupting a clean image C\mathbf{C} with additive white Gaussian noise of standard deviation σ\sigma:

Our baseline architecture is the DnCNN model of Zhang et al. , consisting of 1616 blocks, each with a sequence of a 3×33\times 3 convolutional layer with 6464 feature maps, batch normalization , and a ReLU activation function. In the end, a final 3×33\times 3 convolution is applied, the output of which is added back to the input through a global skip connection.

We use the DnCNN architecture to create our N3\text{N}^{3}Net for image denoising. Specifically, we use three DnCNNs with six blocks each, cf. Fig. 2(b). The first two blocks output 88 feature maps, which are fed into a subsequent N3\text{N}^{3} block that computes 77 neighbor volumes. The concatenated output again has a depth of 6464 feature channels, matching the depth of the other intermediate blocks. The N3\text{N}^{3} blocks extract 10×1010\times 10 patches with a stride of 55. Patches are matched to other patches in a 80×8080\times 80 region, yielding a total of 224224 candidate patches for matching each query patch. More details on the architecture can be found in the supplemental material.

Training details. We follow the protocol of Zhang et al. and use the 400 images in the train and test split of the BSD500 dataset for training. Note that these images are strictly separate from the validation images. For each epoch, we randomly crop 512512 patches of size 80×8080\times 80 from each training image. We use horizontal and vertical flipping as well as random rotations {<spanclass="katexdisplay"><spanclass="katex"><spanclass="katexmathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"display="block"><semantics><mrow><moseparator="true">,</mo></mrow><annotationencoding="application/xtex">,</annotation></semantics></math></span><spanclass="katexhtml"ariahidden="true"><spanclass="base"><spanclass="strut"style="height:0.3em;verticalalign:0.1944em;"></span><spanclass="mpunct">,</span></span></span></span></span>,<spanclass="katexdisplay"><spanclass="katex"><spanclass="katexmathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"display="block"><semantics><mrow><moseparator="true">,</mo></mrow><annotationencoding="application/xtex">,</annotation></semantics></math></span><spanclass="katexhtml"ariahidden="true"><spanclass="base"><spanclass="strut"style="height:0.3em;verticalalign:0.1944em;"></span><spanclass="mpunct">,</span></span></span></span></span>}\in\{<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">,</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.3em;vertical-align:-0.1944em;"></span><span class="mpunct">,</span></span></span></span></span>,<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">,</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.3em;vertical-align:-0.1944em;"></span><span class="mpunct">,</span></span></span></span></span>\} as further data augmentation. In total, we train for 5050 epochs with a batch size of 3232, using the Adam optimizer with default parameters β1=0.9,β2=0.999\beta_{1}=0.9,\beta_{2}=0.999 to minimize the squared error. The learning rate is initially set to 10310^{-3} and exponentially decreased to 10810^{-8} over the course of training. Following the publicly available implementation of DnCNN , we apply a weight decay with strength 10410^{-4} to the weights of the convolution layers and the scaling of batch normalization layers.

We evaluate our full model on three different datasets: (i) a set of twelve commonly used benchmark images (Set12), (ii) the 68 images subset of the BSD500 validation set , and (iii) the Urban100 dataset, which contains images of urban scenes where repetitive patterns are abundant.

We begin by discerning the effectiveness of the individual components. We compare our full N3\text{N}^{3}Net against several baselines: (i,ii) The baseline DnCNN network with depths 1717 (default) and 1818 (matching the depth of N3\text{N}^{3}Net). (iii) A baseline where we replace the N3\text{N}^{3} blocks with KNN selection (k=7k=7) to obtain neighbors for each patch. Distance calculation is done on the noisy input patches. (iv) The same baseline as (iii) but where distances are calculated on denoised patches. Here we use the pretrained 1717-layer DnCNN as strong denoiser. The task specific hand-chosen distance embedding for this baseline should intuitively yield more sensible nearest neighbors matches than when matching noisy input patches. (v) A baseline where we use Concrete distributions to approximately reparameterize the stochastic nearest neighbors sampling. The resulting Concrete block has an additional network for estimating the annealing parameter of the Concrete distribution.

Table 1 shows the results on the Urban100 test set (σ=25\sigma=25) from which we can infer four insights: First, the KNN baselines (iii) and (iv) improve upon the plain DnCNN model, showing that allowing the network to access non-local information is beneficial. Second, matching denoised patches (baseline (iv)) does not improve significantly over matching noisy patches (baseline (iii)). Third, learning a patch embedding with our novel N3\text{N}^{3} block shows a clear improvement over all baselines. We, moreover, evaluate a smaller version of N3\text{N}^{3}Net with only two DnCNN blocks of depth 66 (ours light). This model already outperforms the baseline DnCNN with depth 1717 despite having fewer layers (1212 vs. 1717) and fewer parameters (427427k vs. 556556k). Fourth, reparameterization with Concrete distributions (baseline (v)) performs worse than our continuous nearest neighbors. This is probably due to the Concrete distribution introducing stochasticity into the forward pass, leading to a less stable training. Additional ablations are given in the the supplemental material.

Next, we compare N3\text{N}^{3}Nets with a varying number of selected neighbors. Table 2 shows the results on Urban100 with σ{25,50}\sigma\in\{25,50\}. We can observe that, as expected, more neighbors improve denoising results. However, the effect diminishes after roughly four neighbors and accuracy starts to deteriorate again. As we refrain from selecting optimal hyper-parameters on the test set, we will stick to the architecture with k=7k=7 for the remaining experiments on image denoising and SISR.

2 Comparison to the state of the art

We compare our full N3\text{N}^{3}Net against state-of-the-art local denoising methods, i. e. the DnCNN baseline , the very deep and wide (3030 layers, 128128 feature channels) RED30 model , and the recent FFDNet . Moreover, we compare against competing non-local denoisers. These include the classical BM3D , which uses a hand-crafted denoising pipeline, and the state-of-the-art trainable non-local models NLNet and UNLNet , both learning to process non-locally aggregated patches. We also compare against NN3D , which applies a non-local step on top of a pretrained network. For fair comparison, we apply a single denoising step for NN3D using our 17-layer baseline DnCNN. As a crucial difference to our proposed N3\text{N}^{3}Net, all of the compared non-local methods use KNN selection on a fixed feature space, thus not being able to learn an embedding for matching.

Table 3 shows the results for three different noise levels. We make three important observations: First, our N3\text{N}^{3}Net significantly outperforms the baseline DnCNN network on all tested noise levels and all datasets. Especially for higher noise levels the margin is dramatic, e. g. +0.54dB (σ=50)+0.54\text{dB }(\sigma=50) or +0.79dB (σ=70)+0.79\text{dB }(\sigma=70) on Urban100. Even the deeper and wider RED30 model does not reach the accuracy of N3\text{N}^{3}Net. Second, our method is the only trainable non-local model that is able to outperform the local models DnCNN, RED30, and FFDNet. The competing models NLNet and UNLNet do not reach the accuracy of DnCNN even on Urban100, whereas our N3\text{N}^{3}Net even fares better than the strongest local denoiser FFDNet. Third, the post-hoc non-local step applied by NN3D is very effective on Urban100 where self-similarity can intuitively shine. However, on Set12 the gains are noticeably smaller whilst on BDS68 the non-local step can even result in degraded accuracy, e. g. NN3D achieves 0.04dB-0.04\text{dB} compared to DnCNN while N3\text{N}^{3}Net achieves +0.16dB+0.16\text{dB} for σ=50\sigma=50. This highlights the importance of integrating non-local processing into an end-to-end trainable pipeline. Figure 3 shows denoising results for an image from the Urban100 dataset. BM3D and UNLNet can exploit the recurrence of image structures to produce good results albeit introducing artifacts in the windows. DnCNN and FFDNet yield even more artifacts due to the limited receptive field and NN3D, as a post-processing method, cannot recover from the errors of DnCNN. In contrast, our N3\text{N}^{3}Net produces a significantly cleaner image where most of the facade structure is correctly restored.

3 Real image denoising

To further demonstrate the merits of our approach, we applied the same N3\text{N}^{3}Net architecture as before to the task of denoising real-world images with realistic noise. To this end, we evaluate on the recent Darmstadt Noise Dataset , consisting of 5050 noisy images shot with four different cameras at varying ISO levels. Realistic noise can be well explained by a Poisson-Gaussian distribution which, in turn, can be well approximated by a Gaussian distribution where the variance depends on the image intensity via a linear noise level function . We use this heteroscedastic Gaussian distribution to generate synthetic noise for training. Specifically, we use a broad range of noise level functions covering those that occur on the test images. For training, we use the 400400 images of the BSDS training and test splits, 800800 images of the DIV2K training set , and a training split of 37933793 images from the Waterloo database . Before adding synthetic noise, we transform the clean RGB images YRGB\mathbf{Y}_{\text{RGB}} to YRAW\mathbf{Y}_{\text{RAW}} such that they more closely resemble images with raw intensity values:

where Y()Y(\cdot) computes luminance values from RGB, the exponentiation with fef_{e} aims at undoing compression of high image intensities, and scaling with fcf_{c} aims at undoing the effect of white balancing. Further training details can be found in the supplemental material.

We train both the DnCNN baseline as well as our N3\text{N}^{3}Net with the same training protocol and evaluate them on the benchmark website. Results are shown in Table 4. N3\text{N}^{3}Net sets a new state of the art for denoising raw images, outperforming DnCNN and BM3D by a significant margin. Moreover, the PSNR values, when evaluated on developed sRGB images, surpass those of the currently top performing methods in sRGB denoising, TWSC and CBDNet .

4 Single image super-resolution

We now show that we can also augment recent strong CNN models for SISR with our N3\text{N}^{3} block. We particularly consider the common task of upsampling a low-resolution image that was obtained from a high-resolution image by bicubic downscaling. We chose the VDSR model as our baseline architecture, since it is conceptually very close to the DnCNN model for image denoising. The only notable difference is that it has 2020 layers instead of 1717. We derive our N3\text{N}^{3}Net for SISR from the VDSR model by stacking three VDSR networks with depth 77 and inserting two N3\text{N}^{3} blocks (k=7k=7) after the first two VDSR networks, cf. Fig. 2(b). Following , the input to our network is the bicubicly upsampled low-resolution image and we train a single model for super-resolving images with factors 22, 33, and 44. Further details on the architecture and training protocol can be found in the supplemental material. Note that we refrain from building our N3\text{N}^{3}Net for SISR from more recent networks, e. g. MemNet , MDSR , or WDnCNN , since they are too costly to train.

We compare our N3\text{N}^{3}Net against VDSR and MemNet as well as two non-local models: SelfEx and the recent WSD-SR . Table 5 shows results on Set5 . Again, we can observe a consistent gain of N3\text{N}^{3}Net compared to the strong baseline VDSR for all super-resolution factors, e. g. +0.15dB+0.15\text{dB} for ×4\times 4 super-resolution. More importantly, the other non-local methods perform inferior compared to our N3\text{N}^{3}Net (e. g. +0.36dB+0.36\text{dB} compared to WSD-SR for ×2\times 2 super-resolution), showing that learning the matching feature space is superior to relying on a hand-defined feature space. Further quantitative and visual results demonstrating the same benefits of N3\text{N}^{3}Net can be found in the supplemental material.

5 Correspondence classification

As a third application, we look at classifying correspondences between image features from two images as either correct or incorrect. Again, we augment a baseline network with our non-local block. Specifically, we build upon the context normalization network , which we call CNNet in the following. The input to this network is a set of pairs of image coordinates of putative correspondences and the output is a probability for each of the correspondences to be correct. CNNet consists of 1212 blocks, each comprised of a local fully connected layer with 128128 feature channels that processes each point individually, and a context normalization and batch normalization layer that pool information across the whole point set. We augment CNNet by introducing a N3\text{N}^{3} block after the sixth original block. As opposed to the N3\text{N}^{3} block for the previous two tasks, where neighbors are searched only in the vicinity of a query patch, here we search for nearest neighbors among all correspondences. We want to emphasize that this is a pure set reasoning task. Image features are used only to determine putative correspondences while the network itself is agnostic of any image content.

For training we use the publicly available code of . We consider two settings: First, we train on the training set of the outdoor sequence St. Peter and evaluate on the test set of St. Peter and another outdoor sequence called Reichstag to test generalization. Second, we train and test on the respective sets of the indoor sequence Brown. Table 6 shows the resulting mean average precision (MAP) values at different error thresholds (for details on this metric, see ). We compare our N3\text{N}^{3}Net to the original CNNet and a baseline that just uses all putative correspondences for pose estimation. As can be seen, by simply inserting our N3\text{N}^{3} block we achieve a consistent and significant gain in all considered settings, increasing MAP scores by 10%10\% to 30%30\%. This suggests that our N3\text{N}^{3} block can enhance local processing networks in a wide range of applications and data domains.

Conclusion

Non-local methods have been well studied, e. g., in image restoration. Existing approaches, however, apply KNN selection on a hand-defined feature space, which may be suboptimal for the task at hand. To overcome this limitation, we introduced the first continuous relaxation of the KNN selection rule that maintains differentiability w. r. t. the pairwise distances used for neighbor selection. We integrated continuous nearest neighbors selection into a novel network block, called N3\text{N}^{3} block, which can be used as a general building block in neural networks. We exemplified its benefit in the context of image denoising, SISR, and correspondence classification, where we outperform state-of-the-art CNN-based methods and non-local approaches. We expect the N3\text{N}^{3} block to also benefit end-to-end trainable architectures for other input domains, such as text or other sequence-valued data.

The research leading to these results has received funding from the European Research Council under the European Union’s Seventh Framework Programme (FP/2007–2013)/ERC Grant agreement No. 307942. We would like to thank reviewers for their fruitful comments.

A Architectures and Training Details

A detailed summary of the used architectures can be found in the following tables:“Ker.”, “Str.”, “Pad.”, and “Feat.” refer to the kernel size, stride, padding and number of feature channels, respectively.

Tables 8 and 8 show the architecture of embedding network and the temperature network within an N3\text{N}^{3} block, respectively.

Table 10 shows the architecture of a DnCNN block used as local processing network in our N3\text{N}^{3}Net for denoising. The architecture of the whole N3\text{N}^{3}Net can be found in Table 10.

Table 12 shows the architecture of a VDSR block used as local processing network in our N3\text{N}^{3}Net for single image super-resolution. The architecture of the whole N3\text{N}^{3}Net can be found in Table 12.

Analogously to image denoising, the N3\text{N}^{3} blocks for super-resolution extract 10×1010\times 10 patches with a stride of 55 and patches are matched to other patches in a 80×8080\times 80 region.

Training details for super-resolution. We follow the training protocol of . Our training set consists of 291 images: The 200 images of the BSD500 training set and 91 images from . In each of the 80 training epochs, we randomly crop 38333833 patches of size 80×8080\times 80 from each image and apply data augmentation by flipping and using a rotation {<spanclass="katexdisplay"><spanclass="katex"><spanclass="katexmathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"display="block"><semantics><mrow><moseparator="true">,</mo></mrow><annotationencoding="application/xtex">,</annotation></semantics></math></span><spanclass="katexhtml"ariahidden="true"><spanclass="base"><spanclass="strut"style="height:0.3em;verticalalign:0.1944em;"></span><spanclass="mpunct">,</span></span></span></span></span>,<spanclass="katexdisplay"><spanclass="katex"><spanclass="katexmathml"><mathxmlns="http://www.w3.org/1998/Math/MathML"display="block"><semantics><mrow><moseparator="true">,</mo></mrow><annotationencoding="application/xtex">,</annotation></semantics></math></span><spanclass="katexhtml"ariahidden="true"><spanclass="base"><spanclass="strut"style="height:0.3em;verticalalign:0.1944em;"></span><spanclass="mpunct">,</span></span></span></span></span>}\in\{<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">,</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.3em;vertical-align:-0.1944em;"></span><span class="mpunct">,</span></span></span></span></span>,<span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">,</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.3em;vertical-align:-0.1944em;"></span><span class="mpunct">,</span></span></span></span></span>\}. Our batchsize is 32. As in , we use the SGD optimizer with momentum of 0.90.9 and a weight decay of 10410^{-4}. The initial learning rate is set to 0.10.1 and decayed by a factor of 10 every 20 epochs. Like , we apply gradient clipping to stabilize training.

B Further Analyses on Gaussian Denoising

We first conduct further ablation studies on the task of removing additive white Gaussian noise, extending the results of Sec. 5.1 of the main paper. We basically want to discern the effect of adding a single KNN or N3\text{N}^{3} block, respectively, and the effect of training the baseline model on bigger patch sizes. Table 13 shows these results. We make the following observations: First, for d=6d=6 our N3\text{N}^{3} block outperforms simple stacking of DnCNN networks as well as using a KNN block by a significant margin, for both σ=25\sigma=25 and 7070. Second, for d=17d=17 stacking two full networks performs poorly as training becomes more difficult with the increased depth. Interestingly, N3\text{N}^{3} can remedy some of the ill effects. Third, increasing the receptive field for the baseline DnCNN using more layers does not always help (cf. 2 ×\times DnCNN, d=17d=17 in Table 13). This is in contrast to our approach that allows increasing the receptive field without having many layers or parameters. Fourth, training on larger patch sizes does not benefit the baseline DnCNN model, cf. baseline (i) in Table 1 of the main paper.

Runtime overhead.

For denoising, the runtime of our full model with N3\text{N}^{3} increases by 3.5×3.5\times compared to the baseline DnCNN model (d=17d=17). For KNN this overhead is 2.5×2.5\times.

Learned strength of the continuous relaxation.

C Super-Resolution Results

Table 14 shows results for single image super-resolution on two further datasets: The full BSD500 validation set consisting of 100 images (BSD100), and Urban100. We observe a consistent gain of N3\text{N}^{3}Net compared to the very strong baseline VDSR on both datasets and all super-resolution factors. Moreover, the performance of the other non-local methods falls short compared to both the baseline and our N3\text{N}^{3}Net. Figure 4 shows visual results for our method and VDSR. We can see that N3\text{N}^{3}Net produces sharper details than VDSR, leading to perceptually more pleasing images despite the PSNR values being relatively close.

References