A power user electricity stealing behavior detection method based on graph contrastive learning

By constructing a joint training framework of community graph structure and temporal contrastive learning, the problems of ignoring user spatial relationships and unutilizing unlabeled data in existing electricity theft detection methods are solved, and high-precision electricity theft detection is achieved under extreme imbalance conditions.

CN123180220APending Publication Date: 2026-11-27GUILIN UNIV OF ELECTRONIC TECH +1
View PDF 0 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

Existing methods for detecting electricity theft ignore the spatial relationships between electricity users, resulting in low detection accuracy under conditions of scarce labeled data and extreme class imbalance, and fail to effectively utilize massive amounts of unlabeled electricity consumption data.

Method used

By constructing a community graph structure, a joint training framework of community graph regularization constraints and temporal contrastive learning is introduced. ACORN geographic community grouping and adaptive weights are used, combined with one-dimensional convolution, multi-layer Transformer self-attention encoding and multiple loss functions to optimize model training.

Benefits of technology

It significantly improves the accuracy of electricity theft detection under extreme data imbalance conditions, effectively utilizes massive amounts of unlabeled data, and enhances the robustness and adaptability of the model.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123180220A_ABST
    Figure CN123180220A_ABST
Patent Text Reader

Abstract

The application relates to a power user electricity stealing behavior detection method based on graph contrast learning, and comprises the following steps: step 1, power time series data preprocessing and graph structure construction; step 2, constructing a transformer time series encoder; step 3, spatiotemporal graph contrast learning joint training; and step 4, electricity stealing detection reasoning. The application has the beneficial effects that: (1) by introducing a community graph structure and graph regular constraint, the electricity stealing detection precision under an extreme data imbalance condition is significantly improved; (2) by a time contrast learning mechanism, massive unlabeled power consumption data can be effectively utilized; and (3) by adaptive edge weight and time series decay weighting two innovative designs, the adaptability of the graph structure to the electricity stealing detection task is enhanced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of smart grid information security technology, specifically relating to a method for detecting electricity theft by power users based on graph comparison learning. Background Technology

[0002] Electricity theft causes huge economic losses to power grid companies every year. The large-scale deployment of smart meters has made data-driven electricity theft detection the mainstream technical approach. Existing methods are mainly divided into three categories: machine learning methods based on handcrafted features (represented by XGBoost, which trains classifiers by extracting statistical features such as mean, variance, and quantiles, with high computational efficiency but feature engineering relies on expert experience and is difficult to capture deep temporal patterns); supervised methods based on deep learning (represented by CNN-LSTM, ResNet-1D, LSTM, etc., which automatically learn temporal features using convolutional or recurrent networks and perform well when there are sufficient annotations); and pure temporal methods based on Transformer (capturing long-range dependencies through self-attention mechanisms).

[0003] However, the aforementioned methods all face two fundamental difficulties in practical applications. First, the coverage rate of power grid company inspections is extremely low, typically less than 1%, resulting in a severe shortage of labeled samples. Electricity theft users account for only about 5%, and this extreme class imbalance causes the model's decision boundary to be heavily biased towards the majority class, leading to a sharp drop in the accuracy of identifying the few electricity theft samples. For example, with a 5% electricity theft rate, XGBoost's PR-AUC is only 36.33%, CNN-LSTM's is 39.84%, ResNet-1D's is 28.05%, and Transformer only reaches 34.37%. Second, and more critically, existing methods treat each electricity user as an independent sample, completely ignoring the natural spatial relationships between users. In reality, users within the same geographical community exhibit significant similarities in their electricity consumption behavior—electricity theft users not only deviate from their own historical electricity consumption patterns but also from the collective electricity consumption patterns of their neighbors. Existing methods discard this important spatial structural information, making accurate judgments difficult under conditions of extremely limited labeled data.

[0004] To address the aforementioned problems, there is an urgent need for a method to detect electricity theft that can simultaneously utilize power grid diagram structure information and massive amounts of unlabeled electricity consumption data. Therefore, this invention proposes an electricity theft detection scheme based on spatiotemporal graph contrastive learning. By constructing a community graph structure and introducing a joint training framework of community graph regularization constraints and temporal contrastive learning, it effectively overcomes the shortcomings of existing methods. Summary of the Invention

[0005] The technical problems to be solved by this invention mainly include three aspects: First, existing electricity theft detection methods (including XGBoost, CNN-LSTM, ResNet-1D, LSTM, Transformer, etc.) treat each electricity user as an independent sample, completely ignoring the natural spatial relationships between users. In actual power grids, users in the same geographic community (e.g., grouped by ACORN geographic demographics) have significant similarities in their electricity consumption patterns. Electricity thieves not only deviate from their own normal electricity consumption patterns but also from the collective electricity consumption patterns of their neighbors. Existing methods discard this important graph structure information, resulting in the inability to fully utilize community-level constraints to assist in judgment under conditions of scarce labeled data. Second, power grid companies accumulate long-term electricity consumption records of tens of thousands of users in their daily operations, but due to the high cost of on-site inspections, only a very small number of users have verified electricity theft labels (coverage is usually less than 1%). Existing supervised learning methods can only use these few labeled samples for model training, and the rich information contained in the massive amount of unlabeled electricity consumption data is completely wasted, failing to be transformed into an improvement in model recognition capabilities. Third, the proportion of electricity theft users in the total user base is extremely low (typically around 5%), constituting a typical extreme class imbalance scenario. Furthermore, the diverse patterns of electricity theft (including partial current reduction, time-of-use current reduction, mean replacement, constant underreporting, time reversal, and half-cycle current reduction) cause existing supervised classifiers to exhibit a decision boundary heavily biased towards the majority of normal classes when facing this complex scenario, making it difficult to simultaneously achieve high precision and recall for the few electricity theft samples. In conclusion, there is an urgent need to propose a novel electricity theft detection method that can simultaneously utilize power grid structure information and massive amounts of unlabeled data, while maintaining effective detection capabilities even under extreme class imbalance conditions.

