{'fraction_non_alphanumeric': 0.03440274414850686, 'fraction_numerical': 0.012476459510357816, 'mean_word_length': 4.7396255549121795, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Contextual Similarity Aggregation with Self-attention for Visual Re-ranking

In content-based image retrieval, the first-round retrieval result by simple visual feature comparison may be unsatisfactory, which can be refined by visual re-ranking techniques. In image retrieval, it is observed that the contextual similarity among the top-ranked images is an important clue to distinguish the semantic relevance. Inspired by this observation, in this paper, we propose a visual re-ranking method by contextual similarity aggregation with self-attention. In our approach, for each image in the top-K ranking list, we represent it into an affinity feature vector by comparing it with a set of anchor images. Then, the affinity features of the top-K images are refined by aggregating the contextual information with a transformer encoder. Finally, the affinity features are used to recalculate the similarity scores between the query and the top-K images for re-ranking of the latter. To further improve the robustness of our re-ranking model and enhance the performance of our method, a new data augmentation scheme is designed. Since our re-ranking model is not directly involved with the visual feature used in the initial retrieval, it is ready to be applied to retrieval result lists obtained from various retrieval algorithms. We conduct comprehensive experiments on four benchmark datasets to demonstrate the generality and effectiveness of our proposed visual re-ranking method.


Introduction
In instance image retrieval, the goal is to efficiently identify images containing the same object or describing the same scene with the query image from a large corpus of images. Towards this goal, many works have emerged in recent years [42,21,36,26,24]. With the development of deep learning, a great number of methods leverage convolutional neural network (CNN) as feature extractor [38,3,44,4,14,34,25,35,45] to replace or combine with the classic SIFT feature [23]. Generally, the performance of the initial retrieval results by simple comparison of visual feature may not be satisfactory. To refine it, many visual re-ranking techniques have been proposed [9,19,48].
Popular visual re-ranking techniques include query expansion, geometric context verification, kNNbased re-ranking, and diffusion-based methods, etc. Query Expansion (QE) [9,10,39,34,30] computes an average feature of the query and the top-ranked images to update the original query feature, which is then used for a second-round retrieval. Geometric Context Verification (GCV) [30,12,20,2] leverages the geometric context of local features to remove the false matches in the original results. Besides, if two images belong to the k-reciprocal nearest neighbors (kNN) of each other, these two images have a high probability of being relevant. Based on this observation, lots of k-Nearest Neighbors (kNN) based re-ranking methods thus emerge and achieve outstanding performance [19,48,50]. Diffusion-based methods [51,11,18] consider the global similarity of all images and perform similarity propagation iteratively. Most of the above methods do not involve training, thus can be quickly equipped with various features. The recent learning-based methods such as LAttQE [16] and GSS [22], achieve better performance but require training a specific model for each kind of feature. Different from the methods mentioned above, in this paper, we propose a novel visual re-ranking method by contextual information aggregation. The initial retrieval results generated by feature comparison only consider pairwise image similarity, but ignore the rich contextual information contained in the ranking list. As illustrated in [29], if two images are mutually relevant, they share similar distances from a set of anchor images. Thus, we directly select the top-L retrieval results as anchors for each query to fully model the contextual information in the ranking list. We define an affinity feature for each image in top-K candidates by computing the similarity between it and the anchor images. To further promote the re-ranking quality, we propose a new data augmentation method.
Moreover, inspired by Query Expansion (QE) which employs the information of top-ranked images to update the query feature, we propose to update affinity features of each top-K candidates by aggregating the affinity features of other candidates to promote the re-ranking performance with transformer encoder [46]. For each image in the top-K candidates, our re-ranking model dynamically aggregates the affinity features of other candidates based on the importance between candidates by computing their similarities using the affinity features. The output of our re-ranking model can be regarded as the refined affinity features for top-K candidates which contain more contextual information.
To train the re-ranking model, two loss functions are introduced. Firstly, we use a contrastive loss to restrain the updated affinity features so that the relevant images have large similarity, and vice versa. Besides, we exploit a Mean Squared Error (MSE) loss to reserve the information in original affinity features by restricting the difference between the original affinity features and the refined affinity features. During the inference time, we compute the affinity features for the top-K candidates and utilize the transformer encoder to refine the features. Then we re-rank these candidates by computing the cosine similarity between the refined affinity features. The rank of images outside the top-K ranking list remains unchanged.
Note that our re-ranking model is not directly involved with the original visual feature. Instead, it computes the affinity features for top-K images, which serve as the input in our method. Therefore, it can be combined with various existing image retrieval algorithms including representation learning and re-ranking methods, and further enhance the retrieval performance with low computational overhead. We conduct comprehensive experiments on four benchmark datasets to prove the generality and effectiveness of our proposed visual re-ranking method. Besides, the time and memory complexity of our re-ranking method is lower than the state-of-the-art re-ranking methods.

Related Work
In this section, we review the related works on visual re-ranking including query expansion, geometric context verification, kNN based methods, and diffusion-based methods.
Query Expansion. Query Expansion (QE) uses the information of the top-ranked images obtained from the initial retrieval to refine the representation of the original query for further retrieval. Average query expansion (AQE) [9] aggregates the features of top-K retrieval results by average pooling. Average query expansion with decay (AQEwD) [15] proposes a weighted average aggregation, where the weights decay over the rank of retrieved images. Discriminative query expansion (DQE) [1] regards the top-ranked images as positive images, and regards the bottom-ranked images as negative images to train a linear SVM. Then DQE sorts images according to their signed distance from the decision boundary. In [34], α-weighted query expansion (αQE) weights the top-K images by their  Figure 1: The pipeline of our method. In the first retrieval stage marked in blue, given a query, we perform the first-round retrieval to get the initial ranking list. In the second stage marked in green, we first obtain the affinity features for the query (orange cuboid) and top-K candidates (blue cuboids) with top L images as anchor images. The transformer encoder is used to refine the affinity features. The network is trained by minimizing the contrastive loss and MSE loss using the refined affinity features. In the re-ranking phase marked in orange, we recalculate the similarity scores between the query and the top K candidates using the refined affinity features. Best viewed in color. cosine similarity with the query. LAttQE [16] proposes an attention-based model to learn the weights of aggregation.

First Retrieval Stage
Geometric Context Verification. Geometric Context Verification uses the geometric context of local features to remove the false matches. Some approaches [9,30,37] estimate the transformation model to verify the local correspondences by RANSAC-based methods. RANSAC [12] generates hypotheses on random sets of correspondences and then identifies a geometric model with maximum inliers. Spatial coding [52] proposes to represent the relative spatial locations among local features into binary maps for efficient local matching verification. DSM [40] leverages the MSER regions which are detected on the activation maps of the convolutional layer. Then DSM regards these regions as local features for spatial verification.
k-NN-based Re-ranking. The k-reciprocal nearest neighbors of an image are considered as highly relevant candidates [49,32,39]. Contextual Dissimilarity Measure (CDM) [19] iteratively regularizes the average distance of each point to its neighbors to update the similarity matrix. Visual Rank [48] determines the centrality of nodes on a similarity graph according to the link structures among images to rank images. In CRL [27], a lightweight CNN model is trained to explore the contextual information and learn the relevance between images. GSS [22] proposes an unsupervised method for re-ranking based on graph neural network neighbor encoding and pairwise similarity separation loss. In [50], the k-reciprocal feature is designed by encoding the k-reciprocal nearest neighbors into a single vector to perform re-ranking.
Diffusion-based Re-ranking. Diffusion technique is initially designed for ranking on manifolds [51], and it has been successfully applied to many computer vision tasks, such as image classification, object detection, image retrieval, etc. In image retrieval, a lot of research concentrates on propagating similarity through the kNN graph [11]. Diffusion is usually used as a re-ranking method, and it has achieved state-of-the-art performance on many benchmarks [28,47,5,18,33,8,7,6,13,28]. Diffusion considers the underlying manifold structure and explores the internal relationships between images. As one of the representative methods, DFS [18] proposes a regional diffusion mechanism to further improve the recall of small objects based on the neighborhood graphs. Then it employs conjugate gradient method to compute the closed-form solution of diffusion as well as maintaining time efficiency and accuracy.

Framework Overview
In image retrieval, the database is defined as D = {I 1 , I 2 , · · · , I N }, where I i denotes the ith database image and N is the database size. Usually, images are first mapped to high-dimensional vectors through a feature extractor φ(·). We define the feature representation of images as f = φ(I) ∈ R d . Given a query, we obtain an initial ranking list of the top-K images R = [r 1 , r 2 , · · · , r K ] by a retrieval algorithm, where r i denotes the ID of the ith image. For convenience of the following discussion, we assume the query image is returned at the first position in the ranking list, otherwise we directly insert it in the front of the ranking list. The features of top-K images in the ranking list are described as Our framework is shown in Fig. 1. With the initial retrieval ranking list obtained by a query, we propose to represent each of the top-K candidates into an affinity feature vector by computing the cosine similarity between it and a set of anchor images. Then the affinity features are refined by a transformer encoder to aggregate the contextual information in the ranking list.
Affinity Feature. Generally, if two images are relevant to the query, they shall be relevant to each other [43]. Moreover, as revealed in [29], if two images are mutually relevant, their distances to a set of pre-defined anchor images shall be similar. Actually, it is a non-trivial issue to select a proper set of images as anchors. Generally, if the selected anchor images are far from the top-K candidates in the ranking list, the variance of its distance with candidates is relatively small, which is difficult to provide useful information to distinguish the candidates. In other words, a better alternative is to choose the top-L images in ranking list as the anchor images. With anchor images, we define the affinity features for the ith image in the rank list R as follows: After that, we take the affinity features of the K images in R as a sequence, which is fed into our re-ranking model for refinement. Note that the input of our proposed method is affinity feature sequence and is not directly related to the original feature, which endows our method with good generality.
Contextual Similarity Aggregation with Transformer. Although the affinity features have taken into account the contextual information in the ranking list, there may be inconsistency in the initial affinity features obtained by directly comparing with anchor images. In order to make the affinity features of related images more consistent, we propose a new re-ranking model by contextual information aggregation to dynamically refine the affinity features of different images. Specifically, with transformer encoder as the core component of our re-ranking model, we first map the affinity feature a i ∈ R L for the ith image to a ∈ R L using a learnable projection matrix W p ∈ R L×L , and then feed the sequence a i , i = 1, 2, · · · , K into a transformer encoder consisting of Multi-Head Attention (MHA) and Feed-Forward Networks (FFNs).
In MHA, each sequence element is updated by a weighted sum of all other elements based on the scaled dot-product similarity. The scaled dot-product attention first maps affinity features a i (i = 1, 2, · · · , K) to Queries (Q ∈ R K×ds ), Keys (K ∈ R K×ds ) and Values (V ∈ R K×ds ) with three learnable projection matrices. After that, the similarity between Q and K is aggregated with V together, which can be seen as using the similarity between images as weights to aggregate affinity features. The multi-head structure concatenates and fuses the outputs of multiple scaled dot-product attention modules using the learnable projection W M . MHA is defined as follows: where and N H is the head number. Note that to update the affinity feature of an image, the affinity features of all the relevant candidates should be considered as contextual information. A single-head self-attention layer limits the ability of the model to focus on one or more relevant candidates simultaneously without affecting other equally important candidates. This can be achieved by projecting the original affinity features into different representation subspaces. Specifically, in MHA, different projection matrices for Q, K, and V are used for different heads, and these matrices can project affinity features into different subspaces. The output is normalized via Layer Normalization (LN) and finally added to S to form a residue connection, In addition to MHA, the transformer encoder layer has a position-wise feed-forward network.
We stack n transformer encoder layers to obtain more consistent affinity features. The refined affinity features y i , i = 1, 2, · · · , K come from the output of the last layer of our re-ranking model.
Data Augmentation. According to the description above, we represent the top-K images into affinity features, which serve as the input to our model. To improve the robustness of the re-ranking model and avoid overfitting, it is necessary to increase the size of the training sets. To this end, we design a data augmentation scheme oriented to our framework.
Considering that our training data comes from retrieval results, we propose to use different visual features to obtain the ranking lists of the same query. With different types of features to create the affinity features, the network will learn more information about the contextual information. For a query, we employ M different visual feature extractors {φ(·) 1 , φ(·) 2 , · · · , φ(·) M } to obtain different ranking lists, and compute their corresponding affinity features according to the previous section.
The obtained M affinity feature sequences for the same query are used as training samples. In this way, we enlarge the training set size to M times of the original size and improve the robustness of our model.

Objective Functions
Contrastive Loss. The relevant images should have larger cosine similarity and vice versa, thus we design a contrastive loss for representation learning, which is defined as follows: with the cosine similarity: where · is L 2 norm, 1(·) is the indicator function, τ is a temperature hyper-parameter, and y 1 is the refined affinity feature of the query because we assume that query is on the top of the ranking list.
The output affinity features of other images in ranking list are represented as y i , 2 ≤ i ≤ K. In the numerator, the sum is over relevant images, and in the denominator, the sum is over all top-K images in the ranking list. Contrastive loss is minimized when query is similar to its relevant images and dissimilar to all other irrelevant images.

MSE Loss.
In order to preserve the information contained in the original affinity features, we propose to use a Mean Squared Error (MSE) loss between the original affinity features and the refined affinity features. MSE loss is defined as follows: where s i and y i is the original and refined affinity feature for the ith candidate, respectively. The Multilayer Perceptron (MLP) containing two layers with GELU non-linearity projects the refined affinity features back to the original affinity feature space to compute the MSE loss.
Combining Eq. (6) and Eq. (8), we define the final objective function of the proposed method as follows: where λ is a hyper-parameter to indicate the importance of MSE loss.

Re-ranking Processing
To aggregate the contextual information, we represent the top-K images into affinity features and refine them by the transformer encoder. Because of the assumption that the query is at the first position of the ranking list, we compute its similarity with the ith image in ranking list in R using the refined affinity features as follows: s i = sim(y 1 , y i ), i = 1, 2, · · · , K. (10) Finally, all the K images in the initial ranking list R are re-ranked by their new similarity score defined in Eq. (10) in descending order. The order of the remaining images which is out of top-K remains unchanged. Table 1: The re-ranking latency and retrieval accuracy of our method at different re-ranking lengths K on ROxf and RPar datasets. The initial retrieval is denoted as R-GeM, which is the baseline in our experiments. Anchor images list length L = 512.

Method
Re-ranking latency (ms)  Image Representation. We extract global visual features for both the query and database images using a ResNet101 [17] backbone with GeM pooling [34]. The best-performing model fine-tuned on the GL18 [25] is used. The resulting feature is denoted as R-GeM. To verify the robustness of our method when the training and testing sets are represented by different features, we also utilize other four models to extract testing image features: the off-the-shelf version of ResNet101 with R-MAC pooling [44], the off-the-shelf version of ResNet101 with GeM pooling, the fine-tuned version of ResNet101 with Max pooling [44], and the fine-tuned version of VGG16 [41] with GeM pooling.
Evaluation Datasets and Metrics. Four image retrieval benchmark datasets, named Revisited Oxford5k (ROxf), Revisted Paris6k (RPar), ROxf + R1M, and RPar + R1M, are used to evaluate our method. The ROxf [33] and RPar [33] datasets are the revisited version of the original Oxford5k [30] and Paris6k datasets [31]. These two datasets both contain 70 query images depicting buildings, and additionally include 4,993 and 6,322 database images, respectively. ROxf + R1M and RPar + R1M are the large-scale versions of ROxf and RPar which combine a set of 1M distractor images with the small ones. Mean Average Precision (mAP) [30] is used to evaluate the performance. We report the Medium and Hard performance of the four datasets mentioned above. The computation is performed on a single 2080Ti GPU.
Training Details. rSfM120k [34] is used to create training samples. It includes images selected from 3D reconstructions of landmarks and city scenes. In total, 91,642 images from 551 3D models are used for training. Each image in the training set is considered as a query image, and the others are database images. The first-round retrieval results of each query form a training sample. For each query image, the image with the same 3D reconstruction cluster id is considered as a positive sample and vice versa as a negative sample. We select the top-512 returned images for each query image to form a training sample and select the top-512 images as anchor images for computing the affinity features. To realize data augmentation, we extract the training image features using multiple models. Specifically, for each image in the training set, we extract features using fine-tuned Resnet50, Resnet101, and Resnet152 with GeM pooling, respectively, to construct multiple different affinity features. We denote the training set with data augmentation as AugrSfM120k.
Our model consists of a stack of 2 transformer encoder layers, each with 12 heads of 64 dimensions. The fully connected layers within the encoder layers have 4 times more dimensions than the hidden dimension. SGD is used to optimize the model, with an initial learning rate of 0.1, a weight decay of 10 −5 , and a momentum of 0.9. We use a cosine scheduler to gradually decay the learning rate to 0. The temperature in Eq. (6) is set as 2.0. The batch size is set to 256. The model is trained for 100 epochs on four 2080Ti GPUs.

Ablation Study
Re-ranking Length. In our method, we re-rank the initial top-K images of the ranking list and keep the order of the remaining images unchanged. For training, we select the fixed-length top-512 results as training samples. Since our transformer encoder involves no position embedding and the input length of the model is variable, we can change the length of the re-ranking during testing. The re-ranking performance of different K on ROxf and RPar and the corresponding time required are shown in Table 1. The results show that the performance of re-ranking keeps improving as K increases, and the performance starts to saturate after K is larger than 1024. For practical applications, we can take a trade-off between accuracy and latency time of re-ranking. [O]: Off-the-shelf networks pretrained on ImageNet; RMAC: regional max-pooling [44]; GeM: generalized-mean pooling [34]; MAC: max-pooling [44]. Length of Anchor Images List. Our method updates the affinity features to capture the contextual information in the ranking list, and the choice of anchor images plays a key role. We select the top-L images of the returned list as the anchor images for each query. Table 2 shows the effect of different anchor image lengths. The re-ranking achieves a large improvement relative to the baseline for all settings. When L is small, it limits the expressiveness of the affinity vector, and conversely when L is large, the proportion of images associated with the query image is too small, introducing a lot of noisy anchor images and limiting the discriminative power of the model. When L = 512, the best or competitive performance is achieved on all datasets.

Method
Model Variants. In Figure 2, we show the impact of different model variants on the retrieval performance. The optimal performance is achieved when the transformer depth is equal to 2 and the hidden layer dimension is 1024. As seen in Figure 2 self-attention module and is simply a stack of fully connected layers, at which point the performance is lower than the baseline features, highlighting how important the self-attention is for our model. Figure 2(b) shows that the model performance rises and then falls as the model capacity increases. This can be attributed to the overfitting of the model.

MSE Loss.
The effect of the MSE loss on the model performance is shown in Figure 2(c). It can be seen that as λ increases, the performance gradually rises and reaches the highest when λ = 0.2. An excessively large λ makes the model learning be dominated by the MSE loss and the performance decreases.
Dataset augmentation. As shown in Table 3, when using data augmentation, we can increase the training set to three times the original size, achieving higher performance relative to the baseline for the model trained without data augmentation. The re-ranking setting is the same as the compared methods which uses ResNet101-GeM feature to perform retrieval and re-rank using our trained model.

Cross Feature Testing
Our method just requires the affinity feature generated by comparing the image with anchor images, and is not directly related to the original feature. It can be accomplished with different visual features. We use fine-tuned R-GeM feature for the first-round retrieval and compute the affinity features for top candidates to train the re-ranking model. Then we test our model on various (type of features, fine-tuned or not) features. The performance of our method for different testing features is shown in Table 4. It obtains a large improvement relative to the baseline in several settings.

4.4
Comparison with the state-of-the-art methods mAP Comparison. Table 5 reports the performance of our method and different compared methods on ROxf, RPar, ROxf + R1M, RPar + R1M. We compare our method with the following methods: QE and its variants as well as Database Augmentation (DBA), DSM [40], CRL [27], GSS [22], and DFS [11]. In Table 5 , if the visual feature in the first-round retrieval of comparison methods in the original paper is the same with our feature, we directly use the results in the corresponding paper. For example, the results in the second and the third blocks in Table 5 are copied from LAttQE [16]. While in the fourth block in Table 5, the visual features of comparison methods in their original paper are different from our feature. Therefore, we re-test DSM [40] and DFS [11], re-train GSS [22] with our feature by the released code for fair comparison. As for CRL [27], we re-implement it with our features by our own.
The proposed re-ranking method achieves higher performance than most of the compared methods in all settings. Our method obtains better performance compared with LAttQE [16], which is the stateof-the-art method among QE-based methods. DFS [18] and GSS [22] can achieve better performance than ours in some settings since they utilize all database images for re-ranking but inevitably incur expensive extra time costs when the database size is large. We further combine DFS and GSS with our re-ranking approach, i.e., we apply our re-ranking approach to the list of retrieved results based on DFS or GSS re-ranking and the retrieval performance is further improved. Notably, when using  data augmentation, we can achieve higher performance relative to the baseline for the model trained without data augmentation. We show some successful cases and failed cases of our method on ROxf dataset in Figure 3.
Speed and Memory Costs. In Table 6, we present the complexity of the different methods in time and space as well as the measured average re-ranking latency (ms) and the total memory overhead required on the ROxf + R1M, and RPar + R1M datasets. In terms of spatial complexity, both our method and the QE-based method [34] only involve the top-K initial returned images. Differently, DFS [18] needs to encode the neighbor information between database images, resulting in an overhead to store the neighbor graph. As for GSS [34], it requires the neighbor relationship to update the features of the query image. Besides, since it involves the GCN network, the updated features cannot be used to calculate the distance directly with the original features of the database images. So additional storage of the updated features of the database images is required.
As for time complexity, DFS performs iterative operations on the top-K returned candidates (generally K = 10, 000, with over 10 iterations). QE-based methods and GSS need to first update the query features and then perform a second-round retrieval, which leads to larger latency when the size of the database becomes larger. Our method needs to firstly calculate the similarity between the top-K returned candidates and the L anchor images (usually L = 512, K = 512), and then use transformer encoder to generate the features, leading to a secondary complexity about K. Besides, the computation complexity of our method does not increase as the size of the database grows.

Conclusion
In this paper, we propose a novel visual re-ranking method for instance image retrieval. We represent the top-K images in the ranking list with affinity features according to the top-L anchor images. In order to explore the contextual similarity information in the ranking list, we design a self-attention reranking model, which updates the affinity features for re-ranking. Besides, our method is robust to the retrieval algorithm based on other image feature representation since the input of our re-ranking model is not directly related to the original image features. We further propose a data augmentation method to improve the robustness of the re-ranking model and avoid overfitting. Extensive experiments on four datasets show that our method achieves promising results compared with existing state-of-the-art methods in terms of both retrieval performance and computational time.