Skip to content
Federated dual-attention temporal convolutional networks for privacy

Federated dual-attention temporal convolutional networks for privacy

Nature • November 16, 2026

The rapid growth of electric vehicles (EVs) is driving equally rapid deployment of charging infrastructure, turning Electric Vehicle Supply Equipment (EVSE) into a critical part of modern cyber-physical energy systems 1 , 2 . Unlike traditional electrical assets, contemporary charging stations combine power electronics, embedded software, network connectivity, backend cloud services, and user-facing applications within a single operational stack 3 , 4 . As a result, securing EV charging infrastructure is now a systems problem spanning transportation, energy, and communications.

This expanded functionality depends on interoperable communication standards such as the Open Charge Point Protocol (OCPP) and ISO 15118 5 , 6 , 7 . These protocols enable remote management, billing, smart charging, and Plug and Charge workflows, but they also enlarge the attack surface by exposing chargers to network-facing services, credential exchange, and software-controlled operating modes 3 , 8 . The resulting risks are no longer hypothetical: the Brokenwire attack demonstrated wireless disruption of Combined Charging System (CCS) sessions without physical 9 , while broader analyses have documented denial-of-service, man-in-the-middle, remote-control, and firmware-level vulnerabilities across real deployments 4 , 6 , 10 . Such threats extend beyond IT compromise to interrupted charging sessions, degraded user trust, and potential effects on grid-facing operations.

Machine learning has emerged as a promising response because it can model complex behavior and detect attack patterns that are difficult to encode with static rules. Prior work has shown strong results for in-vehicle CAN-bus intrusion detection 11 , 12 and, more recently, for EVSE-focused datasets and testbeds 13 , 14 , 15 , 16 . In particular, the CICEVSE2024 benchmark provides synchronized network, host, and power measurements from physical EVSE experiments, enabling more realistic multimodal intrusion detection research 17 . However, recent studies on this benchmark have used centralized or single-site training settings, which do not align well with real deployments in which charging operators are distributed and may be unable or unwilling to pool raw operational data.

Federated learning addresses this tension by training a shared model through parameter exchange rather than raw-data transfer 18 . Yet federated optimization is challenging: heterogeneous local data and fragmented client views often create a performance gap relative to centralized training 19 . Survey literature identifies privacy-preserving learning as highly relevant to connected and electric-vehicle ecosystems 20 , but its application to EVSE intrusion detection remains limited. This paper therefore asks whether a carefully designed federated model can retain the privacy advantages of decentralized training while remaining competitive with, or even surpassing, a centralized EVSE intrusion detector.

To answer this question, we develop a federated intrusion detection framework built around Temporal Convolutional Networks (TCNs), which provide causal sequence modeling, stable gradient propagation, and efficient parallel computation. The principal contributions are:

Dual-attention TCN architecture: We propose DA-TCN, which combines dilated causal convolutions with Squeeze-and-Excitation (SE) channel attention and multi-head temporal attention to jointly model feature importance and temporal dependencies in multimodal EVSE telemetry.

Dual-attention TCN architecture: We propose DA-TCN, which combines dilated causal convolutions with Squeeze-and-Excitation (SE) channel attention and multi-head temporal attention to jointly model feature importance and temporal dependencies in multimodal EVSE telemetry.

Federated stochastic weight averaging (FedSWA): We introduce a federated weight-averaging strategy that maintains a running average of global models across communication rounds, stabilizing optimization and improving generalization beyond standard FedAvg.

Federated stochastic weight averaging (FedSWA): We introduce a federated weight-averaging strategy that maintains a running average of global models across communication rounds, stabilizing optimization and improving generalization beyond standard FedAvg.

Client-local mixup augmentation: Each client independently applies mixup interpolation during local training to increase data diversity without sharing raw samples, preserving privacy while reducing overfitting.

Client-local mixup augmentation: Each client independently applies mixup interpolation during local training to increase data diversity without sharing raw samples, preserving privacy while reducing overfitting.

Hybrid detection pipeline: We combine supervised DA-TCN classification with unsupervised Isolation Forest anomaly detection to strengthen detection of previously unseen threats.

Hybrid detection pipeline: We combine supervised DA-TCN classification with unsupervised Isolation Forest anomaly detection to strengthen detection of previously unseen threats.

State-of-the-art federated performance: The federated model surpasses the centralized baseline (99.29% vs. 98.79% accuracy; 99.10% vs. 98.65% macro F1), with 8.26 ms inference latency and a 4.07 MB model size suitable for real-time edge deployment.

State-of-the-art federated performance: The federated model surpasses the centralized baseline (99.29% vs. 98.79% accuracy; 99.10% vs. 98.65% macro F1), with 8.26 ms inference latency and a 4.07 MB model size suitable for real-time edge deployment.

Comprehensive robustness analysis: Sensitivity studies confirm graceful performance under differential privacy noise (at least 98% accuracy up to \(\sigma = 0.3\) ), stable scalability up to 10 clients, and robust accuracy across non-IID data heterogeneity (within a 97.9–98.7% band over all Dirichlet settings).