[0006] The technical solution of this invention to solve the above-mentioned technical problems is as follows: A method for detecting electricity theft by power users based on graph comparison learning, comprising the following steps:

[0007] Step 1: By collecting electricity consumption data from multiple users and at multiple time periods, performing time-series aggregation and noise reduction, and constructing a community graph with adaptive weights based on community geographic grouping, the community relationship constraint matrix is ​​calculated. The normalized graph Laplace constraint matrix, the user aggregated electricity consumption sequence, and the adaptive adjacency matrix are obtained. Degree matrix ;

[0008] Step 2: Based on the user aggregated electricity consumption sequence output in Step 1, fixed-dimensional user temporal coding features are obtained through one-dimensional convolutional downsampling, position encoding, multi-layer Transformer self-attention encoding, and global pooling.

[0009] Step 3, based on the community constraint matrix obtained in Step 1 The temporal coding features obtained in step 2 are used for spatiotemporal graph comparison learning and multi-loss joint training to obtain a complete training model with optimized parameters.

[0010] Step 4: Based on the Transformer encoder and classifier head trained in Step 3, extract features from the electricity consumption sequence of the user to be detected, output the electricity theft prediction probability, and combine the optimal threshold of the validation set to complete the binary classification of normal / electricity theft users.

[0011] In some possible implementations, step 1 specifically involves:

[0012] Step 1.1: Obtain the original electricity consumption data matrix ,Include individual electricity users The electricity consumption at the half-hour level for each original time step is calculated; the original time-series data is aggregated by day / week, the sequence length is compressed, and random fluctuations are eliminated to obtain the aggregated electricity consumption sequence for a single user. ;

[0013] Step 1.2, with all Each user is a graph node set. Basic edge sets are constructed based on ACORN geographic community grouping. Only when user , In the same community An adaptive adjacency matrix is ​​constructed by introducing a consumption similarity correction factor. The formula for calculating matrix elements is:

[0014] ;

[0015] in For indicator functions, Let be the similarity coefficient of consumer behavior, and the similarity coefficient... Calculated using Gaussian kernel:

[0016]

[0017] in For users Average electricity consumption The preset Gaussian kernel bandwidth parameters;

[0018] Step 1.3, based on the adaptive adjacency matrix Calculate the degree matrix The diagonal elements satisfy , The identity matrix is ​​used; substituting it into the formula, the community relationship constraint matrix is ​​calculated:

[0019]

[0020] Step 1 collects raw electricity consumption data from all electricity users across multiple time periods and aggregates it by day and week. This smooths short-term random electricity consumption fluctuations and shortens the sequence length to reduce the computational burden on subsequent models. Then, user association graphs are built based on user geographical communities. Adaptive association weights are set for users in the same community based on differences in average electricity consumption. Finally, a community association matrix that can be used for model constraints is generated. This method does not forcibly bind users in the same community with huge differences in electricity consumption behavior. It conforms to the real community electricity consumption distribution pattern and transforms the spatial pattern of similar electricity consumption behavior of community users into a constraint condition that the model can learn. This makes up for the shortcomings of traditional methods that ignore user community associations, reduces misjudgment of normal users from the bottom up, and improves the detection accuracy in scenarios with a small number of electricity theft samples.

[0021] In some possible implementations, step 2 specifically involves:

[0022] Step 2.1, take the single-user electricity consumption sequence output in Step 1. Inputting a Conv1D one-dimensional convolutional layer completes sequence downsampling, compressing the time length and extracting local power consumption patterns;

[0023] Step 2.2: Superimpose sinusoidal position codes on the downsampled sequence and inject temporal position information to enable the model to perceive the sequential relationship of electricity consumption.

[0024] Step 2.3: Feed the position-encoded sequence into the stack. The layered Transformer encoder relies on a multi-head self-attention mechanism to capture long-term temporal dependencies in power consumption. Each layer is configured with multi-head attention and feedforward networks, GELU activation, and Dropout regularization.

[0025] Step 2.4: Perform global pooling on the temporal features output by the Transformer, concatenating the mean and maximum values, to output a fixed-dimensional feature. User time-series coding features .

