Power consumption anomaly detection method based on CLI replay attack

By employing a deep fusion approach of data isolation, hierarchical balanced sampling, and robust training, the problems of data credibility, class balance, and interpretability in CLI replay attack detection are solved, enabling accurate detection and interpretable decision-making in complex scenarios and improving the stability and robustness of the model.

CN122020458APending Publication Date: 2026-05-12TAIAN POWER SUPPLY CO OF STATE GRID SHANDONG ELECTRIC POWER CO
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
TAIAN POWER SUPPLY CO OF STATE GRID SHANDONG ELECTRIC POWER CO
Filing Date
2026-01-15
Publication Date
2026-05-12

AI Technical Summary

Technical Problem

Existing CLI replay attack detection methods suffer from collaborative bottlenecks in terms of data credibility, class balance, interpretability, and dynamic adaptability. They struggle to accurately detect a minority of attack classes in complex scenarios and lack traceable decision-making basis.

Method used

We employ a deep fusion approach that integrates data isolation, hierarchical balanced sampling, interpretable reasoning, and robust training. By preserving essential class differences through feature space-aware hierarchical undersampling, and combining dynamic rule optimization and composite perturbation enhancement, we achieve multi-model collaborative training and adversarial example generation, thereby improving the model's detection capabilities in complex scenarios.

Benefits of technology

While ensuring data isolation, it achieves accurate detection of a minority of attacks, provides interpretable decision-making basis, and maintains stable and efficient detection performance, adapting to complex adversarial environments.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122020458A_ABST
    Figure CN122020458A_ABST
Patent Text Reader

Abstract

The invention discloses a CLI replay attack-based electricity consumption anomaly detection method, which relates to the technical field of network security, and comprises the following steps: (1) data acquisition and preprocessing; (2) adaptively enhancing minority class samples; (3) data isolation and consistency verification; (4) multi-model cooperative training; (5) carrying out iteration processing on the difficult sample; (6) adversarial sample generation and robust training; (7) adaptively optimizing the threshold value; (8) joint reasoning of neural symbols; and (9) result prediction and evaluation: in the step (4), through a multi-model parallel training and prediction fusion mechanism, the system simultaneously has the modeling capability of a deep model for a complex feature interaction relationship and the stability of a traditional model in a small sample and unbalanced data scene, so that the overall accuracy and robustness of an anomaly detection result are improved, and the accuracy and robustness of the anomaly detection result are improved. According to the whole method, category essential differences are reserved through hierarchical under-sampling of feature space perception, dynamic rule optimization and composite disturbance enhancement are combined, it is ensured that the model can accurately capture minority class attacks in a complex scene, a traceable decision basis can be provided, meanwhile, stability and high efficiency of detection performance are maintained, and the method is suitable for large-scale popularization and application. The problem that an existing detection method is unbalanced in false alarm and missing alarm in a dynamic attack scene is effectively solved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of network security technology, specifically to a method for detecting abnormal power consumption based on CLI replay attacks. It is particularly suitable for achieving accurate and interpretable replay attack detection of CLI operations by integrating the perception capabilities of neural network models with the reasoning capabilities of symbolic rules. Background Technology

[0002] In the field of cybersecurity, command-line interface (CLI) replay attacks, which replicate the operation sequences of legitimate users to carry out masquerading and penetration, are a typical threat that bypasses static permission control and behavior baseline auditing. Existing detection methods mostly rely on deep neural networks to build end-to-end learning frameworks, using the model's ability to automatically extract high-dimensional features to identify abnormal patterns. Although a certain detection accuracy can be achieved on closed datasets, its black-box nature leads to a break in the logical chain of attack judgment. Security personnel find it difficult to know what key indicators the model uses to make decisions. This lack of interpretability not only weakens the feasibility of attack tracing and strategy optimization, but also hinders the compliance implementation of the model in key areas such as finance and energy due to the lack of audit evidence, exposing the inherent shortcomings of traditional data-driven methods at the level of security semantic understanding.