Comprehensive robustness analysis: Sensitivity studies confirm graceful performance under differential privacy noise (at least 98% accuracy up to \(\sigma = 0.3\) ), stable scalability up to 10 clients, and robust accuracy across non-IID data heterogeneity (within a 97.9–98.7% band over all Dirichlet settings).

The remainder of this paper is organized as follows. The section reviews related work on EV charging security, temporal modeling for intrusion detection, and federated learning. Subsequent sections detail the proposed methodology, present experimental results, and their implications. The paper concludes with a summary of findings and directions for future research.

Research on EV cybersecurity spans multiple interconnected domains, from in-vehicle network protection to charging infrastructure defense and privacy-preserving distributed learning. This section reviews the relevant literature across these areas, identifies persistent gaps, and positions the present work within the broader landscape 1 .

In-vehicle network intrusion detection

Modern vehicles rely on networks of Electronic Control Units (ECUs) that exchange messages over Controller Area Network (CAN) and, increasingly, automotive Ethernet. CAN in particular lacks native authentication, making message spoofing and injection persistent concerns 12 , 21 . Early in-vehicle intrusion detection studies applied deep neural networks directly to CAN traffic 21 , while later work adopted temporal models such as LSTMs to capture sequential attack behavior 22 , 23 . CNN-based approaches have also been explored by transforming CAN traces into structured representations such as recurrence plots 24 .

These studies establish the importance of temporal modeling for automotive cybersecurity, but their scope is primarily in-vehicle communication. EV charging infrastructure poses a broader problem because it couples vehicle-side communication with backend services, charger host activity, and power-side telemetry, all of which must be considered in a practical EVSE intrusion detector.

Charging infrastructure vulnerabilities

Beyond the vehicle itself, comprehensive assessments have revealed vulnerabilities across communication protocols, upstream cloud services, and charger-side software in EV charging infrastructure 3 , 4 , 8 . OCPP has been repeatedly identified as a critical attack surface because charging stations and central management systems depend on it for command and control 5 , 6 . Experimental studies have demonstrated that weaknesses in charging workflows can enable denial-of-service, man-in-the-middle, and remote code execution scenarios under realistic conditions 10 . ISO 15118 introduces further security-sensitive exchanges around authorization and vehicle-to-grid interactions, making protocol robustness essential to trustworthy charging operation 7 . Collectively, these findings motivate defense mechanisms tailored to the operational and protocol realities of EV charging systems rather than borrowed unchanged from generic enterprise networks.

Datasets for EV charging security

The development of data-driven security solutions depends on representative datasets. Public EV charging datasets such as ACN-Data are valuable for charging-behavior and grid studies, but they were not designed for cybersecurity evaluation 25 . The CICEV2023 dataset introduced a benchmark for DDoS attacks against EV authentication in charging infrastructure 26 . CICEVSE2024 substantially broadens this foundation by collecting synchronized network traffic, host activities, and power-consumption measurements from physical EVSE testbeds under benign and attack conditions 17 . Its multimodal structure makes it a strong benchmark for evaluating modern EVSE intrusion detection methods.

Machine learning for EVSE intrusion detection

Recent studies built on CICEVSE2024 have demonstrated that the benchmark supports high-performing EVSE attack detection. Kumar et al. investigate machine-learning models on the CICEVSE2024 benchmark 13 . Almadhor et al. study transfer learning for cyber-physical attack detection in EV charging infrastructure 14 , while Naeem et al. combine deep transfer learning with genetic-algorithm-based optimization for vehicle-security classification tasks that include CICEVSE data 15 . Makhmudov et al. focus on online intrusion detection for EV charging systems, highlighting the importance of adaptation under changing traffic conditions 16 . Despite this methodological diversity, the published studies remain centralized or single-site in training setup, leaving privacy-preserving collaborative learning largely unexplored for EVSE intrusion detection.

Temporal convolutional networks for sequential anomaly detection

One-dimensional CNN architectures have been applied to a range of sequential classification problems, including environmental time-series prediction 27 , sensor-based human activity recognition 28 , and audio event classification 29 , establishing convolutional feature extraction as an effective alternative to recurrent modeling for temporal data. Temporal Convolutional Networks (TCNs) have emerged as a compelling alternative to recurrent architectures for sequence modeling tasks, addressing well-documented limitations of RNN and LSTM models such as vanishing gradients and constrained sequential computation 30 . Introduced by Bai et al. 31 , TCNs use dilated causal convolutions to capture long-range dependencies while preserving temporal ordering and enabling parallel training. These properties are attractive for security analytics, where low-latency inference and stable optimization are often as important as raw accuracy.

In the broader network-security literature, TCN-based models have been used for abnormal traffic detection 32 , and attention-augmented bidirectional TCN variants have improved malicious traffic classification by learning which temporal patterns deserve greater weight 33 . For EVSE security, this design space is especially relevant because attacks unfold across multiple time scales and across heterogeneous telemetry streams. Nevertheless, we did not find prior work applying a dual-attention TCN architecture to federated EVSE intrusion detection.

Federated learning and privacy-preserving detection

