An intrusion detection method for communication security of a connected vehicle
By constructing a spatiotemporal network representation method and introducing learnable edge credibility modulation and temporal attention mechanism, the problem of insufficient spatiotemporal joint representation in V2X communication security detection is solved, the ability to identify complex attacks and the stability of detection are improved, it can adapt to dynamic interaction scenarios and has engineering feasibility.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHENZHEN AUTOMOTIVE RES INST BEIJING INST OF TECH (SHENZHEN RES INST OF NAT ENG LAB FOR ELECTRIC VEHICLES)
- Filing Date
- 2026-04-27
- Publication Date
- 2026-05-29
AI Technical Summary
Existing V2X communication security detection methods lack spatiotemporal joint representation, making it difficult to utilize spatial adjacency relationships and temporal continuous evolution features. Graph models do not adequately utilize the credibility of adjacency relationships, and the depth of temporal feature mining is insufficient. They also fail to consider the model stability under dynamic node scale, resulting in insufficient ability to identify complex attacks.
By constructing a spatiotemporal network representation method, a learnable edge credibility modulation mechanism and a temporal attention mechanism are introduced. Combined with a masking mechanism and an adjacency pruning mechanism, nodes, edges, node feature sequences and adjacency relationships are organized in a unified manner to enhance the ability to identify complex interactive attacks.
It improves the ability to identify progressive, camouflaged, and continuously evolving attacks, enhances detection stability and discrimination accuracy, adapts to dynamic interactive scenarios, and is feasible for engineering implementation.
Smart Images