[0003] A deeper contradiction lies in the neglect of the reliability of the detection process and environmental adaptability in existing solutions. During the training phase, the lack of strict data isolation mechanisms often leads to implicit correlations between pre-training data and target test data, causing model evaluation results to deviate from real-world performance. Real-world command-line operation data generally suffers from significant class imbalance, with attack samples typically accounting for less than 15%. Traditional undersampling easily loses fine-grained features of the majority class, while oversampling introduces redundant noise, exacerbating overfitting. Although some studies have attempted to alleviate this problem by introducing stratified undersampling, these approaches mostly rely on shallow strategies of random sampling based on class proportions, without incorporating stratification logic based on feature space distribution. This results in the sampled data still failing to fully represent the diverse command patterns of normal samples and the fixed parameter characteristics of attack samples, limiting the model's ability to identify minority class attacks. Furthermore, when faced with noisy, overlapping, and adversarial perturbations in real-world data, single models are prone to overfitting or high false negative rates for low-frequency attack patterns, and their robustness drops sharply when faced with perturbations such as parameter fine-tuning and time interval jitter. Previous studies have attempted to alleviate the problem through model stacking or feature engineering, but failed to incorporate data isolation, interpretable reasoning, hierarchical undersampling, and robust training into a unified framework. As a result, the detection system still faces the dilemma of imbalance between false positives and false negatives in dynamic attack scenarios, making it difficult to achieve a synergistic improvement in security and reliability.

[0004] While existing technical solutions have mitigated the problem of inflated assessments through data isolation and attempted to improve interpretability through rules, they still fail to address three core contradictions: First, the class imbalance caused by the low proportion of attack samples in real data. Traditional undersampling, failing to consider feature space distribution, leads to the loss of key discriminative features in the sampled data, resulting in insufficient recall for minority class attacks. Second, the disconnect between interpretable reasoning and model training. Rule base updates lag behind the evolution of attack methods, and rule weights cannot be dynamically optimized through changes in sample distribution during training. Third, the weak generalization ability of enhancement and training strategies to complex perturbations. When faced with combined perturbations such as signal distortion caused by device heterogeneity and semi-reasonable attack sequences, the model's real-time performance and stability decline. Furthermore, the isolated operation of each module lacks a parameter linkage optimization mechanism, resulting in breakpoints in the data balance, feature learning, and decision interpretation links of the detection process. Summary of the Invention

[0005] This invention aims to overcome the collaborative bottlenecks of existing command-line replay attack detection methods in terms of data credibility, class balance, interpretability, and dynamic adaptation. It provides a power consumption anomaly detection method based on CLI replay attacks, which can achieve deep integration of data isolation, hierarchical balanced sampling, interpretable reasoning, and robust training. By preserving the essential differences between classes through hierarchical undersampling with feature space awareness, and combining dynamic rule optimization and composite perturbation enhancement, it ensures that the model can accurately capture minority class attacks in complex scenarios, provide traceable decision-making basis, and maintain stable and efficient detection performance.

[0006] To achieve the above-mentioned objectives, the technical solution adopted by this invention is as follows: A method for detecting abnormal electricity consumption based on CLI replay attack, comprising the following steps: (1) data acquisition and preprocessing; (2) adaptive enhancement of minority class samples; (3) data isolation and consistency verification; (4) multi-model collaborative training; (5) iterative processing of difficult samples; (6) adversarial sample generation and robust training; (7) threshold adaptive optimization; (8) neural symbol joint reasoning; and (9) result prediction and evaluation.

[0007] (1) Data acquisition and preprocessing: The dataset used is based on the State Grid Corporation of China (SGCC) electricity user consumption dataset, which contains daily time-series electricity consumption data for 42,374 electricity users from January 1, 2014 to October 31, 2016. This invention employs the following multi-stage data processing and feature construction method: Data missing value handling: To address the missing value problem in time-series electricity consumption data, a joint processing method combining numerical imputation and missing value indication is adopted. First, missing values ​​are imputed for the target numerical features based on the median strategy to ensure the robustness of the data distribution. At the same time, a corresponding missing value indication feature is constructed for each feature to explicitly identify the missing state in the original data. The imputed numerical features and missing value indication features are combined to form an extended feature representation containing both numerical information and missing pattern information, thereby improving the recognition capability of subsequent anomaly detection models without losing missing structural information. Original Time Series Feature Extraction: Multi-dimensional statistical features are extracted from the original daily electricity consumption sequence, including: Basic statistical features: average daily electricity consumption, standard deviation of electricity consumption, coefficient of variation, skewness, kurtosis; Periodic features: differences in electricity consumption patterns between weekdays and holidays, monthly electricity consumption trend slope, seasonality index; Frequency domain features; Abnormal fluctuation features: number of sudden increases / decreases in electricity consumption (more than 3 times the standard deviation), number of days with zero / low values, continuous abnormal patterns; Behavioral consistency features: Mahalanobis distance between the user's electricity consumption pattern and the baseline pattern of similar users. The feature extraction formulas are shown in Table 1.