Federated learning enables collaborative model training through the exchange of model updates rather than raw data, preserving privacy in distributed environments 18 . FedAvg remains the standard baseline, while extensions such as FedProx address optimization instability under heterogeneous client data 19 . In the EV domain, survey literature has identified federated learning as a promising direction for privacy-preserving analytics across connected and electric-vehicle ecosystems 20 . More recently, decentralized anomaly detection for EVSE has been explored by combining federated learning with blockchain integration 34 , reinforcing the need to benchmark EVSE intrusion detectors against established federated baselines such as FedAvg and FedProx. More broadly, a growing body of work integrates explainability, blockchain, and weighted or fuzzy aggregation into federated learning for secure energy management, vehicular networks, and cyber-intrusion detection 35 , 36 , 37 , 38 , 39 , 40 ; our work complements these directions by targeting privacy-preserving, temporally-aware intrusion detection for EVSE with a dual-attention TCN and FedSWA. However, the available EVSE intrusion-detection literature on CICEVSE2024 continues to center on centralized learning 13 , 14 , 15 , 16 .

A persistent challenge in federated learning is the accuracy gap relative to centralized training, especially when clients hold limited or non-identically distributed data. Stochastic Weight Averaging (SWA) improves generalization in centralized optimization by averaging weights along the training trajectory 41 . Likewise, mixup regularization improves robustness by interpolating between training samples 42 . Although both ideas are well established in centralized learning, their use as federated optimization tools for EVSE intrusion detection remains underexplored.

Research gaps and positioning

Despite considerable progress, three specific gaps motivate the present work:

1. Limited privacy-preserving learning for EVSE IDS: To the best of our knowledge, published studies on CICEVSE2024-based intrusion detection have used centralized or single-site training, leaving federated evaluation on this benchmark unaddressed.

Limited privacy-preserving learning for EVSE IDS: To the best of our knowledge, published studies on CICEVSE2024-based intrusion detection have used centralized or single-site training, leaving federated evaluation on this benchmark unaddressed.

2. Underexplored temporal modeling for multimodal EVSE telemetry: Prior EVSE studies emphasize transfer learning, online tree-based learners, or other centralized classifiers. TCN-based sequence modeling has not been established on this benchmark despite the inherently temporal nature of attack behavior.

Underexplored temporal modeling for multimodal EVSE telemetry: Prior EVSE studies emphasize transfer learning, online tree-based learners, or other centralized classifiers. TCN-based sequence modeling has not been established on this benchmark despite the inherently temporal nature of attack behavior.

3. Limited study of federated optimization strategies for EVSE security: Techniques such as SWA and mixup are well known in centralized learning, but their adaptation to federated EVSE intrusion detection has not been systematically examined.

Limited study of federated optimization strategies for EVSE security: Techniques such as SWA and mixup are well known in centralized learning, but their adaptation to federated EVSE intrusion detection has not been systematically examined.

The present work addresses these gaps by proposing a federated DA-TCN framework that combines temporal modeling with federated optimization enhancements for privacy-preserving EVSE intrusion detection on CICEVSE2024.

The proposed framework comprises five integrated components: (1) data preprocessing with synthetic oversampling to address class imbalance, (2) a Dual-Attention Temporal Convolutional Network (DA-TCN) architecture combining dilated causal convolutions, Squeeze-and-Excitation (SE) channel attention, and multi-head temporal attention for attack pattern recognition, (3) a federated learning protocol with Federated Stochastic Weight Averaging (FedSWA) enabling collaborative model training across distributed EVSE operators while preserving data locality, (4) client-local mixup augmentation to enhance federated data diversity, and (5) Isolation Forest anomaly detection for zero-day threat identification. Both centralized and federated configurations the same DA-TCN architecture to ensure fair comparison; the federated advantage arises from FedSWA and client-local mixup. All experiments were conducted using PyTorch on machines equipped with NVIDIA GPUs, 16-core processors, and 16 GB RAM. Preprocessing and evaluation relied on NumPy, Pandas, and Scikit-learn (Fig. 1 ).

Dataset and preprocessing

The CICEVSE2024 dataset constitutes a comprehensive collection of network traffic data from Electric Vehicle Supply Equipment (EVSE) systems, specifically developed to advance cybersecurity research in electric vehicle charging infrastructure 17 . This study utilizes the EVSE-B HPC and Kernel Events dataset from the CICEVSE2024 collection, which contains network traffic and kernel event data from high-performance computing (HPC) enabled electric vehicle supply equipment under various attack scenarios.

The CICEVSE2024 dataset ensures diversity through multiple dimensions relevant to cybersecurity: (1) network noise from varying packet latencies, jitter, and transmission conditions; (2) acquisition diversity through data captured from HPC EVSE testbeds under both idle and active charging operational states; and (3) attack diversity spanning four major categories with multiple sub-variants, ensuring robustness against varying threat profiles encountered in real-world deployments.

The raw dataset, comprising 82 columns expanded to 210 features after feature engineering, underwent a rigorous preprocessing pipeline. The process began by filtering out non-informative columns and records without valid ‘attack’ or ‘benign’ labels. Attack variants were consolidated into four primary categories: Benign, Cryptojacking, Reconnaissance, and Denial-of-Service (DoS). Two problematic features with constant values were removed from the 210 engineered features, yielding the final 208-dimensional feature space (99.05% feature retention).