[0026] Step 2 feeds the standardized electricity consumption sequence processed in Step 1 into a one-dimensional convolutional layer to compress the sequence length and extract local electricity consumption patterns. It then overlays temporal position encoding to enable the model to identify the order of electricity consumption. Next, it uses a multi-layer, multi-head self-attention structure to capture long-term electricity consumption change patterns across time periods. Finally, it integrates global features to output a fixed-dimensional user electricity consumption representation. Convolutional compression effectively reduces computational overhead and improves model efficiency. The multi-head attention mechanism can accurately capture temporal anomalies caused by various covert electricity thefts, such as time-sharing current reduction and electricity consumption value tampering. The uniform feature vector completely preserves all electricity consumption temporal information and can be directly adapted to subsequent comparative learning, community constraints, classification and recognition modules for simultaneous use, ensuring no information loss during feature transmission.

[0027] In some possible implementations, step 3 specifically involves:

[0028] Step 3.1, Data Augmentation to Generate Dual Views: Apply random noise jitter and random scaling to the user electricity consumption sequence output in Step 1, and optionally a random time mask, to generate two sets of augmented views. and ;

[0029] Step 3.2, Feature Projection: Input the two sets of enhanced views into the Transformer encoder of Step 2 to obtain the encoded features. and The projection features are obtained by mapping to a low-dimensional projection space through two fully connected projection heads and then normalizing the projection. and The projection feature matrix is ​​obtained by summarizing all view features;

[0030] Step 3.3, calculate the time-decayed weighted time contrast loss. :

[0031] ① Define a data collection time decay weight, assigning higher weight to recently collected user samples:

[0032]

[0033] in For users The time interval between the most recent data collection and the current time in electricity consumption data. The total time span for data collection from all users. This is the decay rate parameter;

[0034] ② Using the InfoNCE loss framework, two views within the same user are considered positive sample pairs, and views across users are considered negative sample pairs. The loss formula is as follows:

[0035]

[0036] in For cosine similarity, For temperature parameters, for Positive samples;

[0037] Step 3.4, based on the community constraint matrix output in Step 1 Calculate the community graph regularization constraint loss. The formula for constraining the distance between projected features of users in the same community using matrix trace operations is as follows:

[0038]

[0039] in For the projection feature matrix of all enhanced views, Represents the trace of a matrix;

[0040] Step 3.5, calculate Focal Loss (classification loss). To address the imbalance of extreme categories in electricity theft detection, the formula is:

[0041]

[0042] in This represents the model's predicted probability of the true class. To focus parameters, Balance the weights for each category;

[0043] Step 3.6: Weighted fusion of the three losses yields the total training loss, calculated using the following formula:

[0044]

[0045] in and These are the weighting coefficients for the time-contrast loss and the graph regularization term, respectively.

[0046] Step 3.7, Optimizer backpropagation total loss The AdamW optimizer, cosine annealing learning rate, and early stopping strategy are used to synchronously update all network parameters of the Transformer encoder, projector head, and classifier head.

[0047] Step 3 applies noise, scaling, and random masking transformations to the user's electricity consumption sequence to generate two sets of differentiated sample views. These are then fed into a temporal encoder to extract features and mapped to a low-dimensional representation space. Temporal comparative learning constraints are constructed based on the two sets of views for the same user. The model autonomously learns general electricity consumption features using massive amounts of unlabeled electricity consumption data, while simultaneously increasing the learning weight of recent electricity consumption behavior, making the model more sensitive to sudden electricity theft. Combined with the community association matrix generated in Step 1, graph structure constraints are added to narrow the feature distance between normal users in the same community, making electricity theft users distinct due to their deviation from the community's collective electricity consumption pattern, effectively reducing the number of false alarms. A classification loss focusing on difficult samples is introduced to alleviate the class imbalance problem caused by the extremely low proportion of electricity theft samples, weakening the training weight of a large number of easily distinguishable normal samples, allowing the model to focus on learning to identify difficult-to-distinguish electricity theft behaviors. The three types of constraint losses are weighted and merged, and all network parameters are updated synchronously in reverse. Temporal self-supervision, community space constraints, and imbalanced classification mechanisms work together to solve three major industry problems at once: scarce labeled samples, loss of user space association, and extreme sample imbalance. The overall detection performance is significantly better than traditional machine learning and basic deep learning detection algorithms.

[0048] In some possible implementations, step 4 specifically involves:

[0049] Step 4.1: Input the original electricity consumption sequence of the user to be tested into the preprocessing flow of Step 1 to obtain the standardized aggregated electricity consumption sequence;

[0050] Step 4.2: Feed the standardized sequence into the Transformer encoder trained in Step 3, extract the temporal coding features and input them into the classification head, outputting the predicted probability of electricity theft for the user. ;

[0051] Step 4.3: During the model training phase, a PR curve is plotted on the validation set based on a preset recall target to determine the optimal classification decision threshold. ;

[0052] Step 4.4, perform a judgment on the user to be tested: if If the electricity is stolen, the user is considered a legitimate electricity user; otherwise, the user is considered a legitimate electricity user.