[0008] (2) Adaptive enhancement of minority class samples: After feature construction is completed, statistical analysis is performed on the distribution of sample labels; when the proportion of abnormal samples is detected to be lower than a preset threshold, the minority class sample enhancement module is triggered. The preset threshold is set to a ratio of abnormal samples to normal samples of less than 1:3 to 1:50. The adaptive enhancement process includes adaptively selecting the sample enhancement method and enhancement intensity according to the distribution density, neighborhood structure and boundary relationship of abnormal samples in the feature space and normal samples. At least one of the following methods is used to generate synthetic abnormal samples to supplement the original abnormal sample distribution: sample interpolation generation based on neighborhood relationship, sample expansion based on local density awareness and sample generation based on feature perturbation. During the sample generation process, the number of synthetic samples is dynamically controlled according to the target class balance interval, and the validity of the generated synthetic samples is checked. Low-confidence samples that are abnormally far from the original abnormal samples or highly overlap with normal samples are removed, thereby alleviating the class imbalance problem while avoiding excessive generation of abnormal samples and improving the stability and generalization ability of subsequent model training.

[0009] (3) Dataset isolation and consistency verification: First, a duplicate detection method based on sample fingerprints is used to check the feature vector of each sample. The sample fingerprint vector is constructed by concatenating and encoding it with its label. Concatenate and encode to construct sample fingerprint vectors. Sample fingerprint values ​​are generated using a hash function. First, by comparing the consistency of fingerprint values ​​across different data subsets, the system detects whether there are completely duplicated or highly similar samples. When identical or similar fingerprint values ​​are detected, a data leakage risk is identified, and the data partitioning operation is re-executed. Second, a statistical distribution consistency detection method is used to model the statistical distribution of each feature dimension in the training, validation, and test sets, respectively. The similarity between the feature distributions of each data subset is determined by calculating the distance index between them. In one implementation, the Kullback-Leibler divergence (KL divergence) is used to analyze the distribution of the training set. Distribution with validation or test sets The measurement is defined by formula (1):

[0010] When the divergence value is lower than the preset distribution difference threshold, it is determined that there is abnormal distribution overlap between different data subsets, thereby triggering a re-division or manual verification process. Further, a cross-detection method based on feature space distance constraints is adopted to map the samples to the original feature space or the low-dimensional feature space after principal component analysis (PCA) dimensionality reduction. The Euclidean distance between samples across data subsets is calculated, defined by formula (2):

[0011] When there are sample pairs from different subsets of data whose distance is less than a preset distance threshold. If a sample pair is deemed highly similar in the feature space, posing a potential risk of information leakage, the relevant samples are removed or reassigned. By combining three methods—sample fingerprint hash detection, statistical distribution consistency test, and feature space distance constraint detection—multi-level verification of the independence between data subsets is performed. This ensures that the model training, validation, and testing processes are isolated from each other, improving the objectivity and credibility of the anomaly detection model evaluation results.

[0012] (4) Multi-model parallel training and prediction fusion: After completing data isolation and consistency verification, a multi-model parallel training and prediction fusion module is constructed based on the training data to fully utilize the complementary advantages of different models in feature modeling capabilities and generalization characteristics. Specifically, a deep learning-based tabular data modeling model and a traditional machine learning-based classification model are constructed respectively. The deep learning model uses FT-Transformer to perform high-order interactive modeling of sample features through feature embedding and multi-head self-attention mechanism; the traditional machine learning model uses multilayer perceptron (MLP) to capture the nonlinear discriminative relationship of features. For any sample , The predicted probability of an item belonging to the anomaly category is output after training the FT-Transformer model and is defined by formula (3):

[0013] Meanwhile, the corresponding anomaly prediction probability output by the MLP model is defined as formula (4):

[0014] After obtaining the prediction results from the base model, a probabilistic fusion method is used to integrate the outputs of each model. In one implementation, a weighted probabilistic fusion strategy is used, assigning weights to each model based on its performance metrics on the validation set. The resulting comprehensive anomaly score is:

[0015] in, This indicates that the k-th model is paired with the sample. The predicted probability, The corresponding model weights are set adaptively based on the model's F1 score, AUC value, or recall on the validation set. Through the above-mentioned multi-model parallel training and prediction fusion mechanism, the system simultaneously possesses the ability of deep models to model complex feature interactions and the stability of traditional models in small sample and imbalanced data scenarios, thereby improving the overall accuracy and robustness of anomaly detection results.

[0016] (5) Difficult Sample Identification and Iterative Enhancement: After completing the multi-model prediction fusion, a difficult sample identification and iterative enhancement mechanism is introduced to further improve the model's discrimination ability in the decision boundary region and complex abnormal samples. Specifically, based on the comprehensive anomaly probability output by the fusion model... Samples with high prediction uncertainty or those that are misclassified are identified as the hard sample set. For the sample... Its prediction uncertainty can be measured by its distance from the classification threshold:

[0017] when Less than the preset uncertainty threshold If the sample is then deemed a difficult sample, the prediction result is compared with the true label. Inconsistent samples are directly included in the difficult sample set.

[0018] For the aforementioned difficult samples, a data augmentation method based on local perturbation is employed to generate enhanced samples by applying controlled noise to the original feature space:

[0019] The generated enhanced samples are then added to the training set along with the original samples, and the model is retrained multiple times to gradually enhance its expressive ability in abnormal boundary regions.

[0020] (6) Adversarial Example Generation and Robust Training: To improve the model's robustness to unknown attack patterns and input perturbations, an adversarial training mechanism is introduced during the training process. Specifically, based on the loss function of the trained model... Adversarial examples are generated using the Fast Gradient Sign Method (FGSM), with the following perturbation form:

[0021] in, This represents the perturbation intensity coefficient. The adversarial samples and the original samples are jointly input into the model for training. The combined loss function (9) on the original samples and adversarial samples is minimized. This improves the model's stability and generalization ability when faced with input noise and malicious perturbations.

[0022] (7) Threshold Adaptive Optimization: After obtaining the anomaly prediction probability of the fusion model, a threshold adaptive optimization module is introduced to avoid performance degradation caused by using a fixed threshold. Specifically, the candidate threshold set is optimized on the validation set. Perform an iterative search and calculate the precision at each threshold. Recall rate And F1 score:

[0023] In satisfying the minimum recall constraint Given the given conditions, the threshold that maximizes the F1 score is chosen as the optimal classification threshold:

[0024] The optimal threshold Used in subsequent anomaly detection processes to achieve a dynamic optimal balance in detection performance.

[0025] (8) Neural Symbolic Joint Reasoning: Based on the model's prediction results, a neural symbolic collaborative reasoning mechanism is introduced to perform secondary correction on the anomaly detection results. Specifically, a set of symbolic rules based on expert knowledge is constructed. Each rule outputs its rule confidence score. By weighted fusion of the predicted probabilities from the fusion model and the results of rule-based inference, a corrected anomaly score is obtained:

[0026] in, This is a balance coefficient between model prediction and rule-based reasoning. The weight is the rule weight, and satisfies This mechanism reduces the false alarm rate while enhancing the interpretability of anomaly detection results.

[0027] (9) Result Prediction and Evaluation: After completing model training, fusion prediction, and threshold adaptive optimization, the final result prediction and performance evaluation are performed on the test dataset. Specifically, the fusion model predicts the final result and evaluates the performance of the samples. Output the final anomaly prediction probability And combined with the optimal classification threshold obtained by optimization on the validation set. The final predicted label for the generated sample is determined by the following rules:

[0028] in, Indicates an abnormal sample. This represents normal samples. Based on the above prediction results and the true labels, the model's detection performance is systematically evaluated. Given that the number of abnormal samples in the experimental dataset is significantly less than that of normal samples, accuracy alone is insufficient to objectively reflect the model's true performance. Therefore, recall and F1 score are selected as a comprehensive evaluation metric, with F1 score as the primary evaluation criterion to measure the model's overall discriminative ability under class imbalance conditions. Recall is defined as:

[0029] The F1 score is defined as:

[0030] in, (True Positive) represents the number of samples that are actually anomalous and were correctly predicted as anomalous. (True Negative) represents the number of samples that are actually normal and were correctly predicted as normal. (False Positive) represents the number of samples that are actually normal but were incorrectly predicted as abnormal. (False Negative) represents the number of samples that are actually abnormal but are incorrectly predicted as normal. Through the above evaluation method, while ensuring high anomaly detection capability, the false alarm rate can be effectively suppressed, thus comprehensively reflecting the practical application value of the proposed method in highly imbalanced anomaly detection scenarios.

[0031] The beneficial effects of this invention are as follows: This invention addresses the shortcomings of existing command-line replay attack detection methods in terms of data reliability, class balance, model interpretability, and dynamic adaptability. It proposes an integrated solution that combines data isolation, class balance, neural symbolic reasoning, and robust training. This solution can maintain essential differences between classes by using feature-aware hierarchical undersampling while ensuring data isolation. Combined with dynamic rule optimization and multi-strategy perturbation enhancement, it can accurately detect minority class attacks in complex adversarial environments, provide auditable decision-making basis, and maintain high stability and real-time performance of detection. Attached Figure Description

[0032] Figure 1 For: Overall flowchart; Figure 2 For: Model structure diagram. Detailed Implementation