The preprocessing pipeline follows a modular, five-stage architecture: data ingestion and exploration, comprehensive data cleaning, advanced feature engineering (including Interquartile Range outlier detection and correlation-based feature importance analysis), class balancing using SMOTE and ADASYN with fallback mechanisms, and temporal sequence generation.

To prevent data leakage, we implemented a strict split-before-sequence protocol. The dataset was first divided into training (70%) and testing (30%) sets using stratified random splitting, ensuring that class proportions are preserved in both partitions. Temporal sequences were then generated independently within each set using a 30-timestep sliding window with stride 1. This ensures that no individual data point contributes to sequences in both training and testing phases, maintaining evaluation integrity.

The data are partitioned before sequence construction to avoid temporal leakage, using a stratified 70/30 train/test split with a fixed seed (42) that yields 6415 training and 1821 test sequences. From the training partition, a further 15% is held out as a stratified validation set used solely for early stopping and model-checkpoint selection, so the 1821-sequence test set remains untouched and is used only once, for final reporting. All architectural and optimization hyperparameters ( \(\eta = 0.001\) , \(T = 30\) , \(h = 8\) , \(p = 0.3\) , \(B = 64\) ) were fixed a priori from the sensitivity analysis (Table 4 ) and prior work rather than tuned on the test set. k -fold cross-validation was not adopted because repeated temporal sequencing and full federated client reconstruction ( K clients \(\times \) R rounds) per fold would multiply an already heavy training budget without materially changing the conclusions, which are already supported by our sensitivity, non-IID, scalability, and ablation analyses.

The primary evaluation uses multi-class classification for specific attack type identification, with binary classification evaluated as a secondary scenario. Each dataset maintains consistent feature representations while optimizing target variable encodings for the specific classification objective.

Proposed model architecture

The proposed framework employs a Dual-Attention Temporal Convolutional Network (DA-TCN) that combines channel-wise Squeeze-and-Excitation (SE) attention with multi-head temporal attention to capture which features and which timesteps are most relevant for attack detection, while maintaining computational efficiency for real-time deployment.

The architecture consists of three hierarchical temporal blocks with progressively increasing channel dimensions \(\{64, 128, 256\}\) , each implementing a residual structure with two convolutional layers, batch normalization, dropout regularization, and a Squeeze-and-Excitation block for adaptive channel recalibration. Xavier uniform initialization ensures stable gradient flow. Dilation rates \(D=\{1,2,4\}\) combined with kernel size \(k=5\) yield a receptive field of \(r=(k-1)\cdot \sum _i d_i + 1 = 29\) timesteps, sufficient to cover the full sequence length \(T=30\) . The multi-head attention module uses \(h = 8\) heads with key dimension \(d_k = 32\) and model dimension \(d_{\text {model}} = 256\) . Training employed early stopping with patience of 3 epochs, monitoring validation loss to prevent client-side overfitting.

Temporal convolutional network

Table 1 summarizes the architectural components. Each temporal block incorporates a Squeeze-and-Excitation (SE) channel attention mechanism applied after the residual connection. The SE block adaptively recalibrates channel-wise feature responses by explicitly modeling inter-channel dependencies. Given an intermediate feature map \(\textbf{U} \in \mathbb {R}^{C \times T}\) from the residual output, the SE block first squeezes the temporal dimension via global average pooling, then applies a two-layer bottleneck to produce channel attention weights:

where \(\bar{\textbf{u}} = \frac{1}{T}\sum _{t=1}^{T}\textbf{U}_{:,t} \in \mathbb {R}^C\) is the channel-wise mean, \(\textbf{W}_1 \in \mathbb {R}^{(C/r) \times C}\) and \(\textbf{W}_2 \in \mathbb {R}^{C \times (C/r)}\) are learned projections with reduction ratio \(r=16\) , \(\sigma \) denotes the sigmoid function, and \(\odot \) is channel-wise multiplication. This mechanism allows each block to learn which features are most informative for attack detection, suppressing irrelevant channels and amplifying discriminative ones.

Following the temporal convolution layers, the network applies 8-head self-attention to the temporal dimension, enabling dynamic weighting of different time steps based on their relevance to the classification task. The attention mechanism computes:

where Q , K , and V represent the query, key, and value projections of the input features, and \( d_k \) is the dimension of each attention head. This mechanism allows the model to learn long-range dependencies and focus on critical temporal segments that may indicate attack patterns. The classifier head employs a two-layer fully connected architecture with progressive dimension reduction 256 \(\rightarrow \) 128 \(\rightarrow \) classes . The hidden layer incorporates batch normalization and dropout (rate 0.5), providing robust regularization against overfitting. The use of adaptive average pooling before the classifier ensures consistent input dimensions regardless of sequence length variations.

The federated learning framework implements federated averaging with support for heterogeneous client configurations. Each client trains a local copy of the global model in isolation, ensuring that raw data never leaves the client’s domain. The Adam optimizer with a learning rate of 0.001 is used for local training, chosen for its adaptive properties that accommodate varying data distributions across clients. Table 2 details the federated configuration.

Each client trains for 3 local epochs per round using cosine annealing warm restarts for learning rate scheduling, while stratified random splitting maintains class balance across clients. The global model update is defined as follows:

where \( w_k^{(t+1)} \) represents the updated weights from client \( k \) after local training in round \( t+1 \) , \( n_k \) is the number of training samples on client \( k \) , and \( n = \sum _k n_k \) is the total sample count across all clients.

The federated learning protocol coordinates training across distributed EVSE operators as presented in Algorithm 1. The protocol initializes global model parameters and iterates through communication rounds in which a subset of clients is selected for training, providing flexibility for operators with varying computational resources.

The client training process implements local stochastic gradient descent optimization on each operator’s private dataset, as detailed in Algorithm 2. This approach reduces communication overhead while allowing sufficient local adaptation to each operator’s specific network characteristics and threat patterns.

The local training objective for client k is expressed in Eq. ( 4 ).

where \(f_{\theta }(\textbf{x})\) represents the output of the temporal block network with parameters \(\theta \) , \(\ell \) denotes the loss function appropriate for the detection task, and \(\mathscr {R}(\theta )\) implements regularization to prevent overfitting. The regularization term is particularly important in federated settings where each client may have limited data diversity.

Both centralized and federated configurations the same DA-TCN architecture to enable direct comparison. For centralized training, a single model is trained on the complete dataset without mixup augmentation. The federated training process distributes data across clients via random permutation, ensuring each client receives a representative sample. Each communication round consists of three phases: (i) global model distribution to clients, (ii) local training with client-local mixup on private data, and (iii) aggregation of updated weights followed by FedSWA accumulation. This process iterates for 25 rounds, with validation performed after each round to monitor convergence.

Client-local mixup augmentation

To enhance the diversity of local training, each federated client independently applies mixup augmentation during local training. For a mini-batch of training pairs \(\{(\textbf{x}_i, y_i)\}\) , client k samples a mixing coefficient \(\lambda \sim \text {Beta}(\alpha , \alpha )\) with \(\alpha = 0.3\) , clamped to \(\lambda \leftarrow \max (\lambda , 1-\lambda )\) to ensure the original sample dominates the interpolation, and constructs interpolated training examples:

where \((\textbf{x}_j, y_j)\) is a randomly permuted sample from the same mini-batch. Critically, mixup is applied only during federated client training; the centralized baseline trains without augmentation. This design creates an asymmetric advantage: each client independently mixes different sample pairs, and after FedAvg aggregation, the global model implicitly benefits from K distinct augmented data distributions. The resulting implicit ensemble diversity is unique to the federated setting and cannot be replicated in centralized training.

Federated stochastic weight averaging (FedSWA)

We introduce Federated Stochastic Weight Averaging (FedSWA), which formalizes the concept of Iterative Weight Smoothing described in our framework. After a warm-up phase of \(t_0\) rounds, FedSWA maintains a running average of global model weights across successive rounds:

where \(\theta _t\) is the global model after FedAvg at round t , \(\bar{\theta }_n\) is the SWA average after n accumulated rounds, and \(t_0 = 10\) is the SWA start round. The SWA-averaged model is hypothesized to reside in a wider basin of the loss landscape, yielding better generalization. To correct the batch normalization running statistics of the averaged model, a complete forward pass through the full training set is performed before evaluation.

The key asymmetry is structural: in federated training, each round produces a global model informed by K independently optimized trajectories (one per client). FedSWA thus averages across \(K \times R\) optimization paths, whereas centralized SWA would average over a single trajectory. This multi-trajectory averaging provides a richer exploration of the parameter space, explaining the federated model’s superior generalization.

We employ loss functions tailored to each detection scenario. For binary intrusion detection, we use binary cross-entropy loss:

For multi-class attack classification, the loss extends to C classes, where the softmax function normalizes raw outputs into a probability distribution and the one-hot encoded labels \(y_{i,c}\) ensure that only the correct class contributes to each sample’s loss:

Federated concept drift detection

Real-world EVSE networks experience concept drift as attack patterns evolve over time. Static models trained on historical data degrade in performance when confronted with novel attack variants or changing network conditions. To support long-lived deployments, we include a Federated Concept Drift Detection module using the ADWIN (Adaptive Windowing) algorithm to identify significant changes in error distribution. Note that because the CICEVSE2024 benchmark is a static dataset, ADWIN cannot be meaningfully evaluated against ground-truth drift events; we therefore describe the mechanism here for deployment completeness and defer empirical drift evaluation to future longitudinal studies.

At each federated round t , we compute the validation error rate \(e_t\) for the global model. ADWIN maintains a sliding window of recent error rates and detects drift when the difference between sub-window means exceeds a threshold:

where m is the harmonic mean of sub-window sizes, N is the total window size, and \(\delta \) is the confidence parameter. When drift is detected, the system triggers adaptive responses:

where \(\eta _0\) is the base learning rate. This adaptive learning rate mechanism accelerates model adaptation during drift periods while maintaining stable training otherwise. The drift detector operates at the global level, analyzing aggregated performance metrics across all clients to identify systemic changes in the threat landscape rather than client-specific fluctuations.