[0053] Step 4 reuses the electricity consumption data of the users to be detected. Step 1 unifies the preprocessing process to ensure that the data standards for training and detection are completely consistent. Input the completed model after training to extract features and output the probability value of users having electricity theft behavior. Combined with the business's preset minimum detection target for electricity theft, the optimal judgment threshold is determined on the validation dataset through the precision-recall curve. The probability value is compared with the threshold to distinguish between electricity theft and normal users. The unified data processing standard avoids the decrease in accuracy caused by the deviation between training and detection data. The continuous probability output can flexibly adjust the strictness of the inspection and screening to adapt to different manpower verification configuration needs. The threshold set by relying on the precision-recall curve is more suitable for the imbalanced scenario where electricity theft samples are scarce. While ensuring the amount of electricity theft detection, it reduces invalid manual verification. The inference stage only performs simple forward operations, without the need for complex graph construction and loss calculation, which can quickly complete the online electricity theft screening of massive users in batches.

[0054] The beneficial effects of this invention are:

[0055] (1) By introducing community graph structure and graph regularization constraints, the accuracy of electricity theft detection under extreme data imbalance conditions is significantly improved: ablation experiments show that, In the scenario of extreme imbalance in electricity theft rates, the complete STCL-GL method achieves a PR-AUC of 0.4241. When the community graph constraint term is removed (i.e., assuming...), the PR-AUC is... After this, the PR-AUC plummeted to 0.3173, a decrease of 0.1068, demonstrating the crucial contribution of graph structure information to detection performance. The graph regularization term, by constraining the similarity of representations with community users, effectively suppressed false positives against normal users and mitigated the decision boundary shift problem caused by extreme imbalance.

[0056] (2) Through the time-comparison learning mechanism, the effective utilization of massive unlabeled electricity consumption data was achieved: Ablation experiment results show that when the time-comparison loss is removed (i.e., assuming...), After removing the temporal contrast loss and graph regularization term, and retaining only the supervised classification loss (pure supervised mode), the PR-AUC dropped to 38.95%. When both temporal contrast loss and graph regularization term were removed, and only the supervised classification loss was retained (pure supervised mode), the PR-AUC further dropped to 33.63%. This gradient descent trend fully verifies that temporal contrast learning can extract useful temporal representations from unlabeled data and improve the model's discriminative ability without increasing the labeling cost.

[0057] (3) Through two innovative designs, adaptive edge weights and temporal decay weighting, the adaptability of graph structures to electricity theft detection tasks is enhanced: adaptive edge weights This avoids imposing undue constraints on users within the same community but with vastly different electricity usage patterns; data collection time decay weighting. By focusing the model on recently collected electricity consumption data, it becomes more sensitive to electricity theft. These two designs, based on data characteristics, improve the robustness and practicality of the method. Attached Figure Description

[0058] Figure 1 The figure shows the experimental results of the method comparison.

[0059] Figure 2 This is a graph showing the results of the ablation experiment. Detailed Implementation

[0060] The principles and features of the present invention are described below with reference to the accompanying drawings. The examples given are only for explaining the present invention and are not intended to limit the scope of the present invention.

[0061] This invention proposes a method for detecting electricity theft based on spatiotemporal graph contrastive learning (STCL-GL), which includes the following steps:

[0062] Step S1: Preprocessing of electricity consumption time series data and construction of graph structure

[0063] Get Individual electricity users Electricity consumption data matrix at each time step First, the raw half-hourly electricity consumption data is aggregated into daily or weekly electricity consumption sequences to reduce sequence length and random fluctuations. Then, based on the user's geographic community affiliation information (such as ACORN geographic population grouping), a total of... (each community category), construct a community map. , where the node set Includes all Individual users, edge set Defined as: if and only if the user and users When they belong to the same community, Define the adjacency matrix. Its elements are not simple 0 / 1 binary connections, but rather adaptive edge weights that incorporate consumption pattern similarity correction:

[0064]

[0065] in This is an indicator function (1 for the same community, 0 otherwise). The similarity coefficient of consumer behavior is defined as follows:

[0066]

[0067] here For users Average electricity consumption This refers to the preset Gaussian kernel bandwidth parameters. (Introduction) The physical meaning is: even if two users belong to the same community, if their average electricity consumption levels differ significantly, the weight of the corresponding edge in the graph is automatically reduced to avoid forcibly binding users with vastly different electricity consumption patterns together. Conversely, the edge weights are higher between users in the same community with similar electricity consumption levels, resulting in a stronger graph regularization effect. Therefore, the community relationship constraint matrix is ​​calculated as follows:

[0068]

[0069] in For degree matrix, , This is the identity matrix. This constraint matrix characterizes the topological relationships between users in the community and provides a mathematical basis for subsequent community constraints.

[0070] Step S2: Construct the Transformer temporal encoder

[0071] The electricity consumption sequence of each user After downsampling via one-dimensional convolution, the data is input into a multi-layer Transformer encoder. The Transformer captures long-range temporal dependencies in the power consumption sequence through a multi-head self-attention mechanism and outputs encoded features. ,in For encoding dimensions. A complete encoder consists of a Conv1D downsampling layer, a positional coding layer, and... It is composed of stacked Transformer encoder layers.

[0072] Step S3: Spatiotemporal Graph Comparative Learning and Joint Training

[0073] The core innovation of this invention lies in constructing a joint training framework of "time comparison + community graph constraint". Specifically, for each input sample... Apply two data augmentation operations (random noise jitter and random scaling) to generate two augmented views. and The enhanced view is then processed by an encoder to obtain the projection features. and .

[0074] (1) Time comparison loss Enhanced view pairs for the same user Positive sample pairs are formed, and all views from different users form negative sample pairs. A contrastive loss in the form of InfoNCE is used.

