A long-tail image recognition method based on counterfactual attention modulation

By using the category perception and counterfactual attention modulation branches in the counterfactual attention modulation framework, the problem of class imbalance bias in long-tail image recognition is solved, improving the recognition effect of tail categories and reducing computational complexity.

CN123181897APending Publication Date: 2026-11-27BEIJING UNIV OF TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611186818.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-06
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

In existing technologies for long-tail image recognition, the model exhibits bias in the feature extraction process for a few head categories, resulting in poor tail category recognition performance. Furthermore, existing modulation mechanisms have failed to effectively mitigate class imbalance bias.

Method used

We employ a counterfactual attention modulation (CAM) framework, which modulates class-level and sample-level biases through a category-aware attention modulation branch (C1AM) and a counterfactual category attention modulation branch (C2AM), respectively. Combined with an auxiliary classifier and a dual-logistic adjustment strategy, we achieve feature calibration and attention focus.

Benefits of technology

It effectively alleviates the dominance of head categories in the feature representation space, improves the recall and recognition accuracy of tail categories, and reduces the computational complexity of model inference, demonstrating good robustness and applicability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123181897A_ABST
    Figure CN123181897A_ABST
Patent Text Reader

Abstract

The application discloses a long-tail image recognition method based on counterfactual attention modulation, and belongs to the technical field of computer vision and image recognition. The method obtains an image training dataset in a long-tail distribution, pre-trains a convolutional neural network or a residual network backbone, and embeds a counterfactual attention modulation module composed of a category-aware attention modulation branch C1AM and a counterfactual category attention modulation branch C2AM in a preset residual layer. The C1AM branch calibrates an original feature map channel by channel through compression, excitation and category modulation vectors; the C2AM branch maintains a category prototype, constructs a confusion matrix and selects an easily confused category. The application can reduce the per-class modulation calculation overhead while improving the recall rate of tail categories and the long-tail image recognition accuracy.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention is applicable to long-tail image recognition in the field of computer vision, and particularly relates to a long-tail image recognition method based on counterfactual attention modulation. Background Technology

[0002] Deep learning has achieved remarkable results in image recognition, mainly thanks to well-organized and evenly distributed datasets. However, real-world data often exhibits a long-tail distribution: a small number of head categories occupy the vast majority of samples, while numerous tail categories have only a few samples. This extreme data imbalance can shift the decision boundary, interfere with the feature representation space, and ultimately lead to a decline in the model's recognition performance in a few categories.

[0003] To address this type of data distribution imbalance problem, various research approaches have been proposed, including data resampling, class balancing loss weight adjustment, decoupled training, and multi-expert ensemble models. While these methods have shown some effectiveness in practical applications, they mostly optimize only at the data statistics or loss target level and assume that the backbone network can extract unbiased features. In reality, the raw features extracted by the network often contain biases introduced by the head class, which limits the effectiveness of subsequent classifier calibration.

[0004] Researchers have found that assigning different weights to the original feature map is an effective way to repair damaged feature responses. Methods such as Compressed Excitation Network (SENet), Convolutional Block Attention Module (CBAM), and Feature-by-Feature Linear Modulation (FiLM) all belong to modulation mechanisms, and their technical designs are as follows: Figure 1 As shown in (a), (a+b), and (c), modulation is a type of operation that selectively aggregates context along different dimensions, according to relevant research. For example, the Compressed Excitation Network (SENet) learns to assign greater weights to important channels by modeling the correlations between channels. Unlike attention mechanisms, modulation transforms the attention pattern from passive perception to active adjustment. Modulation methods are now widely used in balanced dataset scenarios, such as hybrid networks of convolutional neural networks and Transformers, and multimodal optimization. However, for long-tail recognition tasks, how to design modulation mechanisms to mitigate rather than exacerbate class imbalance bias remains a challenge.

[0005] Research related to DirMixE indicates that variations in the test set label distribution can be categorized into global and local levels. MEDC research shows that in long-tail image recognition tasks, class imbalance bias stems from the difference between inter-class and intra-class distributions. This invention defines these two types of bias as class-level bias and sample-level bias, respectively.

[0006] Category-level bias is caused by differences in the number of samples in each category and the differences in the distribution of category boundaries;

[0007] Sample-level bias arises from the heterogeneity of samples within the same category due to differences in pose, viewpoint, and background, and this heterogeneity is further amplified in imbalanced datasets.

[0008] Based on the above analysis, a feasible approach to mitigating imbalance bias using modulation mechanisms is to separate the two types of bias and address them one by one. This invention proposes a unified framework called Counterfactual Attention Modulator (CAM), which designs solutions for the two types of bias respectively: category-aware attention modulation and context-aware attention focusing.

[0009] To address category-level bias: Existing methods typically combine channel attention and spatial attention, such as Figure 1 As shown in (a) and (b), this approach balances the semantic distribution of different categories. However, such methods only learn attention weights based on data and do not introduce category-related constraints, thus failing to completely eliminate the problems caused by data distribution imbalance. To address this, Counterfactual Attention Modulation (CAM) sets up a separate category modulator for each category and constrains it to focus on internal category features, thereby achieving category-aware attention modulation. This approach faces the challenge of modulator selection during the model inference stage. Inspired by the logistic product adjustment method, this invention adds an auxiliary classifier, dividing the inference process into two stages: auxiliary logistic value evaluation and final logistic value evaluation. The logistic value is corrected based on the actual frequency of category occurrence, improving the generalization ability of long-tail categories.

[0010] To address sample-level bias: existing methods often rely on external conditions to achieve dynamic intervention and solve this problem, such as... Figure 1 As shown in (c), such schemes are highly dependent on contextual information. While contextual cues are suitable for visual reasoning tasks, they are difficult to adapt to visual classification tasks. To address this, this invention generates counterfactual sample attention to achieve context-aware attention focusing for each sample. This approach can extract sample-level semantic information of easily confused categories and decouple causal features from the main process of category-aware attention modulation.