We evaluate both centralized and federated models using five standard classification metrics. Given C classes with true positives \(\textrm{TP}_c\) , false positives \(\textrm{FP}_c\) , false negatives \(\textrm{FN}_c\) , and true negatives \(\textrm{TN}_c\) for each class c , the metrics are defined as follows.

Accuracy measures the overall fraction of correctly classified samples:

where N is the total number of test samples.

Precision quantifies the proportion of predicted positives that are truly positive, averaged across classes:

Recall (sensitivity) captures the proportion of actual positives correctly identified, which is critical for detecting all attack instances in cybersecurity applications:

F1-Score provides the harmonic mean of precision and recall, balancing both false positive and false negative errors:

Area Under the ROC Curve (AUC-ROC) evaluates the model’s discriminative ability across all classification thresholds by plotting the true positive rate against the false positive rate for each class in a one-vs-rest scheme:

All metrics are computed using macro-averaging to weight each class equally, ensuring that minority attack categories (e.g., DoS) receive the same importance as dominant classes (e.g., Benign). Per-class confusion matrices, precision-recall curves, and prediction confidence distributions provide complementary insights into detection reliability across attack types.

Results and discussion

Dataset characteristics and preprocessing

The dataset underwent comprehensive preprocessing to prepare it for cybersecurity attack detection in electric vehicle charging infrastructure. As summarized in Table 3 , the original dataset containing 9208 samples and 210 features was cleaned to 6166 samples with 208 features after removing constant-value and near-zero-variance features and validating record consistency. The reduction in samples resulted from rigorous quality assurance measures including duplicate removal and outlier filtering. The cleaned data were first partitioned 70/30 into stratified training and test sets (4316 and 1850 samples). Class-balanced oversampling via SMOTE was then applied to the training partition only, balancing it to 6444 samples, after which a 30-timestep sliding window (stride 1) generated 6415 training and 1821 test sequences (each sequence count equals its sample count minus \(T-1\) ).

The final processed dataset demonstrates complete data integrity with zero missing values or infinite values. StandardScaler normalization was applied to ensure optimal convergence during neural network training. The raw class distribution—Benign (2302), Cryptojacking (1793), Reconnaissance (1145), DoS (926)—was balanced via SMOTE oversampling to produce uniform class proportions, ensuring unbiased model training.

Hyperparameter sensitivity analysis

Table 4 presents comprehensive sensitivity analysis across five key hyperparameters. The learning rate \(\eta \) exhibited high sensitivity, requiring careful tuning within [0.0005, 0.005] for stable convergence. Sequence length T showed medium sensitivity, with \(T \in [30, 50]\) providing optimal balance between temporal pattern capture and computational efficiency. The number of attention heads h demonstrated low sensitivity, remaining stable across [2, 16], suggesting that 8 heads provide sufficient representational capacity for most scenarios. The model also showed low sensitivity to batch size B (stable across [16, 256]), confirming architectural robustness to these configuration choices.

Given the critical role of temporal window size ( T ) in capturing attack patterns, we conducted additional in-depth analysis on this parameter. Shorter windows ( \(T = 10\) ) reduced computational overhead but failed to capture the multi-stage patterns characteristic of reconnaissance scans. Conversely, windows larger than 50 timesteps yielded diminishing returns in accuracy while increasing inference latency by 15%. The selection of \(T = 30\) represents the optimal equilibrium for real-time EVSE monitoring, balancing pattern capture capability against computational constraints.

Final parameters were selected based on optimal convergence observed during this ablation study, with the configuration \(\eta = 0.001\) , T = 30, h = 8, p = 0.3, and B = 64 providing the best overall performance.

Comparative performance analysis

Table 5 consolidates the preprocessing, architecture, training, and federated hyperparameters used throughout the experiments.

The federated learning approach with FedSWA and client-local mixup achieved superior performance, with an overall accuracy of 99.29% compared to 98.79% for the centralized model. This improvement of +0.50 percentage points demonstrates that privacy-preserving federated learning can match and exceed centralized training when augmented with appropriate techniques, while the consistent gains across all four metrics (accuracy, precision, recall, F1) indicate a systematic rather than incidental advantage. To confirm that this advantage is not an artifact of a single random seed, we repeated the comparison across four seeds under deterministic training: the federated model averaged \(99.11 \pm 0.13\%\) accuracy versus \(98.92 \pm 0.13\%\) for the centralized model and outperformed it in three of the four runs. All headline numbers are reported for the fixed seed \(=42\) used throughout, ensuring full reproducibility (Table 6 ).

To address the fairness of the federated comparison directly, we additionally benchmarked the two standard federated baselines, FedAvg and FedProx, under identical conditions (same 70/30 split, seed 42, \(K = 5\) clients, 25 rounds), with client-local mixup and FedSWA disabled so that the comparison isolates the aggregation strategy. Table 7 reports the results. Standard FedAvg reaches 98.79% accuracy (98.65% macro-F1). For FedProx, we tuned the proximal weight over \(\mu \in \{0.001, 0.01, 0.1\}\) and report the best configuration ( \(\mu = 0.001\) , 91.82% accuracy); the proximal term pulls each client back toward the shared global model and delays the mid-training representation breakthrough (Fig. 2 ) on this class-balanced partition, so within a fixed 25-round budget FedProx trails FedAvg. Our full framework, which layers FedSWA weight averaging and client-local mixup on top of FedAvg aggregation, attains the best result (99.29% accuracy, 99.10% macro-F1). This confirms that the improvement stems from the proposed techniques rather than from the base aggregation method, and that our method surpasses both established federated baselines.