[0075]

[0076] in For cosine similarity, For temperature parameters, for Positive samples (i.e., projection features of another enhanced view for the same user). The data acquisition time decay weight is defined as follows:

[0077]

[0078] in For users The time interval between the most recent data collection and the current time in electricity consumption data. The total time span for data collection from all users. This is the decay rate parameter. The physical meaning of this weight is: electricity consumption behavior is time-varying—the more recent the data collection time of a user sample, the greater its reference value for determining whether electricity theft has occurred. By introducing... This allows the time-contrast loss model to assign higher training weights to recently collected user samples, enabling the model to pay more attention to the latest changes in electricity consumption behavior during training, thereby improving the response speed to electricity theft.

[0079] (2) Community graph constraints Using the community relationship constraint matrix constructed in step S1, the representations of users within the same community are constrained to be close to each other in the feature space. The graph regularization term is defined as:

[0080]

[0081] in For the projection feature matrix of all enhanced views, This represents the trace of the matrix. The regularization term is equivalent to the sum of squared distances between the representations of all neighborhood pairs. By minimizing this term, the model is forced to learn encodings that make the representations of users within the same community similar, thus injecting community-level spatial prior knowledge into the model.

[0082] (3) Classification loss Focal Loss is used as the classification loss function to address extreme class imbalances in electricity theft detection. Focal Loss is adjusted by a factor... Reduce the weight of easily classified samples, so that the model focuses on difficult-to-classify electricity theft samples:

[0083]

[0084] in This represents the model's predicted probability of the true class. To focus parameters, Balance the weights for each category.

[0085] Finally, the total loss function for joint training is:

[0086]

[0087] in and These are the weight coefficients for the temporal contrast loss and the graph regularization term, respectively. During training, the model simultaneously optimizes classification accuracy, the discriminative power of temporal representations, and the consistency of community structure.

[0088] Step S4: Electricity Theft Detection Reasoning

[0089] After training, for the electricity consumption sequence of the user to be detected, features are extracted using the trained encoder, and the probability of electricity theft is output by the classification head. Based on the set recall target (e.g., ...), ... The optimal decision threshold is determined on the validation set and applied to the test set for final decision.

[0090] In summary, the present invention has the following innovative aspects:

[0091] Innovation Point 1: The introduction of community graph structure constraints. Existing methods (XGBoost, CNN-LSTM, Transformer, etc.) treat each electricity user as an independent sample, completely ignoring the spatial relationships between users. This invention is the first to construct the ACORN community affiliation relationship as a graph structure, and injects community-level spatial prior knowledge into the model training through community graph constraints—minimizing the distance between users in the same community in the representation space. This is the most fundamental difference between this invention and existing technologies.

[0092] Innovation Point Two: Adaptive Edge Weight Mechanism: Traditional graph methods use a simple 0 / 1 adjacency matrix, failing to consider differences in electricity consumption levels among users within the same community. This invention introduces a consumption pattern similarity coefficient. As an edge weight correction factor, the constraints between users in the same community with similar electricity levels are stronger, while the constraints between users with different electricity consumption patterns are automatically weakened, thus enhancing the adaptability of the graph structure to the electricity theft detection task.

[0093] Innovation Point 3: Joint Training Framework of Temporal Contrast Learning + Graph Regularization: Existing self-supervised contrastive learning methods only consider the enhancement invariance of the temporal dimension. This invention is the first to jointly optimize temporal contrastive loss with community graph constraints, enabling the model to learn both temporal discriminative representations and community structural consistency representations simultaneously. The two complement each other—temporal contrast provides sample-level discriminative signals, while graph constraints provide community-level smooth priors.

[0094] Innovation Point 4: Data Acquisition Time Decay Weighted Contrastive Loss: Existing contrastive learning methods treat all user samples with equal weights. This method introduces a data acquisition time decay weight. ,in By assigning higher contrast loss weights to recently collected user samples based on the time interval between the user data collection time and the current time, the model becomes more sensitive to the occurrence of electricity theft. This design aligns with the time-varying nature of electricity consumption behavior.

[0095] Innovation Point Five: A multi-loss collaborative mechanism for extreme imbalance: Three loss functions form a closed loop. FocalLoss handles class imbalance (focusing on hard-to-classify electricity theft samples), temporal contrastive loss learns representations using massive amounts of unlabeled data (label-independent), and the community graph constraint term uses community structure to suppress false positives against legitimate users. All three are indispensable, and ablation experiments quantitatively demonstrate the independent contribution of each component.

[0096] Example

[0097] The proposed STCL-GL electricity theft detection system comprises four core modules: a data preprocessing and graph construction module, a Transformer encoder module, a spatiotemporal graph contrastive learning joint training module, and an electricity theft detection inference module. The connections between these modules are as follows: the output of the data preprocessing and graph construction module is connected to both the Transformer encoder module (providing encoding input) and the spatiotemporal graph contrastive learning joint training module (providing the community constraint matrix); the output of the Transformer encoder module is connected to the spatiotemporal graph contrastive learning joint training module (providing encoding and projection features); after training, the output of the Transformer encoder module is connected to the electricity theft detection inference module. The four modules are executed sequentially in the order S1→S2→S3→S4, where module S3 has a feedback loop (gradient backpropagation of the contrastive loss) from the Transformer encoder module during the training phase.