[0011] CAM is a dual-branch plug-and-play framework comprising C1AM and C2AM branches, with technical designs such as... Figure 1As shown in (d), the C1AM branch learns an adjustable vector specific to each class and incorporates class prior information to dynamically recalibrate the feature map. This allows CAM to selectively activate the discriminative channels of specific classes. However, due to sample hierarchical bias, using only the C1AM branch exacerbates the entanglement between the target class and spurious associations. The C2AM branch constructs counterfactual samples and simulates contextual semantic shifts, allowing CAM to actively separate causal attention from interfering context. During the inference phase, CAM, combined with an auxiliary classifier and a dual-logistic adjustment strategy, improves tail-class recall while filtering noise through a conditional Top-K inference retrieval mechanism. CAM can be viewed as a coarse-to-fine attention modulation module. CAM can effectively separate invariant causal features from spurious associations in long-tailed distribution scenarios. Summary of the Invention

[0012] Existing resampling or decoupling methods mostly operate at the data end or classifier end. One of the objectives of this invention is to address the issue from the feature extraction stage by designing a category-aware attention modulation branch (C1AM). This branch assigns a dedicated modulator to each category, actively aligning attention features with the semantics of specific categories. By selectively activating the discriminative channels of specific categories, this effectively alleviates the dominance of the head category in the representation space and overcomes category-level bias.

[0013] To address the challenges of unknown true labels and high computational overhead in class-by-class modulation during the testing phase, this invention proposes an inference strategy based on an auxiliary classifier and dual logit adjustment. The aim is to eliminate head prediction bias through an initial "calibration," ensuring that tail categories successfully enter the Top-K candidate set, and then combine this with a "secondary calibration" to complete the final high-confidence prediction. This significantly reduces the computational complexity of model inference while effectively improving the recall rate of tail categories.

[0014] To address sample-level bias, another objective of this invention is to introduce a causal intervention mechanism. By designing a counterfactual category attention modulation branch (C2AM), counterfactual samples are dynamically generated using a confusion matrix and category prototypes to simulate highly confusing contextual shifts. This serves as a causal stress test, forcing the model to actively separate the target's true, invariant causal features from accidental, false background associations during the training of the main branch, thus achieving context-aware attention focus.

[0015] The ultimate goal of this invention is to construct a unified, lightweight dual-branch framework. By introducing a gradient separation strategy (cutting off the attention collapse path of the counterfactual branch and the interference path of the auxiliary classifier) ​​and consistency and diversity loss constraints, the counterfactual attention modulation module (CAM) can be seamlessly embedded into various existing long-tail recognition baseline models (such as LDAM-DRW, MiSLAS, etc.) with almost no additional computational overhead, comprehensively improving the robustness and recognition accuracy of the model in long-tail distribution scenarios.

[0016] The technical solution adopted in this invention is a long-tail image recognition method based on counterfactual attention modulation, comprising the following steps:

[0017] S1. Obtain an image training dataset with a long tail distribution, count the number of samples and frequency of empirical categories, and pre-train the backbone of a convolutional neural network or residual network based on the image training dataset to obtain a pre-trained backbone network.

[0018] S2, embedding a counterfactual attention modulation module into the preset residual layer of the pre-trained backbone network to construct a long-tailed image recognition network including a convolutional module, an auxiliary classifier, a standard residual layer, a counterfactual attention modulation layer, a global average pooling layer, and a final classifier. The counterfactual attention modulation module includes a category-aware attention modulation branch and a counterfactual category attention modulation branch. The two branches process the same input in parallel and cooperate with each other. The category-aware attention modulation branch is used to overcome category-level bias, and the counterfactual category attention modulation branch is used as a causal regularization term to overcome sample-level bias.

[0019] S3, input the sample image into the long-tail image recognition network, extract the original feature map, and perform compression and activation operations on the original feature map through the category-aware attention modulation branch to obtain the original attention weights; according to the category to which the sample belongs, call the corresponding learnable category modulation vector to modulate the original attention weights element by element to obtain the modulated attention weights, and multiply the modulated attention weights with the original feature map channel by channel to obtain the calibration feature map, thereby completing the attention calibration at the category-aware level;

[0020] S4, while the category-aware attention modulation branch calibrates the original feature map, the counterfactual category attention modulation branch maintains category prototypes for each category, constructs a confusion matrix based on the classification results of the pre-training stage, and determines the set of easily confused categories for the current sample based on the confusion matrix or a subset of categories with similar sampling frequencies; selects confusion category prototypes from the set of easily confused categories, and generates counterfactual samples based on the prototype offset between the current category prototype and the confusion category prototype, the counterfactual strength coefficient, and Gaussian noise. These counterfactual samples simulate the contextual semantic offset between the target category and the easily confused category, and are used to perform causal stress testing on the calibration results of the category-aware attention modulation branch.

[0021] S5, based on the original feature map, the calibration feature map, and the counterfactual samples, construct attention consistency loss, modulation attention consistency loss, and diversity loss, and combine them with classification loss and distillation loss to form the overall training objective; wherein, the attention consistency loss and the modulation attention consistency loss constrain the consistency between the original attention and the counterfactual attention, and between the modulation attention and the modulation counterfactual attention, respectively, forcing the category-aware attention modulation branch to actively separate causal features from spurious associations during training, and the diversity loss constrains the dispersion of the modulation attention to prevent attention collapse; during training, gradient separation is performed on the counterfactual attention link of the counterfactual category attention modulation branch and the interference link from the auxiliary classifier to the final classifier, cutting off the propagation path of the backward gradient to suppress attention collapse and reduce the bias interference of the auxiliary classifier on the final classifier;

[0022] S6. During the inference stage, since the true label is unknown, the modulation vector of the corresponding category cannot be directly called. First, the shallow features and the auxiliary classifier output auxiliary logical values, and the empirical category frequency of the training set is used to perform initial logical value calibration on the auxiliary logical values, thereby eliminating the prediction bias of the head category and ensuring that the tail category has the opportunity to be modulated subsequently.

[0023] S7: Select the top K candidate categories from the auxiliary logic values ​​after the initial calibration, call the corresponding category modulation vector for each candidate category, and perform K independent category-aware attention modulations on the same original feature map to obtain K candidate logic values. This reduces the huge computational overhead of traversing all categories to modulation only for K candidate categories.