This result may appear counterintuitive given the inherent data fragmentation in federated learning. As illustrated in Fig. 2 a, the centralized model exhibits rapid initial convergence, peaking at 98.79% accuracy at its best validation checkpoint (epoch 10) and plateauing near 98.5% from the third epoch onward.

We attribute the federated model’s advantage to three synergistic mechanisms. First, Federated Stochastic Weight Averaging (FedSWA) averages global model weights from round 10 onward, producing a model that resides in a wider basin of the loss landscape. The critical asymmetry is that FedSWA averages across \(K \times R\) independent optimization paths (5 clients \(\times \) 25 rounds), whereas centralized SWA would follow a single trajectory. Second, client-local mixup augmentation ( \(\alpha = 0.3\) ) creates implicit data diversity: each client independently mixes different sample pairs, and after FedAvg, the global model benefits from five distinct augmented distributions—a form of ensemble diversity unavailable to centralized training. Third, Squeeze-and-Excitation channel attention within each temporal block enables the model to adaptively weight the 208 input features, though this component benefits both approaches equally.

Training time analysis reveals that federated learning required substantially more wall-clock time (554.7 s vs. 72.3 s) due to sequential client simulation and 25 communication rounds. In real-world deployment, clients would train in parallel, reducing the effective time to approximately the cost of a single client per round. Notably, the federated model achieves lower inference latency (8.26 ms vs. 9.19 ms per batch), likely due to FedSWA producing smoother weight distributions. Both models maintain sub-15 ms inference times and model sizes of 4.07 MB, ensuring real-time detection capabilities and edge deployment feasibility.

Training dynamics and convergence analysis

Figure 2 a,b present the validation loss and accuracy progression for both approaches, revealing fundamentally different optimization trajectories. The federated learning trajectory exhibits a characteristic stepped improvement pattern over 25 rounds, with substantial gains in the middle rounds suggesting effective knowledge aggregation across clients.

The breakthrough occurs at Round 6 with a 19.7 percentage point accuracy jump (from 67.27 to 86.99%), suggesting that federated averaging across client-local mixup-augmented models consolidates into effective representations. Continued improvements through Rounds 10–25 demonstrate that FedSWA and extended training yield further gains beyond what the raw FedAvg model achieves alone. In contrast, the centralized approach peaks at 98.79% at epoch 10, with accuracy already plateaued from the third epoch. The consistent loss reduction pattern without oscillations indicates stable federated convergence.

The centralized model was trained for the full 10-epoch budget; validation accuracy plateaued near 98.5% from the third epoch onward, and the best validation-loss checkpoint occurred at epoch 10 (validation loss 0.0561, 98.79% accuracy). The complete per-epoch validation-loss trace (Table 8 ) confirms convergence, with accuracy flat while the loss fluctuated within a narrow band, rather than premature stopping. Extending training beyond the 10-epoch budget did not close the gap to the federated model (Table 9 ).

The round-by-round evolution reveals that the raw FedAvg model peaks at 99.29% accuracy (Round 25) while the FedSWA model steadily climbs to 98.85% by Round 25, demonstrating the smoothing effect of weight averaging across rounds. The best model is selected from whichever achieves higher accuracy at each round, combining the strengths of both approaches.

FedSWA convergence analysis

Figure 3 illustrates the convergence dynamics of FedSWA compared to the raw FedAvg model. Starting from Round 10, the SWA-averaged model begins to track the raw model but with reduced variance, confirming that weight averaging smooths the optimization landscape. The SWA model’s steady improvement—from 97.80% at Round 10 to 98.85% at Round 25—validates the hypothesis that averaging across multiple federated rounds produces a model in a wider basin of the loss landscape with better generalization properties. Here the raw FedAvg peak (99.29%) marginally exceeds the SWA model, so the reported federated result is taken as the best of the two per round; FedSWA’s primary contribution is reduced round-to-round variance and more stable convergence rather than a higher peak, consistent with its small ablation delta (Table 14 ).

Detailed classification performance analysis

The confusion matrices in Tables 10 and 11 provide per-class breakdowns of classification outcomes. Both approaches achieve excellent detection across all attack categories, with the federated model achieving perfect recall for benign traffic (680/680) and cryptojacking (524/524), while maintaining strong performance on DoS and reconnaissance.

The federated model achieves perfect recall for benign traffic, correctly identifying all 680 benign instances, and perfect recall for cryptojacking (524/524). The centralized model instead misclassifies 11 benign samples as reconnaissance and loses 2 cryptojacking samples, though it attains perfect reconnaissance recall (341/341). Both models show minor confusion between DoS and reconnaissance attacks, reflecting behavioral overlap in the temporal feature space. The federated model’s primary advantage is its perfect benign and cryptojacking recall, which—because benign is the largest class—outweighs the centralized model’s edge on reconnaissance and yields the overall accuracy improvement.