[0098] For step S1 (data preprocessing and graph construction module), this embodiment uses the London Smart Meters dataset as an example. This dataset contains half-hour electricity consumption records for more than two years for N = 5567 London households, each user is labeled with an ACORN geographic demographic group (K = 17 community categories). First, time aggregation is performed: the original half-hour electricity consumption is aggregated into 6 time periods (0-4h, 4-8h, 8-12h, 12-16h, 16-20h, 20-24h) by 4 hours, and the electricity consumption of each time period is the average of the 8 half-hour readings in that time period multiplied by 2.0 (converted to kWh). Then, weekly aggregation is performed: the daily electricity consumption series after 4-hour aggregation is superimposed by week to obtain the weekly electricity consumption feature series for each user. ,in This represents the total number of time steps after weekly aggregation. Next, a community graph is constructed: using all N users as nodes and ACORN community affiliation as the basis for edges, while also introducing a consumption pattern similarity correction coefficient. Calculate the adaptive edge weights according to the formula in step S1. Then, the adjacency matrix W is constructed, and the community relationship constraint matrix L is calculated. Here, the Gaussian kernel bandwidth parameter... The value is taken as the standard deviation of the average electricity consumption of all users. The physical meaning of this graph structure is that there is a valid connection between two users if and only if they belong to the same ACORN community and have similar consumption levels. The connection weight decreases exponentially as the difference in consumption increases.

[0099] For step S2 (Transformer encoder module), its structure from input to output is as follows: Conv1D downsampling layer, sinusoidal position encoding layer, Transformer encoder stack layer (total... The Transformer encoder consists of several layers, including a global pooling layer (a concatenation of mean pooling and max pooling). Specific parameter configurations are: downsampling convolution kernel size of 4 and stride of 2, compressing the input sequence length from T to T / 2; each layer contains 8 self-attention heads and a 640-dimensional feedforward network, with a hidden layer dimension of 160; a Dropout rate of 0.1; and the activation function is GELU. The encoder output dimension is... The Conv1D downsampling layer extracts local patterns and compresses the length of the original weekly electricity consumption sequence to reduce the computational complexity of subsequent self-attention calculations; the position encoding layer injects temporal position information into the sequence, enabling the Transformer to perceive the temporal structure of the electricity consumption data; the multi-layer self-attention mechanism captures long-range dependencies in the electricity consumption data by calculating the attention weights between any two time steps in the sequence, such as the periodic patterns of weekdays and weekends, seasonal trend changes, etc.; the global pooling layer encodes the variable-length sequence into a fixed-dimensional feature vector, which serves as the input for downstream tasks (classification and contrastive learning).

[0100] For step S3 (Spatiotemporal Graph Comparative Learning Joint Training Module), this module is the core innovation of this invention, and its workflow consists of four steps. The first step is data augmentation: For the input samples of each training batch, two random data augmentation operations are applied—additive Gaussian noise (jitter, standard deviation of 0.05) and multiplicative random scaling (scale, scaling factor follows a normal distribution with mean 1.0 and standard deviation 0.15). An additional random temporal mask (mask ratio 8%) is applied with a 50% probability, generating two different augmented views. and The second step, encoding and projection: input the enhanced view into the Transformer encoder module to obtain the encoded features. Then, the normalized projected features are obtained through a projection head (a two-layer fully connected network containing batch normalization and ReLU activation functions, which maps the 320-dimensional encoded features to a 128-dimensional projection space). The third step is joint calculation of multiple losses: simultaneously calculating three loss functions—time comparison loss. The data acquisition time decay weight was introduced. This weight assigns a higher loss weight (decay rate parameter) to more recent time steps in the sequence. ), encouraging the model to pay more attention to recent changes in users' electricity consumption behavior; community graph constraints Using the community relationship constraint matrix constructed in step S1, calculate the sum of squared projected feature distances for all pairs of community neighbors, driving users within the same community to be closer to each other in the representation space; Focal Loss classification loss. Using focus parameters and category weight (Electricity theft category) This allows the model to focus on difficult-to-classify electricity theft samples, mitigating the impact of extreme class imbalance. The weight coefficients of the three loss terms are set as follows: , The fourth step, gradient backpropagation and parameter update: The total loss... All parameters of the Transformer encoder, projector head, and classifier head are updated simultaneously via backpropagation, using the AdamW optimizer with an initial learning rate of [missing value]. The weight decay coefficient is With the cosine annealing learning rate scheduling strategy, the maximum number of training rounds is 80, and the early stopping patience value is 30 rounds.