[0033] The invention will be further described below with reference to the accompanying drawings: A highly robust command-line replay attack detection method based on neural symbol integration and adversarial enhancement includes (1) data acquisition and preprocessing; (2) adaptive enhancement of minority class samples; (3) data isolation and consistency verification; (4) multi-model collaborative training; (5) iterative processing of difficult samples; (6) adversarial sample generation and robust training; (7) threshold adaptive optimization; (8) neural symbol joint reasoning; and (9) result prediction and evaluation. The specific measures are as follows: Step 1: Data Preprocessing: For missing values ​​in the daily electricity consumption feature of the dataset, firstly, calculate the median of the non-missing values ​​in each feature column, and fill in all missing positions in the column with this median; then, generate a corresponding binary missing indicator feature for each feature column, marking a sample as 1 if the original value of the feature is missing, otherwise marking it as 0; finally, concatenate the filled numerical features with the generated missing indicator features column by column to form an extended feature set that contains both the filled numerical values ​​and the original missing state information, which can retain the potential discriminative information of missing patterns while completing the data.

[0034] Step 2: Adaptive Augmentation of Minority Class Samples: For imbalanced data, adaptive augmentation and dynamic control of minority class sample balancing were performed. First, the distribution density of outlier samples in the feature space and their boundary relationship with normal samples were analyzed. Augmentation strategies were dynamically selected based on sparsity: for sparse regions, linear interpolation based on K-nearest neighbors was used to generate synthetic samples; for dense regions, feature perturbations (such as adding Gaussian noise) were used to generate approximate variants. All generated synthetic samples underwent double validity verification—Mahavior distance was used to ensure their intrinsic consistency with the original outlier clusters, while avoiding overlap with the normal sample space. The synthesis process was progressive, with model performance evaluated after each generation, and the number of subsequent generation samples dynamically adjusted according to the preset target class ratio until an optimal balance was reached. Finally, valid synthetic samples were merged into the training set and subjected to deduplication based on feature fingerprints and distribution consistency checks to ensure that the augmented dataset improved the model's ability to identify minority classes while maintaining the overall data distribution's rationality.

[0035] Step 3: Data Isolation and Consistency Verification: To ensure the authenticity and reliability of model evaluation, this invention implements a multi-level data isolation and consistency verification mechanism to ensure strict independence between the training set, validation set, and test set and to prevent information leakage. The specific operation process is as follows: First, by generating a unique hash fingerprint for each sample based on the concatenation of feature vectors and labels, duplicate or highly similar samples across data subsets are systematically detected and excluded, blocking data contamination at the source. Second, statistical modeling is performed on the key feature dimensions of each data subset. By calculating their mean, standard deviation, and Kullback-Leibler divergence, the distribution differences are quantified. If the divergence is lower than a preset threshold, a warning is triggered, indicating that there may be unreasonable partitioning or leakage. Furthermore, feature spatial distance metrics are used to identify sample pairs with abnormally close spatial locations in different subsets as clues to potential cross-contamination. Ultimately, by integrating sample fingerprint verification, distribution consistency analysis, and feature spatial distance detection, the system achieves closed-loop monitoring and correction of data partitioning quality, thereby providing a highly clean, independent, and reasonably distributed data foundation for model training and evaluation, effectively improving the credibility and reproducibility of model generalization ability evaluation.

[0036] Step 4: Multi-model Parallel Training and Prediction Fusion: A multi-model collaborative training strategy is adopted, integrating deep learning and traditional machine learning models to construct a heterogeneous anomaly detection framework to improve system accuracy and robustness. Specific operations include: First, two types of heterogeneous models are selected and constructed—the FT-Transformer for high-order interaction modeling of complex features and the Multilayer Perceptron (MLP) for nonlinear relationship extraction. Both are trained in parallel on independent datasets that have been standardized, imputed, and appropriately partitioned. During the training phase, the FT-Transformer utilizes its self-attention mechanism to capture deep temporal patterns, while the MLP focuses on stable nonlinear mappings in small-sample scenarios. Both are optimized synchronously without interference. Subsequently, dynamic weights are assigned to each model based on the validation set performance, and their output prediction probabilities are weighted and fused to obtain a comprehensive prediction probability. Then, an adaptive threshold optimization strategy is adopted, using grid search to select the optimal classification threshold that maximizes the F1 score on the validation set. Finally, the fusion model was evaluated on the test set and incrementally optimized based on feedback, forming a high-performance anomaly detection system that balances feature complexity, sample imbalance, and decision stability, significantly enhancing the ability to identify command line replay attacks.