To isolate precisely where the federated model improves, Fig. 4 presents the normalized confusion matrix difference (federated minus centralized, in percentage points). Positive diagonal entries indicate improved per-class recall; the federated model gains +1.62 pp on benign recall and +0.38 pp on cryptojacking recall (reaching perfect recall on both), while the centralized model retains an edge on reconnaissance recall (+1.17 pp) and matches on DoS. Because benign is the majority class, its recall gain dominates, confirming that the federated advantage is concentrated in the classes most sensitive to client-local augmentation diversity.

Per-class analysis reveals that both approaches achieve excellent detection, with the federated model showing particular strength in benign and cryptojacking recall (both 1.00).

Table 12 reveals that both models achieve near-perfect detection across all attack categories. The federated model achieves perfect recall for both benign traffic (1.00) and cryptojacking (1.00), whereas the centralized model attains perfect reconnaissance recall (1.00) at the cost of lower benign recall (0.9838) and lower reconnaissance precision (0.9552). Both approaches prove highly effective at identifying cryptojacking, confirming that this attack type’s features are highly distinctive. The federated model’s balanced per-class performance, and in particular its perfect benign recall, reflects the benefits of client-local mixup diversity and FedSWA regularization, yielding the overall accuracy improvement.

Figure 5 a provides a holistic view of per-class performance across precision, recall, and F1-score for both approaches. The radar chart reveals that the federated model’s polygon encloses a slightly larger area, confirming its overall advantage, while the centralized model maintains competitive or marginally superior precision for benign and DoS classes. The per-class F1-score comparison (Fig. 5 b) further highlights that the federated model achieves a perfect F1-score (1.0000) for cryptojacking and gains the largest F1 improvement on reconnaissance (+1.12 pp), where its balanced precision-recall offsets the centralized model’s low reconnaissance precision.

SE channel attention analysis

The Squeeze-and-Excitation blocks provide interpretable insights into which features the model considers most informative. Figure 6 visualizes the learned SE attention weights across the three temporal blocks. Block 1 (64 channels) shows relatively uniform attention, indicating that most low-level features contribute to initial processing. In contrast, Blocks 2 and 3 exhibit increasingly selective attention patterns, with a subset of channels receiving significantly higher weights. This progressive feature selection confirms that the SE mechanism effectively learns to suppress noise channels and amplify discriminative features as information flows through the network hierarchy.

Feature space visualization and interpretability

Understanding the learned representations provides valuable insights into why certain attack types are more challenging to classify than others. Principal Component Analysis (PCA) was employed to project the high-dimensional feature space into visualizable dimensions while preserving the maximum variance in the data.

PCA analysis reveals distinct clustering patterns that correlate strongly with classification performance. Benign traffic forms a tight, well-defined cluster with minimal overlap with other classes, while cryptojacking occupies a separate region with modest internal spread. This clear separation explains the high classification accuracy achieved for these classes.

The most significant PCA finding concerns the spatial relationship between DoS and reconnaissance attacks. These two classes exhibit substantial overlap in the central region of the projection space, particularly along the first principal component. This overlap provides a visual explanation for the confusion between these classes observed in the confusion matrices, while the third principal component offers additional separation beyond the 2D projection.

As shown in Fig. 7 , the variance explained by the first three principal components totals 99.6% (PC1: 56.9%, PC2: 26.7%, PC3: 16.1%), indicating that the Dual-Attention TCN learns highly compact, well-structured representations. The high explained variance reflects the effectiveness of SE channel attention in focusing the model on the most discriminative feature dimensions.

To complement the linear PCA projection, we applied t-distributed Stochastic Neighbor Embedding (t-SNE) to capture non-linear structure in the learned feature space. As shown in Fig. 8 , t-SNE produces tighter, more well-separated clusters than PCA, confirming that the DA-TCN learns representations with strong non-linear separability. Benign and cryptojacking classes form compact, isolated clusters, while the partial overlap between DoS and reconnaissance observed in PCA is substantially reduced in the t-SNE embedding, suggesting that the model captures non-linear discriminative patterns that linear projections understate.

Anomaly detection integration and performance

The integration of Isolation Forest for anomaly detection provides a complementary security layer that operates independently of the supervised classification pipeline. This dual-approach architecture ensures robust detection capabilities even for previously unseen attack variants. Figure 9 presents a comprehensive analysis of anomaly score distributions across attack classes.

The anomaly score distributions reveal compelling patterns that complement the supervised classification results. DoS attacks consistently produce the lowest anomaly scores (mean: 0.621, std: 0.178), indicating their significant deviation from normal behavior patterns. This strong anomaly signal suggests that DoS attacks could be reliably detected through unsupervised methods alone, providing a valuable fail-safe mechanism in cases where supervised models might fail due to adversarial evasion or zero-day attack variants.

Cryptojacking and benign traffic exhibit similar anomaly score distributions (means: 0.735 and 0.765 respectively), reflecting the sophisticated nature of cryptojacking attacks, which deliberately attempt to mimic legitimate computational patterns to avoid detection. The success of our supervised approach in distinguishing these classes despite their similar anomaly profiles validates the importance of the SE-enhanced feature representations (Table 13 ).

Ablation study ...

Extracted Entities