[0101] The working principle of the spatiotemporal graph contrastive learning joint training module lies in the mutually reinforcing closed-loop collaborative mechanism formed by three loss functions, which specifically address the three technical problems mentioned in the background. The temporal contrastive loss (self-supervised) solves the problem of unusable massive amounts of unlabeled data: it does not rely on electricity theft labels, but only on the consistency constraints of representations between two augmented views of the same user, enabling the learning of discriminative temporal representations from the electricity consumption data of all users (including the vast majority of unlabeled users). The community graph constraint term solves the problem of ignoring graph structure information: it utilizes the graph structure constructed from community affiliation relationships to impose smoothing constraints on users within the same community in the representation space, naturally forming clusters of normal users, while the representations of electricity thieves (whose electricity consumption behavior deviates from the community's collective pattern) are pushed out of these clusters. FocalLoss solves the problem of extreme class imbalance: by reducing the loss weights of easily classifiable samples, it focuses the training process on truly difficult electricity theft samples, rather than being dominated by a large number of easily classifiable normal samples. All three components are indispensable: without temporal contrast loss (ablation experiments show PR-AUC drops to 38.95%), the encoder relies solely on a very small number of labeled samples for training, failing to learn high-quality representations; without graph regularization (PR-AUC drops to 31.73%), community structure priors cannot be injected, and the model loses a crucial means of constraining false positives; without Focal Loss and using ordinary cross-entropy (PR-AUC drops to 33.63%), class imbalance causes the model to favor the majority class. It is the synergistic effect of these three components that enables this invention to achieve detection accuracy superior to existing methods at an extreme electricity theft rate of 5%.

[0102] For step S4 (electricity theft detection inference module), after training is complete, the electricity consumption sequence of the user to be detected is input into the Transformer encoder module, and the probability that the user belongs to the electricity theft category is output by the classification head. On the validation set, based on the preset recall target (set to 85% in this embodiment, meaning at least 85% of genuine electricity theft users must be detected), the optimal decision threshold is determined using the precision-recall curve. For any user in the test set, if If the user is identified as a user stealing electricity, they are considered a normal user.

[0103] To verify the technical effectiveness of this invention, method comparison and ablation experiments were conducted on the London Smart Meters dataset. Existing methods compared included: XGBoost (a gradient boosting tree based on 20-dimensional hand-crafted statistical features), CNN-LSTM (a combination of convolutional and bidirectional LSTM networks), ResNet-1D (a one-dimensional residual convolutional network), LSTM (a bidirectional LSTM network), and Transformer (a pure Transformer encoder). The evaluation metric used was PR-AUC (area under the precision-recall curve), which comprehensively measures the overall detection performance under different decision thresholds, and is particularly suitable for imbalanced class scenarios. The experiments were conducted with the training, validation, and test sets hierarchically divided in an 8:1:1 ratio, with a 5% electricity theft injection rate.

[0104] The experimental results comparing the methods are shown in Figure 1. Under the condition of an extreme electricity theft rate of 5%, the PR-AUC of the STCL-GL method of this invention reaches 41.26%, surpassing existing methods such as XGBoost (36.33%), CNN-LSTM (39.84%), ResNet-1D (28.05%), and Transformer (34.37%). This result verifies that the present invention effectively compensates for the shortcomings of existing supervised learning methods in extreme imbalance scenarios by introducing community graph structure information.

[0105] The ablation experiment results are shown in Figure 2 and Table 1. To verify the independent contribution of each core component, the complete model and the model with graph regularization terms removed (assuming...) were tested respectively. ), removal time comparison loss (assuming) ) and pure supervision model ( Four configurations are available. The meanings of each evaluation metric are as follows: PR-AUC (area under the precision-recall curve) comprehensively measures the detection performance under different decision thresholds and is the core evaluation metric for class imbalance scenarios; ROC-AUC (area under the receiver operating characteristic curve) measures the overall ability of the model to distinguish between positive and negative samples; F1 score is the harmonic mean of precision and recall, calculated at a preset recall threshold of 85%.

[0106] Table 1: Ablation Experiment Results (5% Electricity Theft Rate)

[0107]

[0108] As shown in Table 1, the complete STCL-GL model performs well and evenly across all three metrics. Removing the graph regularization term reduces PR-AUC by 10.68 percentage points (25.2%) and F1 by 2.76 percentage points (21.8%), indicating that the community graph constraint effectively suppresses false positives against normal users through community priors, and is a key component for maintaining overall performance under extreme imbalance. Removing the temporal contrastive loss reduces PR-AUC by 3.46 percentage points. While F1 slightly improves, the model loses its ability to learn representations from unlabeled data, impairing generalization. In the pure supervised mode, lacking two self-supervised components, PR-AUC decreases by 8.78 percentage points (20.7%), validating the necessity of the self-supervised contrastive learning framework for improving detection performance. The ablation data quantitatively demonstrates that the three core components—time-contrast loss, community graph constraint, and Focal Loss classification loss—form a mutually reinforcing closed-loop system, all of which contribute significantly to detection performance, with the community graph constraint contributing the most.

[0109] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A method for detecting electricity theft by power users based on graph contrastive learning, characterized in that, The steps include the following: Step 1: By collecting electricity consumption data from multiple users and at multiple time periods, performing time-series aggregation and noise reduction, and constructing a community graph with adaptive weights based on community geographic grouping, the community relationship constraint matrix is ​​calculated. The normalized graph Laplace constraint matrix, the user aggregated electricity consumption sequence, and the adaptive adjacency matrix are obtained. Degree matrix ; Step 2: Based on the user aggregated electricity consumption sequence output in Step 1, fixed-dimensional user temporal coding features are obtained through one-dimensional convolutional downsampling, position encoding, multi-layer Transformer self-attention encoding, and global pooling. Step 3, based on the community constraint matrix obtained in Step 1 The temporal coding features obtained in step 2 are used for spatiotemporal graph comparison learning and multi-loss joint training to obtain a complete training model with optimized parameters. Step 4: Based on the Transformer encoder and classifier head trained in Step 3, extract features from the electricity consumption sequence of the user to be detected, output the electricity theft prediction probability, and combine the optimal threshold of the validation set to complete the binary classification of normal / electricity theft users.

2. The method for detecting electricity theft by power users based on graph contrast learning according to claim 1, characterized in that, Step 1 is as follows: Step 1.1: Obtain the original electricity consumption data matrix ,Include individual electricity users The electricity consumption at the half-hour level for each original time step is calculated; the original time-series data is aggregated by day / week, the sequence length is compressed, and random fluctuations are eliminated to obtain the aggregated electricity consumption sequence for a single user. ; Step 1.2, with all Each user is a graph node set. Basic edge sets are constructed based on ACORN geographic community grouping. Only when user , In the same community An adaptive adjacency matrix is ​​constructed by introducing a consumption similarity correction factor. The formula for calculating matrix elements is: ; in For indicator functions, Let be the similarity coefficient of consumer behavior, and the similarity coefficient... Calculated using Gaussian kernel: in For users Average electricity consumption The preset Gaussian kernel bandwidth parameters; Step 1.3, based on the adaptive adjacency matrix Calculate the degree matrix The diagonal elements satisfy , The identity matrix is ​​used; substituting it into the formula, the community relationship constraint matrix is ​​calculated:

3. The method for detecting electricity theft by power users based on graph contrast learning according to claim 2, characterized in that, Step 2 is as follows: Step 2.1, output the single-user electricity consumption sequence from Step 1. Inputting a Conv1D one-dimensional convolutional layer completes sequence downsampling, compressing the time length and extracting local power consumption patterns; Step 2.2: Superimpose sinusoidal position codes on the downsampled sequence and inject temporal position information to enable the model to perceive the sequential relationship of electricity consumption. Step 2.3: Feed the position-encoded sequence into the stack. The layered Transformer encoder relies on a multi-head self-attention mechanism to capture long-term temporal dependencies in power consumption. Each layer is configured with multi-head attention and feedforward networks, GELU activation, and Dropout regularization. Step 2.4: Perform global pooling on the time-series features output by the Transformer, concatenating the mean and maximum values, to output a fixed-dimensional feature. User time-series coding features .

4. The method for detecting electricity theft by power users based on graph contrast learning according to claim 3, characterized in that, Step 3 specifically involves: Step 3.1, Data Augmentation to Generate Dual Views: Apply random noise jitter and random scaling to the user electricity consumption sequence output in Step 1, and optionally a random time mask, to generate two sets of augmented views. and ; Step 3.2, Feature Projection: Input the two sets of enhanced views into the Transformer encoder of Step 2 to obtain the encoded features. and The projection features are obtained by mapping to a low-dimensional projection space through two fully connected projection heads and then normalizing the projection. and The projection feature matrix is ​​obtained by summarizing all view features; Step 3.3, calculate the time-decayed weighted time contrast loss. : ① Define a data collection time decay weight, assigning higher weight to recently collected user samples: in For users The time interval between the most recent data collection and the current time in electricity consumption data. The total time span for data collection from all users. This is the decay rate parameter; ② Using the InfoNCE loss framework, two views within the same user are considered positive sample pairs, and views across users are considered negative sample pairs. The loss formula is as follows: in For cosine similarity, For temperature parameters, for Positive samples; Step 3.4, based on the community constraint matrix output in Step 1 Calculate the community graph regularization constraint loss. The formula for constraining the distance between projected features of users in the same community using matrix trace operations is as follows: in The projection feature matrix for all enhanced views. Represents the trace of a matrix; Step 3.5, calculate Focal Loss (classification loss). To address the imbalance of extreme categories in electricity theft detection, the formula is: in This represents the model's predicted probability of the true class. To focus parameters, Balance the weights for each category; Step 3.6: Weighted fusion of the three losses yields the total training loss, calculated using the following formula: in and These are the weighting coefficients for the time-contrast loss and the graph regularization term, respectively. Step 3.7, Optimizer backpropagation total loss The AdamW optimizer, cosine annealing learning rate, and early stopping strategy are used to synchronously update all network parameters of the Transformer encoder, projector head, and classifier head.

5. The method for detecting electricity theft by power users based on graph contrast learning according to claim 4, characterized in that, Step 4 specifically involves: Step 4.1: Input the original electricity consumption sequence of the user to be tested into the preprocessing flow of Step 1 to obtain the standardized aggregated electricity consumption sequence; Step 4.2: Feed the standardized sequence into the Transformer encoder trained in Step 3, extract the temporal coding features and input them into the classification head, outputting the predicted probability of the user stealing electricity. ; Step 4.3: During the model training phase, a PR curve is plotted on the validation set based on a preset recall target to determine the optimal classification decision threshold. ; Step 4.4, perform a judgment on the user to be tested: if If the electricity is stolen, the user is considered a legitimate electricity user; otherwise, the user is considered a legitimate electricity user.