[0037] Step 5: Difficult Sample Identification and Iterative Enhancement: Through a multi-round iterative difficult sample processing mechanism, the model's classification ability near the decision boundary is dynamically optimized. The specific process is as follows: After each round of training, the system comprehensively identifies difficult samples based on two factors: prediction uncertainty (i.e., the absolute difference between the prediction probability and the classification threshold) and the existence of misclassification. Subsequently, targeted enhancement strategies are implemented for these samples—including adding small-amplitude Gaussian noise and implementing feature space boundary perturbation—to generate new samples with greater discriminative power. At the same time, the validity of the generated samples is verified through distance metrics and overlap detection to ensure that they neither deviate from the original abnormal sample distribution nor excessively overlap with the normal sample space. Next, the verified enhanced samples are merged with the original difficult samples to expand the training set for the next round of model retraining. This process is iterative. In each round, the model's performance in handling difficult samples is evaluated through a validation set, and the enhancement strategies and iteration termination conditions are dynamically adjusted based on the evaluation results. Ultimately, the model converges on complex and fuzzy decision boundaries, significantly improving the discrimination accuracy of boundary samples and the overall detection robustness.

[0038] Step 6: Adversarial Example Generation and Robust Training: By integrating adversarial example generation and adversarial training, the model's robustness to input perturbations and unknown attacks is significantly enhanced. Adversarial examples are generated using a fast gradient sign method: For each training sample, the gradient of its loss function relative to the input is calculated, its sign is taken, and it is scaled by a preset small-amplitude perturbation coefficient. This is then superimposed onto the original sample as an adversarial perturbation, thus constructing adversarial examples that are difficult for humans to detect but can mislead the model's classification. During the training phase, the model is optimized simultaneously based on both the original and adversarial examples. Its total loss function is defined as the sum of the losses of both, and this total loss is minimized using a gradient descent algorithm to update the model parameters, forcing the model to learn robust decision boundaries that are insensitive to input perturbations. To further improve performance, this invention implements several optimization strategies: dynamically adjusting the perturbation amplitude to balance training stability and robustness; introducing multiple adversarial example generation methods to enhance attack diversity; and alternating the use of adversarial examples and original samples for training to prevent the model from overfitting the adversarial distribution and impairing the original task performance. Finally, through comprehensive evaluation of metrics such as accuracy, F1 score, and adversarial example classification success rate on the test set, the strategy was verified to enable the model to effectively resist maliciously constructed input perturbations while maintaining high detection accuracy.

[0039] Step 7: Threshold Adaptive Optimization: The threshold adaptive optimization module dynamically determines the optimal classification decision threshold to address the insufficient generalization ability of fixed thresholds in scenarios with highly imbalanced samples. Specifically, the following steps are performed: First, obtain the continuous prediction probabilities of the anomaly categories output by the fusion model on the validation set; then, construct a candidate threshold set with a fine step size within a preset interval, calculating the corresponding precision, recall, and F1 score for each candidate threshold; to ensure the minimum attack detection rate requirement in actual business operations, a recall constraint is introduced, and a feasible candidate threshold set that meets the minimum recall threshold is selected; finally, the threshold that maximizes the F1 score is selected from this set as the optimal classification threshold for the system, and it is then applied to the testing and online detection phases. This mechanism achieves automatic threshold learning and optimization based on validation set performance feedback, dynamically balancing precision and overall detection performance while ensuring high recall.

[0040] Step 8: Neural Symbolic Joint Inference: The neural symbolic joint inference module introduces interpretable symbolic rule inference on top of data-driven neural network prediction, enabling the correction and enhancement of anomaly detection results. Specific operations include: first, obtaining the anomaly prediction probability output by the fusion model, and matching samples based on a symbolic rule base constructed using domain knowledge, calculating the confidence level of each triggering rule; then, weighted aggregation of the confidence levels of multiple triggering rules to obtain an anomaly score at the symbolic inference level; next, using an adjustable balance coefficient, weighted fusion of the neural prediction probability and the symbolic inference score to form a neural symbolic joint anomaly score; then, executing a consistency verification mechanism to resolve conflicts between neural prediction and symbolic rules, suppressing misjudgments on noisy samples; finally, comparing the joint score with the optimal threshold determined by the threshold adaptive optimization module to make the final anomaly determination. This method not only effectively reduces the false alarm rate and improves detection stability, but also enhances the interpretability of the decision-making process by fusing expert rules, achieving a balance between high reliability and strong robustness in complex and dynamic CLI replay attack detection scenarios.