[0024] S8, the empirical category frequency is used to perform secondary logic value calibration on the K candidate logic values ​​to further correct the prediction bias caused by the long-tail distribution, and the category with the highest confidence is selected from the calibrated candidate logic values ​​as the long-tail image recognition result of the image to be recognized, thereby completing the two-stage reasoning process from coarse-grained candidate category screening to fine-grained attention modulation.

[0025] Furthermore, the category-aware attention modulation branch employs a spatial global average pooling layer to perform compression operations; when performing activation operations, a bottleneck structure is used, sequentially passing through a first fully connected layer for dimensionality reduction, an activation function, a second fully connected layer to restore the original channel dimension, and another activation function to obtain the original attention weights; the original attention weights are then multiplied element-wise with the category modulation coefficients compressed to the range of zero to two by the hyperbolic tangent function to obtain the modulated attention weights; finally, the modulated attention weights are multiplied channel-wise with the original feature map to obtain the calibration feature map.

[0026] Furthermore, the update of the category prototype adopts the exponential moving average method. In each training round, the mean of the compressed features of the previous round prototype and the current batch of samples of that category are weighted and summed according to the momentum coefficient to achieve a smooth update of the category prototype.

[0027] Furthermore, the confusion matrix is ​​constructed after the pre-training phase, and each element of the matrix counts the number of samples in the training set whose true class is the row index and whose predicted class is the column index. For head classes or medium classes, the confusion matrix is ​​used to select the top K classes with the highest confusion level as the set of easily confused classes. For tail classes, a subset of classes with similar sampling frequencies is selected as the set of easily confused classes.

[0028] Furthermore, the counterfactual sample is generated by adding a weighted value of the difference between the current category prototype and the easily confused category prototype to the original compressed features of the sample, and then adding adaptive Gaussian noise to obtain the counterfactual sample; the counterfactual sample causes the original features to shift towards the decision boundary of the easily confused category, thereby simulating the attention response of the model in the counterfactual category environment.

[0029] Furthermore, the attention consistency loss constraint ensures that the original attention weights and counterfactual attention weights remain consistent across the channels with the strongest attention activation, preventing the model from deviating from causal feature extraction due to counterfactual interference; the modulation attention consistency loss constraint ensures that the modulated attention weights and modulated counterfactual attention weights remain consistent across the channels with the strongest modulation attention activation, focusing the modulated features on causal channels with invariance; the diversity loss constraint ensures that the standard deviation of the modulated attention weights is not lower than a preset boundary threshold, prompting the modulation module to selectively activate causal feature channels and suppress channels corresponding to false associations, preventing attention from collapsing into a constant vector.

[0030] Furthermore, the gradient separation includes: performing gradient separation on the backpropagation path of attention consistency loss and modulation attention consistency loss in the counterfactual category attention modulation branch, stopping the backpropagation of gradients to the attention collapse path of the counterfactual category attention modulation branch, and prompting the category-aware attention modulation branch to actively maintain the consistency of causal attention without being disturbed by the gradients of the counterfactual branch; performing gradient separation on the path from distillation loss to the final logical vector, cutting off the propagation path of the back gradient, enabling the auxiliary classifier to learn basic classification ability by relying on classification loss, while enabling the final classifier to play the role of teacher anchor point without parameter updates.

[0031] Furthermore, the initial logic value calibration involves subtracting the logarithm of the empirical category frequency from the auxiliary logic value to weaken the head category prediction bias present in the auxiliary logic value, thereby enabling the tail category to enter the candidate set for subsequent modulation.

[0032] Furthermore, the candidate category set is composed of the top K categories with the highest values ​​selected from the calibrated auxiliary logic values, and K is much smaller than the total number of categories; the candidate logic values ​​are calculated by passing the test samples through the standard residual layer and the counterfactual attention modulation layer in sequence, and then calling the corresponding category modulation vector to perform attention modulation for each candidate category in the candidate category set before outputting.

[0033] Furthermore, the secondary logic value calibration is to subtract the second calibration intensity parameter multiplied by the logarithm of the empirical category frequency from the candidate logic value to obtain the final calibration logic value; the final prediction category is selected by taking the maximum value in the logic value vector output by each candidate branch, and then selecting the category corresponding to the maximum value from all candidate branches as the final prediction result.

[0034] Compared with existing technologies, this invention achieves significant technical results on multiple long-tail recognition benchmark datasets by embedding a dual-branch attention modulation module consisting of a category-aware attention modulation branch and a counterfactual category attention modulation branch during the feature extraction stage. Specifically, this is reflected in the following aspects:

[0035] This invention enables the model to selectively activate the discriminative channels of each category by independently maintaining a learnable modulation vector for each category, thereby fundamentally alleviating the dominant role of the head category in the feature representation space.

[0036] This invention employs a counterfactual category attention modulation branch, dynamically generating counterfactual samples using a confusion matrix and category prototypes to simulate contextual semantic shifts between easily confused categories. It uses attention consistency loss and modulation attention consistency loss as constraints to force the model to actively decouple the invariant causal features of the target category from accidental background spurious associations during training. Visual analysis using gradient class activation mapping technology demonstrates that, after calibration using this method, the model's attention activation region refocuses from scattered background textures to the key foreground region of the target object, effectively correcting the false detection problem present in the baseline model and verifying the significant advantages of this invention at the feature decoupling level.

[0037] The counterfactual attention modulation module proposed in this invention is a two-stage plug-and-play architecture that can be seamlessly embedded into various mainstream long-tail recognition baseline models, including LDAM-DRW, Remix-FCC, MiSLAS, GLMC, LogitAdjust, and SSD. Without increasing additional computational overhead, this module can bring stable and consistent performance gains to different baseline models, demonstrating good model independence and versatility. Experimental results show that on the ImageNet-LT dataset, this invention improves the overall accuracy of the GLMC algorithm by 1.39%; on the iNaturalist2018 fine-grained dataset, this invention improves the overall accuracy of the LDAM-DRW algorithm by 1.88% and the overall accuracy of the SSD algorithm by 0.33%, further verifying the broad applicability of this invention under different network architectures and data scenarios.