Figure CN122120031A_ABST
Abstract
Description
Technical Field
[0001] This invention provides an intrusion detection method for secure communication in connected vehicles, belonging to the field of vehicle network security technology. Background Technology
[0002] Vehicle-to-Everything (V2X) communication is a crucial foundational communication mechanism for intelligent connected vehicles to achieve functions such as environmental perception, collaborative decision-making, and proactive safety warnings. V2X communication systems typically feature open broadcasting, dynamic networking, high-speed node mobility, and widespread access from heterogeneous terminals, inherently posing significant cybersecurity risks. Currently, industry solutions for V2X communication security typically employ rule-based matching, statistical threshold analysis, and intrusion detection methods based on machine learning or deep learning. These methods monitor vehicle broadcast or interactive messages online to detect anomalies and issue attack alerts. While rule-based or threshold-based methods are simple to implement and fast to respond, they often rely on manually defined prior rules, limiting their ability to identify only a few known and easily identifiable anomaly patterns. They are prone to false positives or false negatives when facing sophisticated attacks such as deceptive message injection, gradual tampering, and coordinated deception. While traditional machine learning and deep learning methods offer stronger feature extraction capabilities, most existing solutions only consider single-vehicle temporal behavior or single-moment spatial relationships, failing to effectively model both the "behavioral evolution of the same vehicle across time" and the "interactions and influences between multiple vehicles." This results in insufficient ability to identify complex V2X attacks. Furthermore, some deep learning models have large parameter scales, high computational overhead, and complex inference chains, making it difficult to meet the deployment requirements of vehicle terminals or roadside equipment for low latency and low resource consumption. In summary, existing detection systems generally face a dilemma in balancing detection accuracy, real-time performance, adaptability to complex scenarios, and engineering deployability. There is an urgent need to propose a novel intrusion detection technology that can adapt to dynamic V2X interaction scenarios and balance spatiotemporal correlation modeling capabilities with engineering feasibility. Summary of the Invention
[0003] This invention provides an intrusion detection method for secure communication in connected vehicles, aiming to solve the following technical problems:
[0004] (1) Existing technologies are insufficient in spatiotemporal joint representation of V2X messages, making it difficult for models to simultaneously utilize spatial adjacency relationships and temporal continuous evolution characteristics;
[0005] Existing V2X security detection methods fall into two categories. One type relies on rules, thresholds, or statistical benchmark models to detect single messages or local fields. While simple to implement, this approach typically only determines whether a message deviates from the normal range at the "current moment," failing to capture the evolution of vehicle behavior over continuous time windows. Another type introduces network structure models, such as graph models, to represent the spatial relationships between vehicle nodes, but often emphasizes adjacency topology or local interactions at the same moment, failing to unify the historical behavior sequences of nodes with their current spatial adjacency relationships into a complete and learnable representation. Since V2X attacks are often not isolated instantaneous events but gradually manifest over multiple time slices as positional shifts, abnormal speeds, identity spoofing, or multi-node collaborative deception, it is difficult to establish a complete basis for judging complex attacks if the detection model cannot simultaneously utilize information such as "who is adjacent to whom," "how nodes have changed in the past," and "how adjacency relationships have evolved over time." Furthermore, the number of vehicles, inter-vehicle relationships, and interaction patterns in a V2X environment are themselves dynamically changing. If an intrusion detection model fails to organize nodes, edges, node feature sequences, adjacency relationships, and corresponding masks in a unified manner, the model can often only observe the data locally and cannot understand the traffic interaction state within a sliding time window as a whole. This will directly weaken its ability to identify group, progressive, and disguised attacks.
[0006] For the reasons mentioned above, one of the primary objectives of this invention is to propose a spatiotemporal network representation method that, by uniformly constructing nodes, edges, node feature sequences, adjacency relationships, and mask information, enables the model to explicitly utilize spatial adjacency relationships and temporal continuity, providing a structured input basis for subsequent known attack detection.
[0007] (2) Existing graph models do not make sufficient use of the credibility of adjacency relationships, which leads to dynamic topology and noisy edges interfering with the spatial aggregation results;
[0008] In V2X scenarios, the adjacency relationships between traffic participants are not static. Their visibility, communicability, and mutual influence constantly change with vehicle distance and speed, road structure, occlusion conditions, communication status, and scene variations. Therefore, adjacency edges established within a given time slice do not necessarily possess the same authenticity, stability, and reference value. While existing technologies have begun to use graph neural networks or graph attention networks to analyze vehicle relationships, most methods still treat adjacency relationships as given conditions, without further addressing the questions of "whether the edges are reliable over time and how much weight should be assigned." In other words, existing solutions often emphasize "whether there is a relationship" between nodes, but fail to adequately characterize "whether this relationship is reliable" and "how this relationship evolves over time." It is precisely because of the lack of detailed modeling of edge reliability that noisy edges and falsely associated edges in dynamic topological environments are more likely to interfere with the final detection results.
[0009] Therefore, this invention further proposes to introduce a learnable edge credibility modulation mechanism into the graph attention mechanism, which improves the stability of spatial feature extraction and the ability to identify complex interaction attacks by allowing the model to adaptively evaluate the importance and reliability of different adjacent edges during spatial aggregation.
[0010] (3) Existing technologies lack sufficient depth in mining temporal features, making it difficult to detect progressive, disguised, and continuously evolving attacks;
[0011] From the perspective of existing technology, many traditional detection methods, while considering "time information," mostly only roughly reflect time changes through adjacent message differences, frequency statistics, simple consistency checks, or fixed-length window statistics. These methods can describe basic trends but struggle to deeply capture "which moments are most critical," "which changes are most anomalous," and "which segments have the greatest impact on the final attack determination." In V2X scenarios, some attacks do not obviously cross boundaries in a short period but accumulate anomalous effects over a longer timeframe through gradual drifting, delayed replays, slight tampering, and short-term camouflage. If simple temporal features or fixed rules are still used for modeling, it is easy to mistake such continuously evolving attacks for normal fluctuations, or conversely, to misjudge normal operating condition changes as anomalous. It is precisely because existing technologies do not utilize the time dimension deeply enough that models cannot effectively distinguish the essential difference between "normal fluctuations" and "abnormal evolution"; and it is precisely because they cannot identify truly critical change segments that detection results are prone to false positives and false negatives. This deficiency further illustrates that V2X detection not only needs to "see time" but also needs to "selectively understand time."
[0012] Therefore, one of the objectives of this invention is to introduce a temporal attention mechanism based on spatial graph network modeling, proposing a spatiotemporal network structure. This allows the model to focus more on neighboring nodes and interactions that are truly important to the current node in the spatial dimension, while adaptively focusing on key time slices with greater discriminative significance in the temporal dimension. In this way, the model's ability to identify progressive, camouflaged, and continuously evolving attacks can be enhanced, and the detection stability and discrimination accuracy in complex scenarios can be improved.
[0013] (4) Existing technologies do not consider model stability under dynamic node scale;
[0014] In real-world V2X scenarios, the number of vehicles interacting within the same time window is not constant. The number of nodes can fluctuate significantly across different samples due to traffic flow, road conditions, and sampling range. To meet the needs of batch training and a unified input format, node dimension padding is typically necessary. However, if the features, labels, and adjacency relationships of the padded nodes are not strictly masked, these invalid nodes, which should not participate in the computation, will introduce false edges, false labels, and invalid information propagation during graph construction, loss calculation, and classification, thus affecting model training stability and inference accuracy.
[0015] Existing technologies emphasize the detection approach itself, but lack sufficient details on the engineering implementation under dynamic node scale. As a result, some solutions may work in theory, but easily expose instability issues during large-scale training, batch inference, or complex scene transfer. Therefore, the input alignment and invalid node masking problems brought about by dynamic node scale are among the key factors affecting the engineering feasibility of spatiotemporal graph models.
[0016] Therefore, this invention also aims to impose unified constraints on the completion nodes through a masking mechanism, an invalid label blocking mechanism, and an adjacency pruning mechanism, so that the model can still stably complete training and inference even when the number of nodes changes dynamically, thereby enhancing the engineering feasibility and practical deployment reliability of the method.
[0017] The specific technical solution of this invention is as follows:
[0018] An intrusion detection method for secure communication of connected vehicles firstly cleans, aligns, and extracts features from the received vehicle V2X messages on the RSU, and then constructs a spatiotemporal graph input consisting of vehicle nodes, adjacency relationships, node feature sequences, and masks within a sliding time window;
[0019] The input is then fed into a spatiotemporal joint coding module deployed in the cloud. First, sparse temporal attention is used to extract the cross-time behavior evolution features of nodes. Then, graph networks are used to aggregate the spatial interaction relationships between nodes, and edge credibility modulation is combined to enhance the utilization of effective neighbor information.
[0020] Finally, a multi-layer discriminator deployed in the cloud first completes the normal or abnormal identification, then further subdivides the abnormal nodes according to known attack types, and finally outputs the detection results to RSU to support RSU alarm handling.
[0021] Specifically, the following steps are included:
[0022] S1. Dataset Construction;
[0023] The training dataset is constructed using raw CSV data from vehicle operation as input. Data cleaning, sample extraction, graph structure construction, and label generation are performed on fields such as timestamps, vehicle identifiers, vehicle status information, and attack tags. This transforms the raw discrete records into structurally consistent and temporally ordered basic observation data. Specifically, the following sub-steps are included:
[0024] S1.1 Data cleaning;
[0025] The input raw CSV data is cleaned and normalized.
[0026] First, read the vehicle status information and attack tag fields from the original data, including timestamp, vehicle identifier, location, speed, heading, acceleration, vehicle type, and so on. Then, perform a unified conversion on the data type of each field to meet the basic requirements of numerical calculation and time-series indexing.
[0027] The system processes abnormal and redundant entries in the original records. Records with missing fields, incorrectly formatted fields, or those clearly unsuitable for subsequent calculations are removed or corrected. Duplicate records of the same vehicle occurring at the same time are randomly deduplicated.
[0028] At the same time, all records are sorted according to timestamps to ensure that the state evolution process of the same vehicle and the same scenario remains consistent in the time dimension.
[0029] S1.2 Sample extraction;
[0030] Using a target vehicle at a certain central moment as the central node, a local traffic interaction scenario is constructed around the central node.
[0031] First, the position of the target vehicle is obtained at the center time, and its spatial distance to other vehicles at the same time is calculated. Then, based on the set neighborhood search radius, candidate neighbor nodes within the local spatial range are selected and sorted by distance or overall importance. Only the top N=20 neighbor nodes in the importance ranking are extracted. After extraction, this operation is repeated at historical time T, using the current center node as the core.
[0032] S1.3 Graph Structure Construction;
[0033] At the sample center time, each traffic participant is used as the central node. The relative spatial relationships of the remaining traffic participants in the scene are calculated one by one, and a local interaction graph is constructed accordingly. For any pair of nodes, the two-dimensional position coordinates of the two nodes at the center time are first extracted, and their Euclidean distance is calculated. Then, the dynamic region of interest of the central node at the current time is determined by combining the motion type, instantaneous velocity, and heading angle of the central node. The basic scale of the region of interest is determined by the type of traffic participant and further expands adaptively with the velocity of the central node. Different basic ranges are set for different traffic participants, and then superimposed with the velocity term to form the node-level perception radius, so that different nodes have different interaction search ranges.
[0034] An anisotropic interaction region modeling mechanism related to heading is introduced. For motor vehicles, based on the angle between the heading angle of the center node and the relative azimuth angle of the candidate nodes, an asymmetric region of interest is constructed with priority given to forward direction, followed by lateral direction, and weaker backward direction. This makes the area of interest in front of the vehicle significantly larger than that behind and to the rear, thus better reflecting the pattern of "stronger forward interaction and weaker backward influence" in real traffic scenarios. For non-motorized vehicles, a directional region with a larger forward direction and a smaller backward direction is adopted. For pedestrians, a relatively uniform neighbor attention method is adopted. Therefore, only when a candidate node falls into the effective region of interest corresponding to the type and orientation of the center node is it included in the adjacency candidate set.
[0035] Furthermore, when the number of candidate neighbors exceeds the preset limit, the system does not randomly truncate them, but sorts them according to the ratio of "actual distance divided by direction-normalized reachable distance", giving priority to retaining neighbor nodes that are more interactively meaningful to the central node.
[0036] After neighbor selection, the connection strength of the edges is further assigned. Specifically, the edge weights are not simply set to a uniform constant, but are determined by a combination of distance decay factors and spatial region prior factors. For motor vehicle nodes, different prior importance coefficients are assigned to different regions based on whether the candidate node is located in front of, to the left front, to the right front, to the left rear, or to the right rear of the center node. Then, the region prior is jointly calculated with a function that decays monotonically with distance to obtain the initial connection strength between node pairs. For pedestrians and non-motorized vehicles, directional weights and distance decay rules adapted to their motion characteristics are also adopted. Finally, the weights of each neighbor edge are normalized to ensure their stable use in subsequent message propagation and feature aggregation in the graph neural network.
[0037] S1.4 Tag Generation;
[0038] The training labels for each node are determined by combining the attack status of the target node or its neighboring nodes within the time window.
[0039] S1.5 Dataset Construction and Mask Matrix Design;
[0040] The constructed spatiotemporal graph samples are organized into a dataset file that can be directly used for model training. Specifically, for each center time point and target vehicle that meets the graph construction conditions, a corresponding single sample is generated, and the sample features, connectivity graph, and labels are encapsulated into structured data units for storage. A mask matrix matching the above dataset structure is designed. Let N be the maximum number of nodes in a single batch processing parallel environment. max In each single sample with N actual nodes, the first N positions are marked as 1 to indicate a real, valid node, and the remaining N positions are marked as 1. max -N positions are set to 0, representing zero-padding nodes introduced to satisfy batch alignment.
[0041] S2. Construct a temporal attention layer;
[0042] Designing a sparse temporal attention module to model time series data with sparse attention can more effectively extract temporal anomaly features.
[0043] A local causal sparse temporal attention mechanism is introduced. This mechanism only allows the current time step to focus on the most recent ω historical time steps and the current time step itself, and prohibits the current time step from accessing future information through causal constraints, thereby significantly compressing the scope of attention computation while preserving the local dynamic evolution capability.
[0044] Let Q, K, and V be the input matrices for attention, and define the temporal mask matrix and the set of computable locations M. t,τ Where t and τ represent time t and time τ, respectively:
[0045]
[0046] At this point, the initial attention score e between times (t, τ) t,τ Calculate using the following method:
[0047]
[0048] The corresponding attention score a between times (t, τ) t,τ Use the following normalization formula:
[0049]
[0050] Finally, the output of sparse attention is:
[0051]
[0052] Multi-head attention models linearly project inputs Q, K, and V using different learned projection parameter matrices, then input these matrices into the attention calculation formula. This process is repeated h times, with the output values of each head concatenated to form the final output. Multi-head sparse attention:
[0053]
[0054]
[0055] The fully connected feedforward neural network layer FFN(X) consists of two fully connected neural network layers, with a linear activation layer in between, using the ReLU activation function.
[0056]
[0057] in This is the weight matrix of the fully connected layer. This is the bias vector for the fully connected layer.
[0058] Residual connection layers are used to improve the vanishing gradient problem:
[0059]
[0060] Normalization layers are used to stabilize the training process:
[0061]
[0062] in Output for residual connection layer Mean and variance of each layer For an infinitesimal quantity, These are the parameters to be learned.
[0063] S3. Construct a spatial attention layer;
[0064] The design of the graph attention module adaptively learns the influence of neighboring nodes on the current node under the constraints of known vehicle spatial connection relationships. Based on the traditional graph attention mechanism, a learnable edge gating is introduced to unify the initial connection weights and edge propagation weights between vehicles into the spatial modeling process.
[0065] First, h is obtained by dimensionality transformation of the output of the time attention layer. i The hidden representation of each node in the time dimension is obtained through linear mapping. :
[0066]
[0067] Among them W hThe weight matrix is learnable; then, concatenated features are constructed for any node pair (i,j), and the base attention score is calculated:
[0068]
[0069] Where 'a' is a learnable weight matrix, and || denotes the concatenation operation; based on this, the model further introduces an edge gating mechanism, which jointly generates edge weights by combining connection matrix information and a small MLP encoding results based on node information:
[0070]
[0071] Where A i,j The connection matrix is used; based on the basic attention and edge weighting results, the final attention score is obtained:
[0072]
[0073] in To avoid minor computational failures, we finally normalize only the nodes with non-zero adjacency matrices, based on the attention score, to obtain the final attention score:
[0074]
[0075] Finally, neighborhood aggregation is performed based on the attention score to obtain the output h on the spatial module. i ':
[0076]
[0077] A multi-head graph attention module is used on top of the single-head graph attention layer. The multi-head graph attention module consists of multiple parallel single-head graph attention layers. Each attention head shares the same input node features, adjacency relationships, and node masks, but has its own independent parameters, thus enabling it to learn different spatial association patterns.
[0078]
[0079] Where K is the number of attention heads, H is the spatial state information of the input and output, A is the connection matrix, and M is the mask matrix; then, the outputs of each head are concatenated along the feature dimension to obtain:
[0080]
[0081] Finally, a linear fusion layer is used for dimensionality compression to obtain the output result:
[0082]
[0083] Among them W g(l) and b g (l) They are all learnable matrices.
[0084] S4. Construct a two-layer classification output layer;
[0085] After the spatiotemporal feature extraction network completes the encoding, each node in the sample will obtain a high-dimensional representation containing temporal and spatial interaction information. In order to conform to the discrimination logic of the V2X attack detection task of "first determining whether it is abnormal, and then determining which type of abnormality it is", the model adopts an explicit two-layer output structure.
[0086] Specifically, the first output layer is responsible for performing normal or abnormal binary classification to answer the question "Does the current node exhibit abnormal behavior?"; the second output layer is responsible for performing detailed classification of abnormal types to further identify the specific attack category if the first layer determines it to be abnormal. Its core implementation consists of three parts: a shared encoder, a first-layer classification header head_stage1, and a second-layer classification header head_stage2.
[0087] The shared encoder first filters the output of the spatiotemporal layer for effective nodes and flattens the output in both the temporal and node dimensions. Then, the adjusted output is input into a two-layer neural network for information extraction.
[0088]
[0089] in, 1 and 2 represents the combined operation of "linear transformation + normalization + activation + dropout", where W1, W2, b1, and b2 are all learnable matrices; this encoding process compresses the multidimensional observations of a node over the entire time window into a compact semantic representation z. t This is for use by the subsequent two levels of discrimination heads;
[0090] The first-layer output head_stage1 and the second-layer output head_stage2 are both linear classifiers, and their input is the shared embedding z. t Output the attack probability p and the attack type classification result y, respectively; the corresponding classifier structures are:
[0091] output=Wz+b
[0092] Both W and b are learnable matrices.
[0093] S5. Designing the Loss Function
[0094] Considering that the intrusion detection system solves a classification problem, the overall loss function for the adopted two-layer judgment structure is as follows:
[0095]
[0096] Where L Stage1 This represents the error during the first-level detection, i.e., the error in distinguishing whether the message is normal or abnormal.
[0097]
[0098] Where α is the balance factor, γ is the hard sample adjustment factor, and p t Let be the probability that the sample is actually a positive sample, that is:
[0099]
[0100] L Stage2 This represents the error during secondary detection, specifically the error arising from distinguishing which type of attack anomaly the message belongs to:
[0101]
[0102] Where x represents the model output, y represents the true label, C represents the number of categories, and n represents the number of attack samples.
[0103] This invention addresses the dynamic interaction scenario of multiple vehicles in V2X, unifying the modeling of vehicle nodes, inter-node relationships, and behavioral evolution within continuous time slices into a spatiotemporal network structure. Based on this, a spatiotemporal feature joint learning mechanism is used to collaboratively extract individual vehicle behavioral features and group interaction features, thereby improving the ability to identify false information. Furthermore, this invention employs a hierarchical discrimination mechanism for node-level detection tasks to effectively distinguish between "normal or abnormal" states and "specific attack types," thus enhancing the interpretability and subsequent processing value of detection results. Simultaneously, considering the dynamic changes in the number of nodes, the temporal changes in adjacency relationships, and the high real-time requirements of deployment in V2X scenarios, this invention features targeted structural designs for model input organization, relationship modeling, and discrimination processes, ensuring both detection effectiveness and good online application potential. In summary, this invention provides an intrusion detection solution for integrated communication security of intelligent connected vehicles, roadside equipment, and the cloud, which is more adaptable to dynamic spatiotemporal scenarios, more suitable for engineering deployment, and more conducive to precise attack identification. Attached Figure Description
[0104] Figure 1 This is a flowchart of the present invention;
[0105] Figure 2This is a schematic diagram of the temporal sparse mask matrix for an example (assuming ω=4).
[0106] Figure 3 The overall structure of the spatial attention layer in this embodiment;
[0107] Figure 4 The example dataset shows the prediction results for the BurST-ADMA dataset.
[0108] Figure 5 The example dataset is the prediction result for the VeReMi-Extension dataset. Detailed Implementation
[0109] like Figure 1 As shown, this invention proposes a comprehensive technical solution for V2X attack detection based on spatiotemporal networks: First, the message preprocessing module deployed on the RSU cleans, aligns, and extracts features from the raw V2X messages received by the RSU, constructing a spatiotemporal graph input consisting of vehicle nodes, adjacency relationships, node feature sequences, and masks within a sliding time window; then, the input is fed into a spatiotemporal joint coding module deployed in the cloud, first using sparse temporal attention to extract cross-time behavioral evolution features of nodes, then using graph networks to aggregate spatial interaction relationships between nodes, and combining edge credibility modulation to enhance the utilization of effective neighbor information; finally, a multi-layer discriminator first completes the normal or abnormal discrimination, then further subdivides abnormal nodes according to known attack types, and finally outputs the detection results to the RSU to support alarm handling. The specific steps are as follows:
[0110] S1. Dataset Construction;
[0111] The training dataset is constructed using raw CSV data from vehicle operation as input. Data cleaning, sample extraction, graph structure construction, and label generation are performed on fields such as timestamps, vehicle identifiers, vehicle status information, and attack tags. This transforms the raw discrete records into structurally consistent and temporally ordered basic observation data. The specific operations are as follows:
[0112] S1.1 Data cleaning;
[0113] To ensure the raw data meets the requirements for subsequent spatiotemporal graph sample construction and model training, the input raw CSV data is first cleaned and normalized. Specifically, vehicle state information and attack tag fields, including timestamps, vehicle identifiers, locations, speeds, headings, accelerations, vehicle types, and other data types, are read from the raw data. The data types of each field are then uniformly converted to meet the basic requirements for numerical calculations and temporal indexing. After unifying the field types, outliers and redundant items in the raw records are further processed. Records with missing fields, incorrectly formatted fields, or those clearly unsuitable for subsequent calculations are removed or corrected. Duplicate records of the same vehicle appearing at the same time are randomly deduplicated to avoid the same observation being repeatedly introduced into the subsequent sample construction process. Simultaneously, all records are sorted by timestamp to ensure consistency in the state evolution process of the same vehicle and within the same scene over time, thus laying the foundation for subsequent extraction of temporal samples based on continuous time windows.
[0114] S1.2 Sample extraction;
[0115] After basic cleaning, this invention uses a target vehicle at a specific central moment as the central node and constructs a local traffic interaction scenario around this central node. Specifically, the position of the target vehicle is first obtained at the central moment, and its spatial distance to other vehicles at the same moment is calculated. Then, based on a set neighborhood search radius, candidate neighbor nodes within the local spatial range are selected and sorted according to distance or overall importance. To avoid data explosion caused by too many nodes in a single sample, only the top N=20 neighbor nodes in importance are extracted. After extraction, this operation is repeated at historical time T, using the current central node as the core.
[0116] S1.3 Graph Structure Construction;
[0117] In order to construct a scene graph that can accurately represent the interactive relationships in traffic scenarios, this invention does not determine the node connection relationship solely based on the spatial distance between traffic participants, but rather constructs an adjacency matrix by comprehensively considering the spatial proximity and relative motion relationship between node pairs.
[0118] Specifically, at the center of the sample, each traffic participant is used as the central node, and the relative spatial relationships of the remaining traffic participants in the scene are calculated one by one, thereby constructing a local interaction graph. For any pair of nodes, the two-dimensional position coordinates of the two nodes at the center time are first extracted, and their Euclidean distance is calculated. Then, the dynamic region of interest of the central node at the current time is determined by combining the motion type, instantaneous velocity, and heading angle of the central node. The basic scale of the region of interest is determined by the type of traffic participant and further expands adaptively with the velocity of the central node. Different basic ranges are set for different traffic participants, and then superimposed with the velocity term to form the node-level perception radius, so that different nodes have different interaction search ranges.
[0119] Building upon this foundation, this invention does not employ the traditional fixed-radius neighborhood determination method. Instead, it further introduces an anisotropic interaction region modeling mechanism related to heading. For motor vehicles, based on the angle between the heading angle of the central node and the relative azimuth angle of the candidate nodes, a forward-priority, lateral-priority, and backward-priority asymmetric region of interest is constructed. This makes the area of interest in front of the vehicle significantly larger than that behind and to the rear, thus better reflecting the real-world traffic scenario's pattern of "stronger forward interaction and weaker backward influence." For non-motorized vehicles, a directional region with a larger forward orientation and a smaller backward orientation is used. For pedestrians, a relatively uniform neighborhood attention method is employed. Therefore, only when a candidate node falls into an effective region of interest corresponding to the type and orientation of the central node is it included in the adjacency candidate set, thus avoiding forcibly connecting nodes that are spatially close but unlikely to form effective interactions.
[0120] Furthermore, when the number of candidate neighbors exceeds a preset limit, the system does not randomly truncate them, but sorts them according to the ratio of "actual distance divided by direction-normalized reachable distance," prioritizing the retention of neighboring nodes that are more interactively significant to the central node. In other words, the modeling process considers not only how close two nodes are to each other, but also whether that distance lies within a highly sensitive region facing the current orientation of the central node. This enhances the fidelity of the graph structure for key interactive objects and controls the graph size and computational complexity.
[0121] After neighbor selection, the connection strength of the edges is further assigned. Specifically, the edge weights are not simply set to a uniform constant, but are determined by a combination of distance decay factors and spatial region prior factors. For motor vehicle nodes, different prior importance coefficients are assigned to different regions based on whether the candidate node is located in front of, to the left front, to the right front, to the left rear, or to the right rear of the center node. Then, the region prior is jointly calculated with a function that decays monotonically with distance to obtain the initial connection strength between node pairs. For pedestrians and non-motorized vehicles, directional weights and distance decay rules adapted to their motion characteristics are also adopted. Finally, the weights of each neighbor edge are normalized to ensure their stable use in subsequent message propagation and feature aggregation in the graph neural network.
[0122] Therefore, the graph structure constructed in this invention does not merely reflect whether two nodes are close to each other, but further encodes differences in node type, movement orientation, local spatial orientation, and interaction strength, giving each edge in the graph a more explicit traffic semantic. Simultaneously, to maintain the integrity of the node's historical state and local representation during graph convolution propagation, the adjacency matrix retains the self-connection terms of each node, thus avoiding excessive dilution of the node's own features while aggregating neighborhood information.
[0123] S1.4 Tag Generation;
[0124] This invention does not simply assign values based on the state at a single moment, but rather combines the attack states of the target node or adjacent nodes within a time window to determine the training labels for each node.
[0125] S1.5 Dataset Construction and Mask Matrix Design;
[0126] After completing data cleaning, sample extraction, graph structure construction, and label generation, this invention further organizes the constructed spatiotemporal graph samples into a dataset file that can be directly used for model training. Specifically, for each center time and target vehicle that meets the graph construction conditions, a corresponding single sample is generated, and the sample features, connectivity graph, and labels are encapsulated into structured data units for storage. To adapt to the batch parallel computing requirements in subsequent model training, this invention further designs a mask matrix that matches the above dataset structure. Let N be the maximum number of nodes in a single batch processing parallel environment. max In each single sample with N actual nodes, the first N positions are marked as 1 to indicate a real, valid node, and the remaining N positions are marked as 1. max -N positions are set to 0, representing zero-padding nodes introduced to satisfy batch alignment.
[0127] S2. Construct a temporal attention layer;
[0128] Considering that the impact of intrusion attacks on node states is often primarily manifested in abnormal fluctuations, continuous drifts, or sudden distortions in the time dimension, this invention designs a sparse temporal attention module to perform sparse attention modeling on time series, which can more effectively extract temporal anomaly features.
[0129] Traditional global self-attention mechanisms calculate temporal correlations for the entire sequence of time length T, and their output can be expressed as:
[0130] (1)
[0131] In the formula, Q, K, and V serve as the input matrices for attention. To reduce the computational complexity of the temporal attention module, this invention does not employ full-time domain self-attention but instead introduces a local causal sparse temporal attention mechanism. This mechanism only allows the current time moment to focus on the most recent ω historical time moments and the current time moment itself, and prohibits the current time moment from accessing future information through causal constraints, thereby significantly compressing the attention computation range while preserving local dynamic evolution capabilities. Let Q, K, and V serve as the input matrices for attention, and define the temporal mask matrix and the set of computable locations M. t,τ Where t and τ represent time t and time τ, respectively:
[0132] (2)
[0133] The corresponding sparse matrix is as follows Figure 2 As shown, the initial attention score e between times (t, τ) is... t,τ Calculate using the following method:
[0134] (3)
[0135] The corresponding attention score a between times (t, τ) t,τ Use the following normalization formula:
[0136] (4)
[0137] Finally, the output of sparse attention is:
[0138] (5)
[0139] Multi-head attention models can more efficiently focus on the global information of a sequence. It involves linearly projecting the inputs Q, K, and V using different learned projection parameter matrices, then inputting these into the attention calculation formula, repeating this process h times, with the output values of each head concatenated to form the final output. Multi-head sparse attention is shown in equations (6) and (7):
[0140] (6)
[0141] (7)
[0142] The fully connected feedforward neural network layer FFN(X) consists of two fully connected neural network layers with a linear activation layer in between. The linear activation layer uses the ReLU activation function, as shown in equation (8):
[0143] (8)
[0144] in This is the weight matrix of the fully connected layer. This is the bias vector for the fully connected layer.
[0145] The residual connection layer is used to improve the gradient vanishing problem, as shown in equation (9):
[0146] (9)
[0147] The normalization layer is used to stabilize the training process, as shown in equation (10):
[0148] (10)
[0149] in Output for residual connection layer Mean and variance of each layer For an infinitesimal quantity, These are the parameters to be learned.
[0150] S3. Construct a spatial attention layer;
[0151] Considering that the spatial interactions between vehicles in real-world traffic scenarios are not uniform but are simultaneously influenced by topological connectivity constraints and differences in interaction intensity, traditional fixed-weight or simple average graph aggregation methods are insufficient to fully reflect the true relationships between nodes. Therefore, this invention designs a graph attention module that adaptively learns the influence of neighboring nodes on the current node under known vehicle spatial connectivity constraints. This module further introduces learnable edge gating on top of the traditional graph attention mechanism, unifying the initial connection weights and edge propagation weights between vehicles into the spatial modeling process. This allows the model to both select effective neighbors and distinguish the contribution levels of different neighbors, thereby more accurately representing the non-uniform interactions in complex traffic environments and improving the precision and robustness of spatial feature extraction.
[0152] The overall structure of the spatial attention layer is as follows: Figure 3 As shown:
[0153] First, h is obtained by dimensionality transformation of the output of the time attention layer. i The hidden representation of each node in the time dimension is obtained through linear mapping. :
[0154] (11)
[0155] Among them W h The weight matrix is learnable; then, concatenated features are constructed for any node pair (i,j), and the base attention score is calculated:
[0156] (12)
[0157] Where 'a' is a learnable weight matrix, and || denotes the concatenation operation; based on this, the model further introduces an edge gating mechanism, which jointly generates edge weights by combining connection matrix information and a small MLP encoding results based on node information:
[0158] (13)
[0159] Where A i,j The connection matrix is used; based on the basic attention and edge weighting results, the final attention score is obtained:
[0160] (14)
[0161] in To avoid minor computational failures, we finally normalize only the attention scores at nodes with non-zero adjacency moments, based on the attention score:
[0162] (15)
[0163] Finally, neighborhood aggregation is performed based on the attention score to obtain the output h on the spatial module. i ':
[0164] (16)
[0165] Building upon the single-head graph attention layer, a multi-head graph attention module is further employed to model the interaction patterns between vehicle nodes in parallel from different subspaces and relational perspectives. This module consists of multiple parallel single-head graph attention layers. Each attention head shares the same input node features, adjacency relationships, and node masks, but has its own independent parameters, enabling it to learn different spatial association patterns independently.
[0166] (17)
[0167] Where K is the number of attention heads, H is the spatial state information of the input and output, A is the connection matrix, and M is the mask matrix; then, the outputs of each head are concatenated along the feature dimension to obtain:
[0168] (18)
[0169] Finally, a linear fusion layer is used for dimensionality compression to obtain the output result:
[0170] (19)
[0171] Among them W g (l) and b g (l) They are all learnable matrices.
[0172] S4. Construct a two-layer classification output layer;
[0173] After the spatiotemporal feature extraction network completes the encoding, each node in the sample receives a high-dimensional representation containing both temporal and spatial interaction information. To better align with the V2X attack detection task's logic of "first determining if it's abnormal, then determining which type of abnormality it belongs to," the model employs an explicit two-layer output structure. Specifically, the first output layer performs binary classification (normal or abnormal) to answer the question "Does the current node exhibit abnormal behavior?" The second output layer performs detailed classification of the abnormality type, further identifying the specific attack category given the first layer's determination of an abnormality. Its core implementation comprises three parts: a shared encoder, a first-layer classification head (head_stage1), and a second-layer classification head (head_stage2).
[0174] The shared encoder first filters the output of the spatiotemporal layer for effective nodes and flattens the output in both the temporal and node dimensions. Then, the adjusted output is input into a two-layer neural network for information extraction.
[0175] (20)
[0176] in, 1 and 2 represents the combined operation of "linear transformation + normalization + activation + dropout", where W1, W2, b1, and b2 are all learnable matrices; this encoding process compresses the multidimensional observations of a node over the entire time window into a compact semantic representation z. t This is for use by the subsequent two levels of discrimination heads;
[0177] The first-layer output head_stage1 and the second-layer output head_stage2 are both linear classifiers, and their input is the shared embedding z. t The attack probability p and the attack type classification result y are output respectively. The corresponding classifier structures are:
[0178] output=Wz+b (twenty one)
[0179] Both W and b are learnable matrices.
[0180] S5. Design the loss function;
[0181] Considering that the intrusion detection system solves a classification problem, the overall loss function for the adopted two-layer judgment structure is shown in equation (22):
[0182] (twenty two)
[0183] Where L stage1 This represents the error during the first-level detection, i.e., the error in distinguishing whether the message is normal or abnormal.
[0184] (twenty three)
[0185] Where α is the balance factor, γ is the hard sample adjustment factor, and p t Let be the probability that the sample is actually a positive sample, that is:
[0186] (twenty four)
[0187] L stage2 This represents the error during secondary detection, specifically the error arising from distinguishing which type of attack anomaly the message belongs to:
[0188] (25)
[0189] Where x represents the model output, y represents the true label, C represents the number of categories, and n represents the number of attack samples.
[0190] This embodiment verifies the results using a publicly available dataset:
[0191] 1. Introduction to the dataset
[0192] To verify the feasibility of the algorithm of this invention in the V2X attack detection task, this embodiment uses the BurST-ADMA dataset and the VeReMi-Extension dataset to train and test the model.
[0193] The BurST-ADMA dataset is a publicly available benchmark dataset for detecting erroneous behavior in connected vehicles (V2X). Generated from traffic scenario simulations in Burwood, Melbourne, Australia, it covers various traffic participants including cars, trucks, motorcycles, buses / trams, and pedestrians. This dataset contains normal basic security messages as well as seven typical types of spoofed data injection attacks, effectively simulating message tampering and forgery in a V2X environment, providing an important testing foundation for research on erroneous behavior detection and anomaly identification.
[0194] The VeReMi-Extension dataset is an extended version of the original VeReMi dataset generated from LuST traffic scenarios and the VEINS platform, expanding the attack types from 5 to 20. Compared to the original VeReMi, the attacks in VeReMi-Extension can be categorized into five main types: location spoofing, speed manipulation, freeze / replay, DoS, and Sybil attacks. It offers significant improvements in attack type coverage, scenario complexity, and data realism, making it more suitable for evaluating the performance of V2X security detection models in multi-class attack identification and complex scenario generalization.
[0195] 2. Model Validation Methods
[0196] This invention validates the model through test set experiments. To verify the model's feasibility, accuracy, precision, recall, and F1 score are used to evaluate its performance. Accuracy is the ratio of correctly predicted samples to the total number of samples; precision reflects the proportion of samples that are indeed intrusions among the data predicted as intrusions, primarily reflecting the false positive probability of the intrusion detection system; recall reflects the proportion of samples predicted as intrusions that are indeed intrusions, primarily reflecting how many attacks were correctly identified; the F1 score is a comprehensive evaluation of precision and recall, taking into account both false positives and false negatives. The definitions of the relevant scores are as follows:
[0197]
[0198]
[0199]
[0200]
[0201] 3. BurST-ADMA dataset test results
[0202] In multi-class classification problems, the confusion matrix of the model's prediction results is as follows: Figure 4 As shown, the prediction accuracy of the model in this invention is 99.56%.
[0203] Table 1 is Figure 4 Attacks on the Burst-ADMA dataset
[0204] type meaning type meaning 0 Real behavior 4 Constant random velocity 1 Constant random position 5 Positive velocity deflection 2 Positive position offset 6 Negative velocity offset 3 Negative position offset 7 Reverse heading
[0205] Table 2 shows the efficient predictive capability of the model of this invention.
[0206] Furthermore, the model of this invention takes only 38.44ms and consumes 7.21MB of memory in a single run, demonstrating the superior performance of the model compared to other methods.
[0207] Table 2. Test results of the BurST-ADMA dataset.
[0208] Method Name Prediction accuracy Predicted time Model file size Logistic Regression 0.9047 75ms \ Naive Bayes 0.6752 24ms \ K-Nearest Neighbor 0.9892 7.81s \ Gradient boosting classifier 0.9990 1.5s \ Support Vector Machine 0.9244 106s \ ANYANWU et al. 0.9989 1.27s 17.1MB Ours 0.9956 42.41ms 7.25MB
[0209] 4. Test results of the VeReMi-Extension dataset
[0210] In multi-class classification problems, the confusion matrix of the model's prediction results is as follows: Figure 5 As shown, the prediction accuracy of the model in this invention is 99.996%.
[0211] Table 3 is... Figure 5 Attacks on the VeReMi-Extension dataset
[0212] type meaning type meaning 0 Real behavior 10 Interference type 1 constant position 11 Data replay 2 constant position offset 12 Finally stopped 3 random location 13 Denial of Service 4 Random position offset 14 Random denial of service 5 constant speed 15 Disruptive Denial of Service 6 Constant speed offset 16 Sybil (data replay type) 7 Random speed 17 Traffic congestion Sybil 8 Random velocity offset 18 Random Denial of Service Sybil 9 Delayed message 19 Sybil (Interference Denial of Service)
[0213] Table 4 illustrates the high predictive efficiency of the model of this invention.
[0214] Furthermore, the model of this invention contains a total of 213K parameters, takes only 38.44ms in a single run, and consumes 7.21MB of memory, demonstrating the superior performance of the model of this invention compared to other methods.
[0215] Table 4. Test results of the VeReMi-Extension dataset
[0216] Method Name accuracy F1 score Parameters Memory usage Predicted time CNN-BiLSTM 0.9839 0.9809 5.36M \ 2.01s GRUs 0.9798 0.9759 1.39M \ 81.52ms SVMDformer 0.9840 0.9802 2.45M \ 1.68s ANYANWU et al. 0.995 \ \ \ 1.53s Khan et al. 0.9828 \ 10.27M 39.18MB 1.73s Huang et al. 0.9841 0.9859 390K \ 42.75ms Youness et al. 0.9905 0.99 \ \ 41.76ms Frimpong et al. 0.9912 0.9902 \ \ 235ms Ours 0.9946 0.99 213K 7.21MB 38.44ms
[0217] This invention addresses the shortcomings of existing V2X known attack detection methods, such as insufficient spatiotemporal joint representation, inadequate utilization of adjacency credibility, and insufficient depth in mining temporal anomalies. It proposes an intrusion detection method for dynamic vehicular network scenarios utilizing a spatiotemporal joint attention graph network. First, this method constructs a spatiotemporal sample representation around the target vehicle, including continuous time windows, neighbor node sets, adjacency weight matrices, and effective node constraint information. This allows discrete V2X messages to be uniformly organized into structured inputs that possess both spatial interaction semantics and temporal evolution semantics. Based on this, a temporal attention mechanism is used to extract key temporal features from changes in node historical behavior. Then, a graph attention mechanism incorporating edge credibility modulation is used to adaptively model different adjacent edges, thereby highlighting real and effective interaction relationships during spatial aggregation. Furthermore, by performing hierarchical discrimination based on normal or abnormal categories and subcategories of anomalies, the detection process better aligns with the coarse-to-fine cognitive pattern of V2X intrusion detection. Because this invention does not make isolated judgments on individual vehicles and messages, but comprehensively considers the historical evolution of nodes, neighbor interactions, and dynamic topological changes within a spatiotemporal structure, it can more completely characterize known attack behaviors such as position drift, speed tampering, identity spoofing, and collaborative deception, thus improving detection accuracy and discrimination stability in complex scenarios. Furthermore, this invention also considers the engineering implementation challenge of the dynamic fluctuation of the number of nodes with traffic flow in real-world V2X scenarios. Through mechanisms such as mask constraints, invalid node masking, and adjacency pruning, it uniformly restricts the impact of supplementary nodes on feature propagation, label calculation, and loss calculation, thereby avoiding the introduction of false edges, false labels, and the spread of invalid information due to the participation of invalid nodes in computation.
[0218] In summary, this invention not only enhances the ability to identify progressive, camouflaged, and continuously evolving known attacks in terms of detection principle, but also improves the stability and deployability of the model during training and inference under dynamic node scale conditions in terms of engineering implementation. Furthermore, due to its adoption of a two-stage discrimination and spatiotemporal joint modeling approach, it can also improve the ability to distinguish different types of known attacks while reducing the false alarm rate of normal samples. Therefore, it has high practical value and promotion significance.
Claims
1. An intrusion detection method for secure communication in connected vehicles, characterized in that, Includes the following processes: First, the received vehicle V2X messages are cleaned, aligned, and feature extracted on the RSU. Then, a spatiotemporal graph input consisting of vehicle nodes, adjacency relationships, node feature sequences, and masks is constructed within the sliding time window. The input is then fed into a spatiotemporal joint coding module deployed in the cloud. First, sparse temporal attention is used to extract the cross-time behavior evolution features of nodes. Then, graph networks are used to aggregate the spatial interaction relationships between nodes, and edge credibility modulation is combined to enhance the utilization of effective neighbor information. The system first distinguishes between normal and abnormal nodes by deploying a multi-layer discriminator in the cloud, then further subdivides the abnormal nodes by known attack types, and finally outputs the detection results to RSU to support RSU alarm handling. Specifically, the following steps are included: S1. Dataset Construction; The training dataset is constructed by taking the original CSV data during vehicle operation as input, and performing data cleaning, sample extraction, graph structure construction, and label generation on the timestamp, vehicle identifier, vehicle status information, and attack label fields, and organizing the original discrete records into basic observation data with consistent structure and temporal order. S2. Construct a temporal attention layer; Designing a sparse temporal attention module to model time series data with sparse attention can more effectively extract temporal anomaly features. S3. Construct a spatial attention layer; The design of the graph attention module is to adaptively learn the degree of influence of neighboring nodes on the current node under the constraints of known vehicle spatial connection relationships; and to introduce learnable edge gating on the basis of traditional graph attention mechanism, so as to integrate the initial connection weights and edge propagation weights between vehicles into the spatial modeling process. S4. Construct a two-layer classification output layer; After the spatiotemporal feature extraction network completes the encoding, each node in the sample will obtain a high-dimensional representation containing temporal information and spatial interaction information. In order to conform to the discrimination logic of the V2X attack detection task of "first determine whether it is abnormal, and then determine which type of abnormality it belongs to", the model adopts an explicit two-layer output structure. S5. Design the loss function; For the adopted two-layer judgment structure, an overall loss function is constructed.
2. The intrusion detection method for secure communication in connected vehicles according to claim 1, characterized in that, S1 specifically includes the following sub-steps: S1.1 Data cleaning; The raw input CSV data is cleaned and normalized. First, read the vehicle status information and attack tag fields from the raw data, including timestamp, vehicle identifier, location, speed, heading, acceleration, vehicle type, and so on. Then, perform a unified conversion on the data type of each field to meet the requirements of numerical calculation and time-series indexing. The system handles abnormal and redundant entries in the original records; it removes or corrects records with missing fields, incorrectly formatted fields, or those that are obviously unable to participate in subsequent calculations; and it randomly removes duplicate records of the same vehicle appearing at the same time. At the same time, all records are sorted according to timestamps to ensure that the state evolution process of the same vehicle and the same scenario remains consistent in the time dimension. S1.2 Sample extraction; Using a target vehicle at a certain central moment as the central node, a local traffic interaction scenario is constructed around the central node; First, the position of the target vehicle is obtained at the central moment, and the spatial distance between it and other vehicles at the same moment is calculated; then, based on the set neighborhood search radius, candidate neighbor nodes located within the local spatial range are selected and sorted according to distance or comprehensive importance. Only extract the top N=20 neighbor nodes based on importance; After extraction, this operation is repeated at historical time T, with the current central node as the core. S1.3 Graph Structure Construction; At the sample center moment, each traffic participant is used as the central node, and the relative spatial relationships of the remaining traffic participants in the scene are calculated one by one, and a local interaction graph is constructed accordingly. For any pair of nodes, the two-dimensional position coordinates of the two nodes at the center moment are extracted first, and their Euclidean distance is calculated. Then, the dynamic region of interest of the central node at the current moment is determined by combining the motion type, instantaneous velocity, and heading angle of the central node. The basic scale of the region of interest is determined by the type of traffic participant and further expands adaptively with the velocity of the central node. Different basic ranges are set for different traffic participants, and then superimposed with the velocity term to form the node-level perception radius, so that different nodes have different interaction search ranges. An anisotropic interaction region modeling mechanism related to heading is introduced. For motor vehicles, based on the angle between the heading angle of the center node and the relative azimuth angle of the candidate nodes, an asymmetric region of interest is constructed with priority given to forward direction, followed by lateral direction, and weaker backward direction. This makes the area of interest in front of the vehicle significantly larger than that behind and to the rear, which is more in line with the real traffic scenario of "stronger forward interaction and weaker backward influence". For non-motorized vehicles, a directional region with a larger forward direction and a smaller backward direction is adopted. For pedestrians, a relatively uniform neighbor attention method is adopted. Therefore, only when a candidate node falls into the effective region of interest of the corresponding type and orientation of the center node is it included in the adjacency candidate set. When the number of candidate neighbors exceeds the preset limit, the system sorts them according to the ratio of "actual distance divided by direction-normalized reachable distance", and prioritizes retaining neighbor nodes that are more interactive to the central node. After neighbor selection, the connection strength of the edges is assigned. The edge weights are determined by a distance decay factor and a spatial region prior factor. For motor vehicle nodes, different prior importance coefficients are assigned to different regions based on whether the candidate node is located in front of, to the left front, to the right front, to the left rear, or to the right rear of the center node. Then, the region prior is combined with a function that decays monotonically with distance to calculate the initial connection strength between node pairs. For pedestrians and non-motorized vehicles, directional weights and distance decay rules adapted to their motion characteristics are also adopted. The weights of each neighbor edge are normalized to ensure that they can be stably used for message propagation and feature aggregation in the subsequent graph neural network. S1.4 Tag Generation; By combining the attack status of the target node or adjacent nodes within the time window, the training labels of each node are determined. S1.5 Dataset Construction and Mask Matrix Design; The constructed spatiotemporal graph samples are organized into dataset files that can be directly used for model training. For each center time and target vehicle that meets the graph construction conditions, a corresponding single sample is generated, and the sample features, connectivity graph, and labels are encapsulated into structured data units for storage. A mask matrix matching the above dataset structure is designed. If the maximum number of nodes in a single batch processing parallel environment is Nmax, then in each single sample with N actual nodes, the first N positions are marked as 1 to represent real valid nodes, and the remaining Nmax-N positions are set to 0, representing zero-padding nodes introduced to meet batch processing alignment.
3. The intrusion detection method for secure communication in connected vehicles according to claim 1, characterized in that, The specific method for S2 is as follows: Let Q, K, and V be the input matrices for attention, and define the temporal mask matrix and the set of computable locations M. t,τ Where t and τ represent time t and time τ, respectively: , At this point, the initial attention score e between times (t, τ) t,τ Calculate using the following method: , The corresponding attention score a between times (t, τ) t,τ Use the following normalization formula: , The output z of sparse attention n (t) is: , Multi-head attention models linearly project inputs Q, K, and V using different learned projection parameter matrices, then input them into the attention calculation formula, repeating this process h times. The output values of each head are concatenated to form the final output; multi-head sparse attention: , , The fully connected feedforward neural network layer FFN(X) consists of two fully connected neural network layers, with a linear activation layer in between, using the ReLU activation function. , in This is the weight matrix of the fully connected layer. This is the bias vector of the fully connected layer; Residual connection layers are used to improve the vanishing gradient problem: , Normalization layers are used to stabilize the training process: , in Output for residual connection layer Mean and variance of each layer For an infinitesimal quantity, These are the parameters to be learned.
4. The intrusion detection method for secure communication in connected vehicles according to claim 1, characterized in that, The specific method for S3 is as follows: First, h is obtained by dimensionality transformation of the output of the time attention layer. i The hidden representation of each node in the time dimension is obtained through linear mapping. : , Among them W h The weight matrix is learnable; then, concatenated features are constructed for any node pair (i,j), and the base attention score is calculated: , Where 'a' is a learnable weight matrix, and || denotes the concatenation operation; based on this, the model further introduces an edge gating mechanism, which jointly generates edge weights by combining connection matrix information and a small MLP encoding results based on node information: , Where A i,j The connection matrix is used; based on the basic attention and edge weighting results, the final attention score is obtained: , in To avoid small calculation failures; Starting with attention scoring, normalization is performed only on nodes with non-zero adjacency matrices to obtain the final attention score: , Neighborhood aggregation is performed based on attention scores to obtain the output h on the spatial module. i ': , A multi-head graph attention module is used on top of the single-head graph attention layer. The multi-head graph attention module consists of multiple parallel single-head graph attention layers. Each attention head shares the same input node features, adjacency relationships, and node masks, but has its own independent parameters, enabling it to learn different spatial association patterns. , Where K is the number of attention heads, H is the spatial state information of the input and output, A is the connection matrix, and M is the mask matrix; then, the outputs of each head are concatenated along the feature dimension to obtain: , Then, dimensionality compression is performed through a linear fusion layer to obtain the output result: , Among them W g (l) and b g (l) They are all learnable matrices.
5. The intrusion detection method for secure communication in connected vehicles according to claim 1, characterized in that, The specific method for S4 is as follows: The first output layer is responsible for performing a normal or abnormal binary classification to answer the question "Does the current node exhibit abnormal behavior?" The second output layer is responsible for performing detailed classification of exception types, which is used to further identify the specific attack category when the first layer determines that it is an exception; its core implementation includes three parts: shared encoder, first-layer classification header head_stage1, and second-layer classification header head_stage2; The shared encoder first filters the output of the spatiotemporal layer for effective nodes and flattens the output in both the temporal and node dimensions. Then, the adjusted output is input into a two-layer neural network for information extraction. , in, 1 and 2 represents the combined operation of "linear transformation + normalization + activation + dropout", and W1, W2, b1, and b2 are all learnable matrices; this encoding process compresses the multidimensional observations of a node over the entire time window into a compact semantic representation z. t This is for use by the subsequent two levels of discrimination heads; The first-layer output head_stage1 and the second-layer output head_stage2 are both linear classifiers, and their input is the shared embedding z. t Output the attack probability p and the attack type classification result y, respectively; the corresponding classifier structures are: output=Wz+b , Both W and b are learnable matrices.
6. The intrusion detection method for secure communication in connected vehicles according to claim 1, characterized in that, In S5, the overall loss function is: , Where L Stage1 This represents the error during the first-level detection, i.e., the error in distinguishing whether the message is normal or abnormal. , Where α is the balance factor, γ is the hard sample adjustment factor, and p t Let be the probability that the sample is actually a positive sample, that is: , L Stage2 This represents the error during secondary detection, specifically the error arising from distinguishing which type of attack anomaly the message belongs to: , Where x represents the model output, y represents the true label, C represents the number of categories, and n represents the number of attack samples.