[0041] Step 9: Result Prediction and Evaluation: In the result prediction and evaluation stage, feature consistency verification is first performed on the strictly isolated test set to ensure that its processing flow is completely consistent with the training stage. Then, the standardized test features are input into the trained neural symbol fusion detection model, and weighted probability fusion of multiple base models and neural symbol joint inference correction are performed sequentially to obtain the final anomaly confidence score for each sample. Next, the optimal threshold determined through adaptive optimization on the validation set is used to determine the confidence score, generating a final predicted label for whether an attack has occurred. Furthermore, a confusion matrix is ​​constructed by comparing the predicted label with the real label, and multiple performance indicators, including recall, precision, and the core comprehensive indicator F1 score, are calculated to comprehensively evaluate the model's detection performance in an imbalanced security scenario. Finally, the specific contributions of each module—fusion model, threshold adaptation, and neural symbol inference—to the overall performance are analyzed, providing a reliable basis for model optimization and engineering deployment. This objectively and reproducibly verifies the detection capability and practical value of this invention in a real adversarial environment. Table 2 shows the performance of this method and the experimental results of other methods.

[0042] The above description is only a preferred embodiment of the present invention. It should be noted that for those skilled in the art, several improvements can be made without departing from the principle of the present invention, and these improvements should also be considered within the scope of protection of the present invention without creative effort.

Claims

1. A method for detecting abnormal power consumption based on CLI replay attacks, characterized in that: The steps are as follows: (1) Data acquisition and preprocessing; (2) Adaptive augmentation of minority class samples; (3) Data isolation and consistency verification; (4) Parallel training and prediction fusion of multiple models; (5) Iterative processing of difficult samples; (6) Adversarial sample generation and robust training; (7) Threshold adaptive optimization; (8) Joint reasoning of neural symbols; (9) Result prediction and evaluation. In step (4), multi-model parallel training and prediction fusion are performed: after data isolation and consistency verification are completed, multi-model parallel training and prediction fusion are constructed based on the training data. A deep learning-based tabular data modeling model and a traditional machine learning-based classification model are constructed respectively. The deep learning model uses FT-Transformer to perform high-order interaction modeling of sample features through feature embedding and multi-head self-attention mechanism; the traditional machine learning model uses multilayer perceptron to capture the nonlinear discriminative relationship of features; for any sample The FT-Transformer model is trained to output the predicted probability of belonging to the anomaly category. At the same time, the MLP model outputs the corresponding anomaly prediction probability. After obtaining the prediction results of the base model, the outputs of each model are integrated using a probabilistic fusion method.

2. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (1) employs a multi-stage data processing and feature construction method: Data missing value handling: To address the missing value problem in time-series electricity consumption data, a joint processing method combining numerical imputation and missing value indication is adopted. First, missing values ​​are imputed for the target numerical features based on the median strategy to ensure the robustness of the data distribution. At the same time, a corresponding missing value indication feature is constructed for each feature to explicitly identify the missing state in the original data. The imputed numerical features and missing value indication features are combined to form an extended feature representation containing both numerical information and missing pattern information, thereby improving the recognition capability of subsequent anomaly detection models without losing missing structural information. Original time-series feature extraction: Extract multi-dimensional statistical features from the original daily electricity consumption sequence, including: basic statistical features: average daily electricity consumption, standard deviation of electricity consumption, coefficient of variation, skewness, kurtosis; periodic features: difference in electricity consumption patterns between weekdays and holidays, monthly electricity consumption trend slope, seasonality index; frequency domain features; abnormal fluctuation features: number of sudden increases / decreases in electricity consumption, number of days with zero / low values, continuous abnormal patterns; behavioral consistency features: Mahalanobis distance between user electricity consumption patterns and the baseline patterns of similar users.

3. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: In step (2), the minority class sample adaptive enhancement is performed: statistical analysis is conducted on the sample label distribution; when the proportion of abnormal samples is detected to be lower than the preset threshold, the minority class sample enhancement module is triggered. The preset threshold is set to the ratio of abnormal samples to normal samples being less than 1:3 to 1:50; the adaptive enhancement process includes adaptively selecting the sample enhancement method and enhancement intensity based on the distribution density, neighborhood structure and boundary relationship of abnormal samples in the feature space and normal samples. At least one of the following methods is used to generate synthetic abnormal samples to supplement the original abnormal sample distribution: sample interpolation generation based on neighborhood relationship, sample expansion based on local density perception and sample generation based on feature perturbation. During the sample generation process, the number of synthetic samples is dynamically controlled according to the target class balance interval, and the validity of the generated synthetic samples is verified. Low-confidence samples that are abnormally far from the original abnormal samples or highly overlap with normal samples are removed, thereby alleviating the class imbalance problem while avoiding excessive generation of abnormal samples and improving the stability and generalization ability of subsequent model training.

4. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: In step (3), dataset isolation and consistency verification are performed: First, a duplicate detection method based on sample fingerprints is used to check the feature vector of each sample. Its tags Perform concatenation encoding to construct the sample fingerprint vector. Sample fingerprint values ​​are generated using a hash function. The system detects whether there are completely duplicated or highly similar samples by comparing the consistency of fingerprint values ​​in different data subsets. When the same or similar fingerprint values ​​are detected, it determines that there is a risk of data leakage and re-executes the data partitioning operation. Secondly, a statistical distribution consistency detection method is adopted to model the statistical distribution of each feature dimension in the training set, validation set and test set respectively, and judges the degree of similarity by calculating the distance index between the feature distributions of each data subset.

5. The power consumption anomaly detection method based on CLI replay attack according to claim 4, characterized in that: In step (3), the Kullback–Leibler divergence is used to analyze the training set distribution. Distribution with validation or test sets The measurement is defined by formula (1): When the divergence value is lower than the preset distribution difference threshold, it is determined that there is abnormal distribution overlap between different data subsets, thereby triggering a re-division or manual verification process; a cross-detection method based on feature space distance constraint is adopted to map the samples to the original feature space or the low-dimensional feature space after principal component analysis dimensionality reduction, and the Euclidean distance between samples across data subsets is calculated, which is defined by formula (2): When there are sample pairs from different subsets of data whose distance is less than a preset distance threshold. If the sample pair is determined to be highly similar in the feature space, posing a potential risk of information leakage, the relevant samples will be removed or reassigned. By combining three methods—sample fingerprint hash detection, statistical distribution consistency test, and feature space distance constraint detection—the independence between data subsets is verified at multiple levels. This ensures that the model training, validation, and testing processes are isolated from each other, thereby improving the objectivity and credibility of the anomaly detection model evaluation results.

6. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (5) Difficult sample identification and iterative enhancement: After completing the multi-model prediction fusion, a difficult sample identification and iterative enhancement mechanism is introduced to further improve the model's ability to distinguish between decision boundary regions and complex abnormal samples; Comprehensive anomaly probability based on the output of the fusion model Identify samples with high prediction uncertainty or those that are misclassified as a set of difficult samples. Its prediction uncertainty can be measured by its distance from the classification threshold: when Less than the preset uncertainty threshold If the sample is deemed a hard sample, the prediction result is compared with the true label. Inconsistent samples are directly included in the difficult sample set; For the aforementioned difficult samples, a data augmentation method based on local perturbation is employed to generate enhanced samples by applying controlled noise to the original feature space: The generated enhanced samples are then added to the training set along with the original samples, and the model is retrained multiple times to gradually enhance its expressive ability in abnormal boundary regions.

7. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (6) Adversarial Example Generation and Robust Training: Loss Function Based on the Trained Model Adversarial examples are generated using the fast gradient sign method, with the following perturbation form: Where α represents the disturbance intensity coefficient; The adversarial examples and the original samples are jointly input into the model for training. The combined loss function on the original samples and the adversarial examples is minimized. Improve the stability and generalization ability of the model when faced with input noise and malicious perturbations.

8. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (7) Threshold Adaptive Optimization: After obtaining the anomaly prediction probability of the fusion model, a threshold adaptive optimization module is introduced to avoid the degradation of detection performance caused by using a fixed threshold.

9. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (8) Neural Symbolic Joint Reasoning: Based on the model prediction results, a neural symbolic collaborative reasoning mechanism is introduced to perform secondary correction on the anomaly judgment results; a symbolic rule set based on expert knowledge is constructed. Each rule outputs its rule confidence score. ; By weighted fusion of the predicted probabilities of the fusion model and the results of rule-based reasoning, a corrected anomaly score is obtained.

10. The power consumption anomaly detection method based on CLI replay attack according to claim 1, characterized in that: Step (9) Result prediction and evaluation: After completing model training, fusion prediction and threshold adaptive optimization, perform final result prediction and performance evaluation on the test dataset; The fusion model outputs the final anomaly prediction probability for the sample. The final predicted label for the sample is generated by combining the optimal classification threshold obtained on the validation set. The determination rule is as follows: ; in, Indicates an abnormal sample. The normal samples are represented by the above prediction results and the true labels. The model detection performance is systematically evaluated. Since the number of abnormal samples in the experimental dataset is significantly less than that of normal samples, it is difficult to objectively reflect the true performance of the model by using the accuracy index alone. Therefore, recall and F1 score are selected as comprehensive evaluation indicators, with F1 score as the main evaluation basis to measure the overall discrimination ability of the model under class imbalance conditions.