[0038] This invention addresses the problems of unknown true labels and high computational overhead in the inference stage by designing a two-stage inference strategy involving an auxiliary classifier and dual logical value adjustment. First, auxiliary logical values ​​are output using shallow features, and initial calibration is performed based on empirical class frequencies, narrowing the candidate class range from all classes to the top K high-confidence classes. Then, refined attention modulation and secondary logical value calibration are performed only on the candidate classes. This strategy reduces computational complexity from a linear dependence on the total number of classes to a constant level, significantly reducing inference overhead while maintaining recall for tail-classes, achieving a good balance between recognition accuracy and computational efficiency.

[0039] This invention achieves unified governance of two core biases in long-tail recognition through the collaborative design of dual-branch parallel processing and gradient separation strategies. The category-aware attention modulation branch addresses category-level bias by independently modulating attention weights for each category using prior category information; the counterfactual category attention modulation branch addresses sample-level bias by forcing the model to suppress spurious associations within samples through counterfactual causal intervention. The two branches collaborate and constrain each other during training, avoiding the overcorrection problem that a single branch is prone to, and leveraging the complementary advantages of the two modulation strategies. Ultimately, this results in superior evaluation results compared to existing mainstream methods across multiple dimensions, including overall accuracy and individual accuracy for head, middle, and tail classes. Attached Figure Description

[0040] Figure 1 This is a comparison of modulation mechanisms. (a): Compressed-Excitation Network (SE) channel attention modulation. (a)+(b): Channel + Spatial Attention Modulation (CBAM). (c): Feature modulation method. (d): Category Attention Module (CAM).

[0041] Figure 2 This is the overall framework diagram of the CAM-ResNET32 model.

[0042] Figure 3 yes Figure 2 A comparison diagram of the internal structures of the Conv block and CAM block.

[0043] Figure 4 It is an attention modulator framework design.

[0044] Figure 5 The attention heatmap of some tail category samples was visualized using gradient class activation mapping. Detailed Implementation

[0045] The present invention will now be described in detail with reference to the accompanying drawings and embodiments.

[0046] This invention proposes a long-tail image recognition method based on counterfactual attention modulation (CFAM). The CAM block is inserted into a traditional convolutional neural network, consisting of two branches: C1AM and C2AM. C1AM implements class-aware attention modulation, assigning a learnable modulation vector to each class to alleviate the dominance of the head class on the model. C2AM constructs counterfactual samples on the prototype, effectively constraining the attention focus part in conjunction with the class-aware attention mechanism, thus mitigating the problem of spurious relevance. CAM effectively compensates for the shortcomings of traditional long-tail image recognition methods.

[0047] First, we define the task of long-tail recognition, and let the training dataset be... ,in Indicates the first Zhang Image For each of its corresponding real category labels, the total number of categories is Definition of the first The training subset of the class is The number of samples in this subset is denoted as The goal of long-tail recognition tasks is to identify categories with extremely imbalanced distributions (i.e.,...). training set Training the model In long-tail data scenarios, the number of samples in each category exhibits a long-tail distribution: a few head categories occupy the vast majority of the training data, while a large number of tail categories have only a small number of samples, which satisfies... To quantify the degree of data imbalance, this invention introduces the imbalance ratio (IR), which, referring to relevant literature, is defined as the ratio between the class with the largest number of samples and the class with the smallest number of samples. .

[0048] Figure 2 It demonstrates the overall framework of Counterfactual Attention Modulation (CAM), which is embedded in CNN networks. CAM is a two-stage plug-and-play fine-tuning process, typically built on a pre-trained backbone network (e.g., ResNet-32). Figure 2 This demonstrates the network architecture (denoted as "CAM-ResNet") resulting from the combination of CAM and ResNet-32 during the fine-tuning phase. This architecture includes convolutional modules. Lightweight auxiliary classifier Two standard residual layers ( Counterfactual attention modulation layer Global average pooling layer and the final classifier .set up For feature map Given the spatial dimensions and number of channels, the forward propagation process of CAM-ResNet can be represented as:

[0049]

[0050]

[0051] (1)

[0052]

[0053]

[0054] Among them, the auxiliary classifier Connected after a single convolutional module, it is used to output auxiliary logic values. Final classifier Responsible for outputting the final logical value Standard residual layer Depend on It consists of several convolutional modules, and a counterfactual attention modulation layer. Also includes There are several modules (each module can be a convolutional module or a CAM module), and the corresponding formulas are as follows:

[0055] (2)

[0056] (3)

[0057] in Representing the Each convolutional module, Represents the CAM module; express Each module within can be selected from two types. For example... Figure 3 As shown, each CAM module With standard convolutional modules The same residual structure is used, the difference being that the CAM module will be in the second... An attention modulation unit is embedded after the convolution operator.

[0058] like Figure 4 As shown, the attention modulation module adopts a two-branch structure: the category attention modulation branch (C1AM) and the counterfactual category attention modulation branch (C2AM). The first branch relies on the category-aware semantic prior to dynamically calibrate the channel-by-channel attention weights, ensuring that the model can achieve targeted feature extraction for both head and tail categories; the second branch serves as a causal regularization term, explicitly guiding the network to focus on causal channels with invariance, while mitigating the problem of spurious associations caused by the majority class.

[0059] In C1AM branch design, set The original feature map is used as the first... CAM module attention modulator The input formula is as follows:

[0060] (4)

[0061] in These are all standard computational units in the residual network module.

[0062] In the C1AM branch, let After compression operations With stimulus calculation Based on the design of the SENet network, compression operations are performed. Implemented using a spatial global average pooling layer; activation computation Using a bottleneck structure, the expression is: .in A dimensionality reduction coefficient was set for the dimensionality reduction layer. , Then restore the original channel dimensions. This yields the original attention weights. .

[0063] Subsequently, by combining residual connection methods, a learnable class modulation factor is utilized. Attention weights The dynamic modulation of element-wise multiplication is performed, and the corresponding formula is as follows:

[0064] (5)

[0065] (6)

[0066] in The labels are for the corresponding samples. This represents the modulated attention weights. Finally, the modulated attention weights are compared with... Perform channel-by-channel multiplication to obtain the calibration feature map. The calculation formula is:

[0067] (7)

[0068] To obtain modulated attention, this invention employs a hyperbolic tangent function. Smoothly compress unconstrained embedding vectors to intervals Internal. This mechanism allows the overall modulation coefficient to... Strictly limited to Within this range. This bounded residual design can retain the robust pre-trained features obtained from the first stage of training when the initial parameter values ​​approach zero; at the same time, when It can suppress spurious associations when This can strengthen the causal characteristics.

[0069] In the C2AM branch design, the aim is to achieve explicit causal intervention at the attention level, transforming the model from a passive observer to an active explorer. Traditional feature adjustment methods (such as FiLM) inevitably amplify spurious associations between the category head background and the label, while C2AM introduces counterfactual "hypothetical scenarios" testing. This method achieves stability through global prototyping, simulating the model's attention response in various counterfactual category environments, forcing the model to separate invariant causal features from the dominant environmental context.

[0070] (1) Update the category prototype

[0071] To construct a stable semantic reference for subsequent causal interventions, this invention provides each category with... Dynamically maintain a class prototype Let the current batch be... , No. The current batch sample set corresponding to the class is This invention employs the exponential moving average (EMA) method, at the [missing information - likely a date or time]. During rounds of training, the prototype of the category Perform a smooth update using the following formula:

[0072] (8)

[0073] in This is the momentum coefficient. This momentum-based accumulation strategy allows the global prototype to stably approximate the true class center throughout the training process, effectively alleviating the problem of excessive intra-class differences that is common in long-tailed distributions.

[0074] (2) Counterfactual sample generation (CG)

[0075] Subsequently, for each real category as samples This invention utilizes dimension as confusion matrix Filter out the most easily confused categories and denote the set of these categories as follows: The confusion matrix is ​​defined as follows:

[0076] (9)

[0077] This matrix is ​​constructed after the pre-training phase, where Representative sample The predicted labels are obtained after the pre-training phase. For broad or medium categories... This invention utilizes a confusion matrix Before clearly selecting There are several easily confused categories; however, for the tail categories, due to the influence of the head categories, the classification boundaries are blurred and the data distribution is compressed. Therefore, the easily confused category set is directly included. Set as a subset of categories with similar sampling frequencies (For example, all other tail categories). Sample The corresponding set of easily confused categories The formal definition of is:

[0078] (10)

[0079] in, The function returns the first largest value in the input set. The index corresponding to each element.

[0080] Determine the set of easily confused categories Subsequently, this invention constructs counterfactual samples. This allows for a targeted examination of attention mechanisms. The study found that for any given... Easily confused categories Current category prototype It contains the overall semantics of the real category, while easily confused category prototypes. This includes the overall semantics of easily confused categories. The difference between the two is... It can be viewed as a spoofing offset, which contains false environmental context information.

[0081] One straightforward way to construct counterfactual samples is to incorporate the offset into the original compressed features. This blurs the boundaries of classification decisions. Specifically, the present invention shifts samples toward easily confused decision boundaries, generating highly challenging counterfactual samples. The formula is as follows:

[0082] (11)

[0083] in, This is the counterfactual strength coefficient, used to control the magnitude of feature offset; For adaptive Gaussian noise, This is a noise scale parameter. Injected noise. It is an important feature-level data augmentation method. For tail class data with extremely few samples, this random perturbation can dynamically increase the intra-class variance in the latent space, avoiding the Class Activation Maps (CAM) from merely mechanically memorizing fixed and deterministic migration trajectories, while prompting the Class Activation Maps to follow a context-aware attention mechanism.

[0084] Obtain counterfactual samples Subsequently, this invention deliberately constructs a complex scenario to allow false associations to... The causal features exhibit a severe mismatch. Subsequently, this invention constrains the original features. Counterfactual samples Attention consistency between channels allows the model to focus on key feature channels.

[0085] This invention proposes three loss functions: attention consistency loss. Modulation of attentional consistency loss Diversity loss ,in The calculation formula is as follows:

[0086] (12)

[0087]

[0088]

[0089] In the formula, For original counterfactual attention, Weights for class-balanced loss; modulate attention consistency loss. The expression is:

[0090] (13)

[0091]

[0092]

[0093] in Represents modulated counterfactual attention; targeting modulated attention This invention introduces diversity loss. To alleviate the attention collapse problem, its expression is:

[0094] (14)

[0095] This loss introduces a preset boundary threshold. Compared to standard deviation, avoid modulating attention. The values ​​tend to be consistent. This constraint ensures that the attention distribution has a sufficient standard deviation, prompting the modulation module to selectively activate causal feature channels and suppress channels corresponding to spurious associations.

[0096] Training and Testing Methods: CAM-ResNet is a two-stage fine-tuning plugin. In the pre-training stage, this invention uses a long-tailed data baseline model based on residual networks to train the backbone network. In the fine-tuning stage, this invention freezes most of the parameters of the pre-trained backbone network while simultaneously adjusting the CAM-Res layers. and two classifiers Optimization is then performed. Specifically, the KL divergence knowledge distillation method is used, leveraging the already frozen final classifier. Training the auxiliary classifier This enables it to distinguish between categories. The process involves distillation loss... The formula is as follows:

[0097] (15)

[0098] in Auxiliary classifiers and the final classifier The predicted logical value, This is the temperature coefficient.

[0099] The overall objective loss function for the fine-tuning phase is:

[0100] (16)

[0101] in For classifying losses, The true label represents the one-hot encoding form. , , , All are weighting coefficients.

[0102] During training, this invention employs two gradient separation strategies, applied to the C2AM module and the auxiliary function, respectively. Affected by loss of attentional consistency and As a result, the C2AM branch will experience an "attention collapse" phenomenon, i.e., the attention matrix will collapse. The value of gradually approaches zero, or converges to a constant vector. To solve this problem, this invention targets the C2AM branch and... and Perform gradient separation operation (i.e., stop backpropagation, see details) Figure 2 and Figure 4 The dashed lines in the diagram are used to prevent attention collapse and encourage the C1AM branch to actively maintain the consistency of causal attention. Furthermore, since the model contains two classifiers, the auxiliary classifier... This will affect the final classifier This generates bias interference. Therefore, this invention addresses the discrimination loss. To the final logical vector The link implements another gradient separation strategy, completely cutting off the propagation path of the back gradient. This method ensures that the auxiliary classifier Relying on classification loss Learn basic classification skills, and at the same time enable the final classifier It serves as a stable, non-updated teacher anchor.

[0103] A key contradiction arises during the inference phase: the true label is unknown, but the category modifier... The calculation of the moderating coefficients requires a specified target category. If the entire network is simply iterated over each category one by one, the computational cost will increase exponentially with the total number of categories. It exhibits a linear doubling effect.

[0104] Due to the inherent long-tail distribution characteristics of the training data, the auxiliary logistic value This results in a significant bias towards head categories, leading to severe activation bias. Consequently, tail categories lose the opportunity to participate in subsequent counterfactual attention regulation early on. To address this issue, this invention employs a dual logical value adjustment mechanism.

[0105] For the test set Any test image in First, extract its shallow features. Then, this feature is input into a pre-trained auxiliary classifier. To obtain auxiliary logic values Referring to mature approaches to adjusting post-logic values, the initial calibration is performed using empirical category prior distributions, thus weakening the influence of... The inherent prediction bias results in a dimension of After calibration, auxiliary logic value The calculation formula is as follows:

[0106] (17)

[0107] In the formula Representative training set The empirical category frequencies obtained from the above statistics, parameters Used to control calibration intensity.

[0108] Subsequently, the first value with the highest auxiliary logic value after calibration was selected. 1 category, construct a candidate category set The calculation method is shown in the formula:

[0109] (18)

[0110] The set The number of elements satisfies .

[0111] Subsequently, the test sample matrix Input residual modules sequentially , and category attention module ,get Candidate logical values ,in It should be noted that the category attention layer used in the inference phase... There are two differences from the structure in the training phase: first, the cross-attention branch has been removed; second, due to the unknown labels of the test samples, shallow features... It needs to go through the modulation matrix corresponding to all candidate categories. .

[0112] To avoid long-tail categories in the mapping function In the softmax operation, the main category is covered. Therefore, this invention performs a secondary calibration operation to obtain the final calibration logic value. The calculation formula is as follows:

[0113] (19)

[0114] In the formula This is a hyperparameter. Finally, the maximum confidence score for each candidate branch is calculated, and the category with the highest confidence score after calibration is selected. The formula for the final prediction result is:

[0115] (20)

[0116] This two-stage logistic adjustment strategy splits the logistic evaluation into two stages and limits the predicted categories to a high-confidence candidate set. Internally, it can correct the distribution bias of the data itself, effectively improving the recognition accuracy of long-tail categories.

[0117] The model of this invention is implemented in the PyTorch framework and trained on an NVIDIA GeForce RTX 3090 with 24GB of VRAM. This invention conducts validation experiments on four classic long-tailed image recognition benchmark datasets: CIFAR-10-LT, CIFAR-100-LT, ImageNet-LT, and iNaturalist2018. The CIFAR-10 / 100-LT dataset is constructed by downsampling the original CIFAR dataset according to an exponential decay distribution. The experiments were conducted with imbalance ratios (IR) of 10, 50, and 100. ImageNet-LT is a large-scale truncated version of ImageNet-1K, containing 115,800 images across 1000 categories, with each category having a sample size ranging from 5 to 1300. iNaturalist2018 is a fine-grained dataset geared towards real-world scenarios, possessing a natural long-tailed data distribution characteristic, consisting of 8142 categories and 437,500 images.

[0118] CAM is a two-stage plug-and-play module. During the pre-training phase, CAM is compatible with various pre-trained models and can be integrated with mature long-tail recognition baseline algorithms such as LDAM-DRW, MiSLAS, and GLMC. Their backbone networks include ResNet32, ResNet50, or ResNext50. In the fine-tuning phase, the shallow network parameters are fixed, and stochastic gradient descent (SGD) is used to fine-tune the CAM module and the two classifiers (…). Fine-tuning was performed jointly. The model was trained for 30 epochs, with an initial learning rate of 0.001, which decayed using a cosine annealing strategy. The counterfactual noise coefficients met the following requirements. The normal distribution is followed. During the inference phase, to balance conditional classification accuracy and computational cost, the number of candidate classes in the CIFAR series datasets is set to... Number of candidate classes on large-scale datasets ImageNet-LT and iNaturalist2018 Choose 3 or 5. Additionally, after validation set grid optimization, the dual logic value correction parameter ( The empirical values ​​for ) are 0.2 and 0.3 respectively.

[0119] Referring to the standard evaluation scheme for long-tail identification, this invention reports the overall top-1 accuracy. To analyze the model's performance on data with different sample sizes in detail, this invention divides all categories into three non-overlapping subsets based on the training sample size: head class (samples > 100), middle class (samples between 20 and 100), and tail class (samples ≤ 20).

[0120] This invention compares and evaluates its performance against several mature long-tail recognition algorithms. These benchmark methods cover class-balanced reweighting and resampling (e.g., CB-Focal, BBN), two-stage decoupled training (e.g., cRT, MiSLAS), logistic correction techniques (e.g., LogitAdjust), and representation learning frameworks (e.g., PaCo, SSD, BCL, SHIKE). To verify the versatility and model independence of the CAM module, this invention embeds CAM into four representative benchmark network structures: LDAM-DRW, Remix-FCC, MiSLAS, and GLMC.

[0121] 1. Qualitative assessment

[0122] (1) Experimental results of CIFAR-10 / 100-LT

[0123] As shown in Table 1, combining CAM with any baseline method can consistently improve the model performance of various baseline algorithms under different imbalance ratio (IR) settings. For example, at an imbalance ratio... On the CIFAR-100-LT dataset, CAM improved the absolute accuracy of LDAM-DRW, Remix-FCC, MiSLAS, and GLMC by 3.86%, 3.48%, 1.38%, and 5.01%, respectively. Notably, the GLMC+CAM combination scheme... Under the given conditions, an overall accuracy of 60.89% was achieved, outperforming algorithms proposed in recent years such as ECL and CBTS. These performance improvements demonstrate that the attention-level causal intervention strategy proposed in this invention can bring complementary performance gains beyond traditional long-tail learning optimization schemes.

[0124] Table 1 Experimental results of the CIFAR-100 / 10-LT model based on ResNet32 network

[0125]

[0126] (2) Experimental results on the ImageNet-LT dataset

[0127] Table 2 presents the evaluation results on the large-scale ImageNet-LT dataset. Embedding the CAM module into four different baseline network structures significantly improved the model's performance on both mid-frequency subclasses and tail class subsets. Specifically, introducing CAM into the LDAM-DRW, GLMC, LogitAdjust, and SSD algorithms respectively increased tail class accuracy by 4.11%, 6.90%, 3.52%, and 3.74%, with overall accuracy increasing by 0.67%, 1.39%, 0.45%, and 1.42% respectively. Meanwhile, head class recognition accuracy slightly decreased, ranging from -1.39% to -3.60%. This phenomenon reflects the inherent bias-variance trade-off in long-tail recognition tasks, also known as the seesaw effect. Traditional models often rely on high-frequency invalid background association features to achieve excellent head class recognition performance, while CAM explicitly removes such background features, sacrificing the biased fitting ability of a small number of head classes to construct a more balanced and robust feature representation space for a few tail classes.

[0128] Table 2 shows the experimental results on the large-scale ImageNet-LT dataset.

[0129]

[0130] (3) Experimental results of the iNaturalist2018 dataset

[0131] For the fine-grained dataset iNaturalist2018, Table 3 shows that the CAM method can still effectively improve tail category recognition performance. Compared with the three benchmark algorithms LDAM-DRW, LogitAdjust, and SSD, CAM improves the overall accuracy by 1.88%, 1.02%, and 0.33%, respectively. While continuously optimizing tail category accuracy, head category accuracy only slightly decreases. After combining CAM with GLMC, the tail category accuracy increased from 73.01% to 73.50%, but the head category accuracy and overall accuracy declined (by -8.26% and -1.45%, respectively). This performance divergence stems from the characteristics of the dataset itself and the features of the GLMC algorithm architecture: the iNaturalist2018 dataset contains over eight thousand fine-grained categories with highly similar species characteristics, and the environmental details of the species are the key features for distinguishing each category. GLMC relies on pixel-level blending strategies and global-local spatial feature sharing mechanisms for modeling, while the causal intervention strategy proposed in this invention strictly constrains the model's dependence on background-related features. These two approaches conflict in their logic of utilizing spatial context features. CAM demonstrates stability on other benchmark models such as SSD and LogitAdjust, indicating that the aforementioned overcorrection problem only occurs in algorithm architectures that highly rely on spatial context fusion.

[0132] Table 3. Analysis results based on the fine-grained iNaturalist2018 dataset.

[0133]

[0134] 2. Subjective Results

[0135] To verify the feature calibration capability of CAM, Figure 5 Attention heatmaps for some tail-category samples were visualized using gradient class activation mapping. This invention selects two representative benchmark algorithms: LDAM-DRW and GLMC, and compares the corresponding algorithm models after fusing the CAM module. Experimental results show that, without calibration and optimization, the benchmark models have weak activation responses to the target object, and attention is often widely dispersed in the background region.

[0136] CAM can improve upon the aforementioned problems. At the category level, this method introduces category prior information, preventing tail categories from being influenced by the background information of the dominant head categories. From Figure 5The third and seventh columns show that CAM avoids the convergence of attention to indiscriminate background textures, refocuses on key foreground targets, and corrects the false detection problem of the original model. At the sample level, CAM does not adopt a uniform offset correction strategy, but dynamically suppresses interference noise unique to each image, highlighting the key targets specific to each sample. In summary, the visualization results confirm that CAM can simultaneously eliminate statistical bias in the category dimension and spatial interference in the sample dimension.

[0137] Figure 5 Visualization of attention maps for six tail category samples obtained using gradient-weighted class activation mapping. Each group has four columns from left to right: original image (ground truth label), attention map without CAM (predicted label), attention map with CAM (predicted label), and attention map difference. The left example is based on LDAM-DRW, and the right example is based on GLMC.

Claims

1. A long-tail image recognition method based on counterfactual attention modulation, characterized in that, Includes the following steps: S1. Obtain an image training dataset with a long tail distribution, count the number of samples and frequency of empirical categories, and pre-train the backbone of a convolutional neural network or residual network based on the image training dataset to obtain a pre-trained backbone network. S2, embedding a counterfactual attention modulation module into the preset residual layer of the pre-trained backbone network to construct a long-tailed image recognition network including a convolutional module, an auxiliary classifier, a standard residual layer, a counterfactual attention modulation layer, a global average pooling layer, and a final classifier. The counterfactual attention modulation module includes a category-aware attention modulation branch and a counterfactual category attention modulation branch. The two branches process the same input in parallel and cooperate with each other. The category-aware attention modulation branch is used to overcome category-level bias, and the counterfactual category attention modulation branch is used as a causal regularization term to overcome sample-level bias. S3, input the sample image into the long-tail image recognition network, extract the original feature map, and perform compression and activation operations on the original feature map through the category-aware attention modulation branch to obtain the original attention weights; Based on the category to which the sample belongs, the corresponding learnable category modulation vector is called, and the original attention weights are modulated element by element to obtain modulated attention weights. The modulated attention weights are then multiplied channel by channel with the original feature map to obtain a calibration feature map, thereby completing the attention calibration at the category perception level. S4, while the category-aware attention modulation branch calibrates the original feature map, the counterfactual category attention modulation branch maintains the category prototypes of each category, constructs a confusion matrix based on the classification results of the pre-training stage, and determines the set of easily confused categories of the current sample based on the confusion matrix or a subset of categories with similar sampling frequencies. Confusion category prototypes are selected from the set of easily confused categories. Counterfactual samples are generated based on the prototype offset between the current category prototype and the confusion category prototype, the counterfactual strength coefficient, and Gaussian noise. These counterfactual samples simulate the contextual semantic offset between the target category and the easily confused category and are used to perform causal stress testing on the calibration results of the category-aware attention modulation branch. S5, based on the original feature map, the calibration feature map, and the counterfactual samples, construct attention consistency loss, modulation attention consistency loss, and diversity loss, and combine them with classification loss and distillation loss to form the overall training objective; wherein, the attention consistency loss and the modulation attention consistency loss constrain the consistency between the original attention and the counterfactual attention, and between the modulation attention and the modulation counterfactual attention, respectively, forcing the category-aware attention modulation branch to actively separate causal features from spurious associations during training, and the diversity loss constrains the dispersion of the modulation attention to prevent attention collapse; during training, gradient separation is performed on the counterfactual attention link of the counterfactual category attention modulation branch and the interference link from the auxiliary classifier to the final classifier, cutting off the propagation path of the backward gradient to suppress attention collapse and reduce the bias interference of the auxiliary classifier on the final classifier; S6. During the inference stage, since the true label is unknown, the modulation vector of the corresponding category cannot be directly called. First, the shallow features and the auxiliary classifier output auxiliary logical values, and the empirical category frequency of the training set is used to perform initial logical value calibration on the auxiliary logical values, thereby eliminating the prediction bias of the head category and ensuring that the tail category has the opportunity to be modulated subsequently. S7: Select the top K candidate categories from the auxiliary logic values ​​after the initial calibration, call the corresponding category modulation vector for each candidate category, and perform K independent category-aware attention modulations on the same original feature map to obtain K candidate logic values. This reduces the huge computational overhead of traversing all categories to modulation only for K candidate categories. S8, the empirical category frequency is used to perform secondary logic value calibration on the K candidate logic values ​​to further correct the prediction bias caused by the long-tail distribution, and the category with the highest confidence is selected from the calibrated candidate logic values ​​as the long-tail image recognition result of the image to be recognized, thereby completing the two-stage reasoning process from coarse-grained candidate category screening to fine-grained attention modulation.

2. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The category-aware attention modulation branch employs a spatial global average pooling layer for compression operations and a bottleneck structure for activation operations. It sequentially passes through a first fully connected layer for dimensionality reduction, an activation function, a second fully connected layer to restore the original channel dimensions, and another activation function to obtain the original attention weights. These original attention weights are then multiplied element-wise with the category modulation coefficients compressed to the range of zero to two using a hyperbolic tangent function to obtain the modulated attention weights. Finally, the modulated attention weights are multiplied channel-wise with the original feature map to obtain the calibration feature map.

3. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The update of the category prototypes adopts the exponential moving average method. In each training round, the mean of the compressed features of the previous round prototypes and the current batch of samples of that category are weighted and summed according to the momentum coefficient to achieve a smooth update of the category prototypes.

4. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The confusion matrix is ​​constructed after the pre-training phase. Each element of the matrix counts the number of samples in the training set whose true class is the row index and whose predicted class is the column index. For head or medium classes, the confusion matrix is ​​used to select the top K classes with the highest confusion level as the set of easily confused classes. For tail classes, a subset of classes with similar sampling frequencies is selected as the set of easily confused classes.

5. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The counterfactual sample is generated by adding a weighted value of the difference between the current category prototype and the easily confused category prototype to the original compressed features of the sample, and then adding adaptive Gaussian noise to obtain the counterfactual sample. The counterfactual sample causes the original features to shift towards the decision boundary of the easily confused category, thereby simulating the attention response of the model in the counterfactual category environment.

6. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The attention consistency loss constraint ensures that the original attention weights and counterfactual attention weights remain consistent on the channels with the strongest attention activation, so that the model does not deviate from the causal feature extraction due to counterfactual interference. The modulation attention consistency loss constraint ensures that the modulation attention weights and modulation counterfactual attention weights remain consistent on the channels where modulation attention activation is strongest, so that the modulation features focus on causal channels with invariance; the diversity loss constraint ensures that the standard deviation of the modulation attention weights is not lower than a preset boundary threshold, so that the modulation module selectively activates causal feature channels and suppresses channels corresponding to false associations, preventing attention from collapsing into a constant vector.

7. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The gradient separation includes: performing gradient separation on the backpropagation path of attention consistency loss and modulation attention consistency loss in the counterfactual category attention modulation branch, stopping the backpropagation of gradients to the attention collapse path of the counterfactual category attention modulation branch, and prompting the category-aware attention modulation branch to actively maintain the consistency of causal attention without being disturbed by the gradients of the counterfactual branch; performing gradient separation on the path from distillation loss to the final logical vector, cutting off the propagation path of the back gradient, enabling the auxiliary classifier to learn basic classification ability by relying on classification loss, while enabling the final classifier to play the role of teacher anchor point without parameter updates.

8. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The initial logic value calibration involves subtracting the logarithm of the first calibration intensity parameter multiplied by the empirical category frequency from the auxiliary logic value. This reduces the head category prediction bias present in the auxiliary logic value, allowing the tail category to enter the candidate set for subsequent modulation.

9. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The candidate category set is composed of the top K categories with the highest values ​​selected from the calibrated auxiliary logic values, and K is much smaller than the total number of categories. The candidate logic values ​​are calculated by passing the test samples through the standard residual layer and the counterfactual attention modulation layer in sequence, and then calling the corresponding category modulation vector to perform attention modulation for each candidate category in the candidate category set before outputting.

10. The long-tail image recognition method based on counterfactual attention modulation according to claim 1, characterized in that, The secondary logic value calibration is to subtract the second calibration intensity parameter multiplied by the logarithm of the empirical category frequency from the candidate logic value to obtain the final calibration logic value; the final prediction category is selected by taking the maximum value in the logic value vector output by each candidate branch, and then selecting the category corresponding to the maximum value from all candidate branches as the final prediction result.