A vehicle-mounted CAN intrusion detection method based on image mapping and boundary enhancement

By performing windowing and image mapping on vehicle CAN messages, combined with a lightweight RepVGG-lite network and boundary enhancement mechanism, the problems of insufficient structural information representation and limited ability to distinguish easily confused categories in vehicle CAN intrusion detection are solved, achieving high-precision and low-complexity intrusion detection.

CN122116333APending Publication Date: 2026-05-29CHANGCHUN UNIV

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
CHANGCHUN UNIV
Filing Date
2026-04-21
Publication Date
2026-05-29

Smart Images

  • Figure CN122116333A_ABST
    Figure CN122116333A_ABST
Patent Text Reader

Abstract

The application discloses a vehicle-mounted CAN intrusion detection method based on image mapping and boundary enhancement. When data is processed, each type of original message data is divided in time sequence, and is sequentially divided into a training set, a verification set and a test set. The features of the training set are standardized and fitted, and the same parameters are used to transform the verification set and the test set. Then, continuous message sequences are converted into a fixed-length window feature matrix to generate a window-level label. A lightweight image classification network is constructed, which is provided with a main classification branch and a boundary enhancement branch. The boundary enhancement branch is used to complete boundary enhancement constraint between normal classes and easily confused Gear classes. A training loss function is composed of a main classification loss and a boundary enhancement loss. The boundary enhancement loss is constructed based on intra-class compactness and inter-class separability. Finally, the received CAN data is identified and classified by using the trained model. The method can balance detection accuracy and lightweight deployment requirements.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of vehicle networking and communication security technology, specifically, it relates to an in-vehicle CAN intrusion detection method based on image mapping and boundary enhancement. Background Technology

[0002] With the development of intelligent connected vehicles, multiple ECUs (Electronic Control Units) inside the vehicle transmit control information via the CAN bus, forming a complex in-vehicle communication network. Because the CAN bus typically uses broadcast communication and lacks authentication and message encryption mechanisms, if an attacker injects forged messages into the bus, it could affect vehicle speed, gear position, and other critical control information, thus threatening vehicle operational safety.

[0003] Most existing vehicle-mounted CAN intrusion detection methods directly model single message or ordinary table features. For example, the DCNN model proposed by Hyun Min Song et al. (Song, Hyun Min, Jiyoung Woo, and Huy KangKim. "In-vehicle network intrusion detection using deep convolutional neural network." Vehicular Communications 21 (2020): 100198.) mainly converts CAN traffic into a two-dimensional grid structure and then inputs it into a deep convolutional neural network for detection. Its focus is on using convolutional networks to automatically learn message patterns. AK Desta et al. proposed the Rec-CNN model (Desta, Araya Kibrom, et al. "Rec-CNN: In-vehicle networks intrusion detection using convolutional neural networks trained on recurrence plots." Vehicular Communications 35 (2022):100470.), which uses recurrence plots to graphically represent sequence relationships and then combines them with CNNs for classification. Its focus is on preserving time-series dependencies. While existing methods have improved upon these approaches through convolutional modeling and temporal visualization, enabling them to detect anomalous behavior to some extent, they fail to adequately utilize the local structural features, temporal differences, and multi-field coupling relationships within the continuous message window of an automotive CAN bus, making it difficult to fully characterize the differences between various attack patterns. Furthermore, in multi-category attack identification scenarios, normal traffic and some deceptive attacks often exhibit high similarity, leading to unclear model boundaries in the feature space and a tendency for category confusion.Furthermore, W. Lo et al. proposed a hybrid deep learning detection method based on CNN-LSTM (Lo, Wei, et al. "A hybrid deep learning based intrusion detection system using spatial-temporal representation of in-vehicle network traffic." Vehicular Communications 35 (2022): 100471.), which uses CNN and LSTM for joint spatial-temporal modeling. While this improves detection accuracy, it also increases model complexity and computational overhead. Deeper networks, larger parameter counts, or higher computational complexity make it difficult to adapt to resource-constrained in-vehicle terminal environments, resulting in shortcomings in real-time detection and practical deployment. Therefore, there is an urgent need to propose an in-vehicle intrusion detection method that can effectively visualize the in-vehicle CAN message window and enhance the ability to distinguish easily confused categories by combining sample constraints. Summary of the Invention

[0004] To address the shortcomings of existing vehicle-mounted CAN intrusion detection methods, such as insufficient representation of continuous message window structure information, limited ability to distinguish easily confused attack category boundaries, and difficulty in balancing detection accuracy with lightweight deployment requirements, this invention provides a vehicle-mounted CAN intrusion detection method based on image mapping and boundary enhancement. This method performs windowing processing on continuous CAN messages and maps the window features to fixed-size grayscale images. Combined with a lightweight RepVGG-lite image classification network and boundary enhancement mechanisms for normal and Gear classes, it achieves high-precision detection of five message types: Normal, DoS, Fuzzy, Gear, and RPM, thereby improving the accuracy, stability, and practical feasibility of vehicle-mounted CAN intrusion detection.

[0005] To achieve the above objectives, the present invention adopts the following technical solution: A method for intrusion detection in vehicle CAN based on image mapping and boundary enhancement, comprising the following steps: Step S1. Data preprocessing: First, the raw data is parsed, and basic feature fields are constructed for each CAN message. Then, each type of raw message data is segmented according to time order, and divided into training set, validation set, and test set. Next, the features of the training set are standardized and fitted, and the same parameters are used to transform the validation set and test set. Then, the continuous message sequence is converted into a fixed-length window feature matrix to generate window-level labels. Finally, the window feature matrix is ​​mapped to image samples. Step S2. Construct a lightweight RepVGG-lite image classification network. The lightweight RepVGG-lite image classification network includes three cascaded feature extraction modules, an adaptive average pooling layer, a flattening layer, a shared feature layer, and two parallel main classification branches and boundary enhancement branches. The shared feature layer includes a fully connected layer, a GELU activation layer, and a random deactivation layer arranged sequentially. The main classification branch performs five classifications based on the shared features output by the shared feature layer and calculates the probability distributions of the five classes. The boundary enhancement branch is used to perform boundary enhancement constraints between the normal class and the easily confused Gear class based on the shared features. Step S3. Train the lightweight RepVGG-lite image classification network constructed in Step S2 based on the data obtained in Step S1. The training loss function consists of two parts: main classification loss and boundary enhancement loss. The boundary enhancement loss is constructed based on intra-class compactness and inter-class separability. Step S4. Based on the trained lightweight RepVGG-lite detection model, identify and classify the received CAN traffic data to determine the intrusion detection result.

[0006] As a preferred embodiment of the present invention, when dividing each type of original message data according to time order in step S1, all data is first divided into a 70% development set and a 30% test set according to time order, and then the development set is further divided into an 80% training set and a 20% validation set.

[0007] Preferably, in step S1, when converting the continuous message sequence into a fixed-length window feature matrix, the window length is... window_size The sliding step size is stride Then from the length of From the message sequence, the window is extracted as follows: ; Each window contains a continuous window_size Each message is represented by an 8-dimensional feature vector, resulting in the following shape: The window feature matrix is ​​mapped to a fixed-size two-dimensional grayscale image through rearrangement or interpolation.

[0008] As a preferred embodiment of the present invention, when generating window-level labels in step S1, the category labels are defined as: Normal = 0; Dos = 1; Fuzzy = 2; Gear = 3; Rpm = 4; for normal data windows, the label is directly recorded as Normal; for windows generated by attack files, the proportion of injected packets inside the window is first calculated. The expression is:

[0009] Then compare this ratio with the preset threshold min_attack_ratio = 0.1. If attack_ratio ≥min_attack_ratio, then this window is marked as the corresponding attack category; if attack_ratio <min_attack_ratio, then this window is marked as Normal after being rolled back.

[0010] As a preference of the present invention, the three cascaded feature extraction modules in step S2 are the first feature extraction module, the second feature extraction module, and the third feature extraction module in sequence; the first feature extraction module is used to process the input image sample tensor to extract low-level local texture features; the second feature extraction module is used to process the low-level local texture features to extract middle-level structural features; the third feature extraction module is used to process the middle-level structural features to extract high-level discriminative semantic features and perform global feature compression.

[0011] As a further preference of the present invention, the first feature extraction module includes a convolution branch and a convolution branch arranged in parallel. After convolution in each branch, batch normalization is performed. Subsequently, the outputs of the two branches are added element by element and output after being processed by a non-linear activation function; a first max pooling layer is connected after the first feature extraction module; The second feature extraction module includes a pointwise convolution layer, a depth convolution layer, and a pointwise convolution layer connected in sequence. After each convolution layer, batch normalization is combined, and finally, it is output after being processed by the GELU non-linear activation function; a second max pooling layer is connected after the second feature extraction module; The third feature extraction module includes a pointwise convolution layer, a depth convolution layer, and a pointwise convolution layer connected in sequence. After each convolution layer, batch normalization is also combined, and finally, it is output after being processed by the GELU non-linear activation function; an adaptive average pooling layer is connected after the third feature extraction module.

[0012] As a further preferred embodiment of the present invention, the first feature extraction module, the second feature extraction module, and the third feature extraction module all employ the GELU nonlinear activation function. The first feature extraction module has 1 input channel and 48 output channels; the second feature extraction module has 48 input channels and 96 output channels; and the third feature extraction module has 96 input channels and 192 output channels. The adaptive average pooling layer is AdaptiveAvgPool2d. The fully connected layer within the shared feature layer is used to map the input features from 192 dimensions to 96 dimensions, and the inactivation rate of the random inactivation layer is 0.3.

[0013] As a further preferred embodiment of the present invention, the expression for the training loss function in S3 is: ; in, This represents the primary classification loss for a five-class classification task; This represents the boundary augmentation loss constructed for the normal class and the Gear class; The weights representing the boundary augmentation loss; The main classification loss uses Focal Loss, and its expression is: ; in, This represents the model's predicted probability of the true class. Represents the category weight coefficient. This represents the focusing coefficient.

[0014] As a preferred embodiment of the present invention, the boundary enhancement branch extracts sample features belonging to the Normal and Gear classes from the shared features, and constructs the Normal-Gear boundary enhancement loss based on intra-class compactness and inter-class separability, expressed as: ; ; ; Among them, the internal tightening loss is Inter-class separation loss is , Indicates the weight of compact items within the class. Indicates the weight of the separation item between classes. This represents the preset boundary margin, and the normal sample set is... The Gear class sample set is The center of the normal class and the center of the Gear class are respectively and .

[0015] As a preferred embodiment of the present invention, after completing the calculation of the training loss function, S3 uses the backpropagation algorithm to solve the gradient of the model parameters and uses the AdamW optimizer to iteratively update the model parameters. During the update, the gradient of each layer parameter is first calculated according to the loss function; then the gradient is adaptively adjusted based on the first moment and the second moment; finally, a weight decay term is introduced during the update process.

[0016] Advantages and beneficial effects of the present invention: (1) Window-based image representation enhances the ability to represent the local structural patterns of vehicle CAN messages. This invention organizes continuous vehicle CAN messages into fixed windows and maps them to fixed-size single-channel grayscale images, transforming the field combination relationships in the original messages into a two-dimensional structural representation. This allows the model to simultaneously learn local texture features, field coupling relationships, and overall distribution patterns. Compared with methods that directly model based on single message or ordinary table features, this approach is more conducive to improving the separability between different attack types, thereby improving the accuracy and stability of vehicle CAN intrusion detection.

[0017] (2) Strict temporal partitioning and a low attack ratio threshold together improve the quality of window-level labels. In the data preprocessing stage, this invention adopts a strict temporal partitioning of the training set, validation set, and test set, which is more in line with the actual vehicle detection scenario and avoids information leakage to the training stage in the future. At the same time, in the window-level label generation stage, a low attack ratio threshold min_attack_ratio = 0.10 is used, which allows weak attack mixed windows to be more reasonably assigned attack labels, reducing the situation where they are mistakenly labeled as normal windows, thereby reducing label noise and improving the model training quality and subsequent detection effect.

[0018] (3) Lightweight RepVGG-lite Image Classification Network Balances High Accuracy and Low Complexity. This invention employs a lightweight RepVGG-lite image classification network to extract features from 32×32 single-channel grayscale images. The network retains the RepVGG-like basic feature extraction structure at the front end to enhance its ability to express local texture and low-level structural information; at the back end, it uses a lightweight depthwise separable convolutional feature extraction module to reduce the number of parameters and model complexity. Experimental results show that the current model has only 93,513 parameters and approximately 0.3567 MB of memory, demonstrating good lightweight characteristics and feasibility for engineering deployment.

[0019] (4) The selective boundary enhancement mechanism based on Normal-Gear Margin Loss improves the ability to distinguish key easily confused class pairs. In multi-class vehicle CAN intrusion detection tasks, normal traffic and Gear spoofing attacks are more similar in overall message structure, periodic features, and field distribution, and belong to key easily confused class pairs. To address this issue, this invention introduces Normal-Gear Margin Loss, which applies representation space constraints only to Normal and Gear class samples. By reducing intra-class distance and increasing inter-class interval, the boundaries between the two classes of samples in the shared feature space become clearer, thereby effectively reducing the false positive rate and improving the model's ability to identify fine-grained spoofing attacks.

[0020] (5) This invention achieves high-precision five-class classification detection while maintaining a lightweight design, and also possesses good inference efficiency and real-time processing capabilities. This invention achieved excellent performance on the Car-Hacking full-scale five-class classification task, with a test set accuracy of 99.9897%, a macro average precision of 99.9763%, a macro average recall of 99.9460%, and a macro average F1 score of 99.9611%. These results demonstrate that this invention can achieve high-precision identification of five types of vehicle CAN traffic: Normal, DoS, Fuzzy, Gear, and RPM, and has good practical application value. Under full-scale testing conditions, the average CPU utilization of this invention is approximately 7.14% (14 logical core environment), the throughput reaches 48548.91 samples / s, and the average processing time is 0.0206 ms / sample. This indicates that while maintaining high detection accuracy, this invention still possesses low resource consumption and high processing efficiency, and can better meet the requirements of vehicle intrusion detection for real-time performance and lightweight deployment. Attached Figure Description

[0021] Other objects and results of the invention will become more apparent and readily understood with reference to the following description taken in conjunction with the accompanying drawings. In the drawings: Figure 1 This is a flowchart of the training process for the lightweight RepVGG-lite image classification network (RepVGG-lite model); Figure 2 This is a schematic diagram of the lightweight RepVGG-lite image classification network provided by the present invention; Figure 3 This is the confusion matrix diagram provided by the present invention; Figure 4 This is a bar chart showing the results of this invention. Detailed Implementation

[0022] To enable those skilled in the art to better understand the technical solutions and advantages of the present invention, the present application will be described in detail below with reference to the accompanying drawings, but this is not intended to limit the scope of protection of the present invention.

[0023] like Figure 1 , Figure 2 As shown, the present invention provides a vehicle CAN intrusion detection method based on image mapping and boundary enhancement, which specifically includes the following steps: Step S1. Data preprocessing: Step S101. Parsing the raw data (raw CAN message): The vehicle CAN data used in this invention comes from the publicly available dataset: Car-Hacking dataset, which contains five types of files: normal driving data: Normal_run_data.txt; DoS attack (high-frequency flooding of specific IDs, occupying bus bandwidth): DoS_dataset.csv; Fuzzy attack (randomly generated IDs and payloads, disrupting node logic): Fuzzy_dataset.csv; Gear spoofing attack (forging shift and speed signals, causing dangerous behavior): Gear_dataset.csv; RPM spoofing attack (forging shift and speed signals, causing dangerous behavior): RPM_dataset.csv.

[0024] The script automatically adapts to two original formats: text-based rows and 12-column CSV files. The specific processing flow is as follows: Figure 1 As shown: First, convert them to standard fields:

[0025] in, This is a timestamp used in this dataset to record the time when a CAN message is received; An integer representing the priority of a CAN message; An integer representing the length of the CAN message data; For the data fields of the CAN message, This serves as a marker to indicate whether the data constitutes an injection attack.

[0026] Step S102. Construct message field characteristics: After parsing the original message, this invention constructs basic feature fields for each CAN message. The feature fields for image mapping are fixed as follows: A total of 8 features.

[0027] Step S103. Divide the training set, validation set, and test set in chronological order: To better reflect actual vehicle-mounted testing scenarios, this invention segments each type of raw message data chronologically. Specifically, each type of data is divided into: training set: validation set: test set = 56%: 14%: 30%. That is, all data is first divided into a 70% development set and a 30% test set in chronological order, and then the development set is further divided into an 80% training set and a 20% validation set. This design can simulate, as closely as possible, the application method in actual operation where "historical data is used for training, and subsequent data is used for testing."

[0028] Step S104. Standardize the features: To reduce the impact of differences in feature dimensions on subsequent image mapping and model training, this invention performs standardized fitting on the training set features after time segmentation and uses the same parameters to transform the validation and test sets.

[0029] Specifically, the training subset features of the Normal, DoS, Fuzzy, Gear, and RPM classes are first concatenated row by row to obtain a unified training fit set, train_for_fit. Then, the data standardization tool StandardScaler is used for fitting. For feature x, the StandardScaler transformation is as follows:

[0030] in, This represents the mean of the feature in the training set; This represents the standard deviation of the feature in the training set; This represents the standardized features.

[0031] Finally, the data standardization tool StandardScaler was used to transform corresponding samples in the training, validation, and test sets using the same standardization parameters. This design ensures that data from different categories are comparable within a unified feature space, while preventing test set information from leaking into the training phase.

[0032] Step S105. Perform sliding window slicing on consecutive CAN messages: After standardization, this embodiment converts the continuous message sequence into a fixed-length window sample. Specifically, let the window length be... window_size The sliding step size is stride Then from the length of From the message sequence, the window is extracted as follows:

[0033] Each window contains a continuous window_sizeEach message is represented by the above 8-dimensional feature vector, thus forming a window feature matrix with the shape of: This matrix is further mapped into a grayscale image with a fixed size through rearrangement or interpolation, serving as the input for the subsequent convolutional neural network.

[0034] Specifically, in this embodiment, the specific parameters used for preprocessing are: window_size = 32, stride = 32. That is, every 32 messages form a window, and there is no overlap between windows. If the length of the original sequence is less than one window, then this sequence does not participate in the construction of window samples and an empty sample set is directly returned.

[0035] Step S106. Generate window-level labels: In this embodiment, the class labels are defined as: Normal = 0; Dos = 1; Fuzzy = 2; Gear = 3; Rpm = 4. For normal data windows, since all row-by-row labels are 0, the corresponding window label is directly recorded as Normal. For windows generated from attack files, first calculate the proportion of injected messages within the window , and the expression is:

[0036] Then compare this proportion with the preset threshold min_attack_ratio = 0.1. If attack_ratio ≥ min_attack_ratio, then this window is marked with the corresponding attack category; if attack_ratio < min_attack_ratio, then this window is fallback marked as Normal. That is: when in a window composed of 32 messages, at least 10% of the messages are attack-injected messages, this window is given an attack label; otherwise, it is still regarded as a normal window. This design helps to reduce the label noise caused by mixed windows.

[0037] Step S107. Map the window feature matrix into image samples: After obtaining the window-level feature matrix, the present invention further maps the window features in tabular form into image samples for subsequent modeling using an image classification model.

[0038] Specifically, for each window feature matrix window_feats, first expand it row by row into a one-dimensional vector; then, through linear interpolation and resampling, reconstruct this one-dimensional vector into a two-dimensional grayscale image. Set the image size as image_size = 32, thus obtaining a single-channel grayscale image with the size of .

[0039] Step S108. Summarize and save the preprocessing results: After constructing window samples for each category and data partition, this invention concatenates the window image samples and their labels from the training set, validation set, and test set to form three complete sample sets. Subsequently, each set is saved as a compressed npz file, which contains: an image sample tensor X and a window-level label vector y. At this point, the preprocessing stage is complete.

[0040] Step S2. Construct a lightweight RepVGG-lite image classification network: like Figure 2 As shown, this invention employs a lightweight RepVGG-lite image classification network based on an improved RepVGG structure as the backbone feature extractor to extract local texture features, spatial structure features, and high-level discriminative features from the input grayscale image. The lightweight RepVGG-lite image classification network includes three cascaded feature extraction modules, an adaptive average pooling layer, a flattening layer, a shared feature layer, and two parallel main classification branches and a boundary enhancement branch.

[0041] The three cascaded feature extraction modules are, in sequence, the first feature extraction module, the second feature extraction module, and the third feature extraction module; the first feature extraction module is used to process the input image sample tensor. Processing is performed to extract low-level local texture features. The second feature extraction module is used to extract low-level local texture features. The process is performed to extract mid-level structural features; the third feature extraction module is used to process the mid-level structural features. The image is processed to extract high-level discriminative semantic features and perform global feature compression. The input image sample is a single-channel grayscale image with a size of [size missing]. .

[0042] Furthermore, in this embodiment, the first feature extraction module is constructed using a RepVGG-like basic convolutional structure to enhance its ability to express local texture information and basic structural information in the input grayscale image. Specifically, this module includes parallel configurations... Convolutional branches and The convolutional branches undergo batch normalization (BN) after each convolution. The outputs of the two branches are then element-wise summed and processed by a non-linear activation function before being output. Preferably, the non-linear activation function is the GELU activation function. The first feature extraction module is followed by a first max-pooling layer (MaxPool) to reduce the spatial resolution of the feature map and output low-level local texture features. .

[0043] Furthermore, in this embodiment, the second feature extraction module employs a lightweight convolutional block structure to further extract mid-level structural features with lower model complexity. Specifically, the second feature extraction module includes sequentially connected... Pointwise convolutional layer Deep convolutional layers and The system consists of pointwise convolutional layers, each followed by batch normalization, and finally processed by a non-linear activation function (GELU activation function) before output. A second max-pooling layer follows the second feature extraction module to further compress the feature map size and output mid-level structural features.

[0044] Furthermore, in this embodiment, the third feature extraction module also employs a lightweight convolutional block structure to further extract high-level discriminative semantic features while maintaining lightweight characteristics. Specifically, the third feature extraction module includes sequentially connected... Pointwise convolutional layer Deep convolutional layers and The pointwise convolutional layers combine pointwise convolution with depthwise convolution to extract high-level semantic information with low model complexity. Each convolutional layer is followed by batch normalization, and the output is finally processed by a non-linear activation function (GELU activation function). The third feature extraction module is followed by an adaptive average pooling layer for global feature compression in the spatial dimension.

[0045] Furthermore, the adaptive average pooling layer is AdaptiveAvgPool2d. That is, the output size is fixed. .

[0046] Furthermore, in the main experimental configuration of this invention, the first feature extraction module has 1 input channel and 48 output channels; the second feature extraction module has 48 input channels and 96 output channels; and the third feature extraction module has 96 input channels and 192 output channels. After passing through the third feature extraction module and the adaptive average pooling layer, the output size is... The feature map is then flattened into a one-dimensional feature vector of length 192 through a flattening layer and input into a shared feature layer for feature mapping.

[0047] Furthermore, in this embodiment, the shared feature layer includes a fully connected layer, a GELU activation layer, and a random deactivation layer arranged sequentially; wherein, the fully connected layer is used to map the input features from 192 dimensions to 96 dimensions; the deactivation rate of the random deactivation layer is preferably 0.3. Through this shared feature layer, a compact shared feature representation can be obtained, which can be used as the common input for the subsequent main classification branch and boundary enhancement branch.

[0048] Furthermore, in this embodiment, the main classification branch is used to complete the five-class classification task. The main classification branch first inputs the shared features into the main classification head, which employs a fully connected Linear layer. The algorithm is used to output five-class logits; the five output classes correspond to Normal, DoS, Fuzzy, Gear and RPM respectively; then, the probability distribution of the five classes is calculated by Softmax, and the main classification loss is constructed based on this.

[0049] Furthermore, in this embodiment, the boundary enhancement branch is used to complete the boundary enhancement constraint between the Normal class and the easily confused Gear class, that is, to construct feature space constraints between the normal class Normal and the easily confused attack class Gear. Specifically, sample features belonging to the Normal class and Gear class are extracted from shared features, and a Normal-Gear Margin Loss is constructed based on intra-class compactness and inter-class separability to enhance the boundary separability of the two classes of samples in the shared feature space.

[0050] Compared with traditional deep image classification networks that consist entirely of standard convolutions, this invention balances the ability to extract local structural features with the need for lightweight models by retaining the RepVGG-like basic convolutional structure at the front end and introducing a lightweight depthwise separable convolutional module at the back end. This allows the network to maintain high detection accuracy while having a lower number of parameters and better feasibility for practical deployment.

[0051] During the training phase, the output of the main classification branch is used to construct the five-class main loss, and the boundary augmentation branch is used to construct the Normal-Gear boundary augmentation loss. Together, they form a joint loss function to optimize the network parameters. During the inference phase, only the output of the main classification branch is retained as the final five-class classification result, and the boundary augmentation branch does not participate in the final classification output.

[0052] Step S3. Train the lightweight RepVGG-lite image classification network constructed in Step S2 based on the data obtained in Step S1; This step is mainly used for supervised learning of the grayscale image window samples generated in the preprocessing stage to build an image classification model suitable for vehicle CAN intrusion detection, namely the RepVGG-lite model. During the training phase, the npz format data file output from the preprocessing stage is first read to obtain the image sample tensors X and corresponding window-level label vectors y from the training, validation, and test sets, and then the image data and label data are concatenated.

[0053] The tensor shape of each image sample is: ;in: Indicates the number of image channels; This indicates the image height and width. In this invention, =1, =32, =32.

[0054] Read the (C,H,W) tensor for each sample; the storage type is uint8, which is automatically converted to floating-point and normalized to the [0,1] interval during training for input to the RepVGG-lite image classification network. Then, construct the data loaders for the training, validation, and test sets respectively. The current training set uses random shuffling to construct batches with a batch size of 64.

[0055] Then, the lightweight RepVGG-lite image classification network is input, and the feature extraction and five-class classification are performed on the single-channel grayscale image formed by the mapping of the vehicle CAN message window through the lightweight RepVGG-lite image classification network.

[0056] The training strategy and loss function are as follows: In this invention, a joint loss function is used to train and optimize the lightweight RepVGG-lite image classification network (model); the joint loss function (training loss function) consists of two parts: the main classification loss and the boundary enhancement loss, and its expression is:

[0057] in, This represents the Focal loss for a five-class classification task. This represents the margin loss constructed for the normal class and the Gear class; The weights represent the boundary enhancement loss.

[0058] This joint loss function serves as the overall optimization objective during the model training phase. On the one hand, it ensures multi-class classification performance, and on the other hand, it enhances the ability to distinguish the boundary between the normal class and the Gear class.

[0059] The main classification loss uses Focal Loss to improve the model's learning ability for imbalanced and hard-to-classify samples. Its expression is:

[0060] in, This represents the model's predicted probability of the true class. Represents the category weight coefficient. This represents the focusing coefficient, in this embodiment... .

[0061] The sample features output by the shared feature layer are The normal sample set is denoted as The Gear class sample set is denoted as Define the normal class center and the Gear class center as follows:

[0062]

[0063] To make the internal features of the normal class and the Gear class more concentrated, the intra-class compactness loss is defined as: ; To maintain a sufficient gap between the normal class centers and the Gear class centers, the inter-class separation loss is defined as: ; in, This represents the preset boundary spacing margin, in this embodiment. When the distance between the centers of the two classes is greater than or equal to When the distance between the centers of the two classes is less than 0, this term is 0. In this case, this item is a penalty item.

[0064] Based on intra-class compactness and inter-class separability, a Normal-Gear Margin Loss is constructed, and the final boundary augmentation loss is: ;in, Indicates the weight of compact items within the class. In this invention, the weights of the separated items between classes are represented. , .

[0065] Therefore, the overall training loss is obtained:

[0066] This boundary enhancement loss function is used to constrain the relative distribution of the Normal and Gear classes in the shared feature space. Its parameters are set as follows: .

[0067] After calculating the joint loss function, the backpropagation algorithm is used to solve for the gradients of the model parameters, and the AdamW optimizer is used to iteratively update the model parameters. Specifically, firstly, the gradients of the parameters of each layer are calculated according to the loss function; then, the gradients are adaptively adjusted based on the first and second moments; finally, a weight decay term is introduced during the update process to improve the model's generalization ability.

[0068] The parameter update process of the AdamW optimizer is as follows:

[0069]

[0070]

[0071]

[0072] in, and These are the exponential decay coefficients estimated by the first moment and the second moment, respectively. For the current gradient, The learning rate is used to control the step size for parameter updates. This is the weight decay coefficient, used to constrain the size of model parameters and improve the model's generalization ability. and These represent the first moment and second moment estimates of the gradient, respectively, used for gradient smoothing and adaptive scaling. and This is the estimated value after bias correction. To prevent stable terms with a denominator of 0, and These are the exponential decay coefficients. and The power of t at the t-th iteration is used to correct the bias in the first-order moment estimate and the second-order moment estimate. These are the model parameters updated after the t-th iteration.

[0073] In this embodiment, the number of training epochs is set to 10, the batch size is set to batch_size=64, and the learning rate is set to... =1e-4, weight decay parameter =1e-4, random seed=42.

[0074] During training, after each training round, the following metrics are calculated on the validation set: Validation set accuracy val_acc; Verify the macro average F1 value of the validation set, val_macro_f1; The optimal model is saved based on val_macro_f1. When val_macro_f1 in the current round is better than the historical best value, the current model parameters are saved as the optimal weight file.

[0075] After all training epochs are completed, the model weights with the best validation set metrics are loaded as the final trained RepVGG-lite detection model. In the subsequent testing phase, only the main classification branch is retained for forward inference, outputting the final five-class classification result; the joint loss function is only used to guide parameter updates during training and does not participate in the inference output.

[0076] Step S4. Based on the trained lightweight RepVGG-lite detection model, identify and classify the received CAN traffic data to determine the intrusion detection result.

[0077] Ultimately, this invention achieved near 100% accuracy and recall in experiments, significantly outperforming traditional CNN / RNN / Transformer methods. Furthermore, this invention was also tested on the Car-hacking dataset for accuracy, precision, recall, and F1 score of P-LeNet (a publicly available model of a Deeptransfer learning based intrusion detection system for electric vehicular networks), KNN (Nearest Neighbor Algorithm), SVM (Support Vector Machine), DCNN (Deep Convolutional Neural Network), and CANet (An unsupervised intrusion detection system for high dimensional CAN busdata). The results are shown in the table below.

[0078] Table 1 Comparative test results Model Accuracy (%) Accuracy (%) Recall rate (%) F1(%) P-LeNet 98.10 98.04 98.14 97.83 KNN 96.30 97.40 96.40 93.40 SVM 96.50 95.80 95.70 93.37 DCNN 99.93 99.84 99.84 99.91 CANet 98.75 98.75 99.09 98.89 Ours 99.98 99.97 99.94 99.96 Results: The model of this invention achieved accuracy, precision, recall, and F1 score of 0.9998, 0.9997, 0.9994, and 0.9996, respectively, demonstrating excellent performance. Specifically, its accuracy was 0.0188, 0.0368, 0.0348, 0.0005, and 0.0123 higher than P-LeNet, KNN, SVM, DCNN, and CANet, respectively. Its F1 score was 0.0193, 0.0257, 0.0417, 0.0013, and 0.0122 higher than P-LeNet, KNN, SVM, DCNN, and CANet, respectively. Furthermore… Figure 3 The resulting confusion matrix further demonstrates that the present invention has an excellent ability to distinguish between various attack categories.

[0079] Furthermore, this invention also evaluated the CPU utilization, number of parameters, parameter memory, throughput, and average processing time during the experiment, and the results are shown in the table below: Table 2 Performance Evaluation Results CPU utilization (%) Memory usage (MB) Number of parameters Throughput (samples / s) Average processing time (ms / sample) 7.14 0.3567 93513 48548.91 0.0206 As can be seen from Table 2, the present invention exhibits excellent performance indicators during the evaluation process: the CPU utilization rate of the model is 7.14%, and the memory size occupied by the model parameters is only 0.3567MB, showing low resource consumption; the throughput of the model reaches 48548.91 samples / second, while the average processing time per sample is 0.0206 milliseconds, demonstrating efficient processing capability and fast response speed.

[0080] It should be noted that in multi-category vehicle CAN intrusion detection tasks, the separability between different categories varies significantly. DoS attacks and fuzzy attacks typically exhibit obvious abnormal patterns, showing significant differences from the normal class and are easily distinguishable. However, Gear and RPM attacks, by forging legitimate messages and modifying only a few fields, have overall characteristics highly similar to normal messages, making them typical easily confused categories. Applying uniform boundary constraints to all categories not only introduces additional computational overhead but may also lead to over-constraint of the feature space, affecting the model's convergence stability and generalization ability. Therefore, this invention employs a selective discrimination enhancement strategy, introducing Margin Loss constraints only for the key easily confused category pair of the normal class and the Gear attack class. By explicitly increasing the feature distance between the normal class and the Gear attack class in the shared feature space, the two classes of samples have clearer discriminative boundaries in their feature distributions. This effectively improves the model's ability to identify fine-grained deception attacks and reduces the false positive rate without significantly increasing model complexity.

[0081] The present invention also provides an electronic device, comprising: one or more processors and a memory; wherein the memory is used to store one or more programs, and when the one or more programs are executed by the one or more processors, the one or more processors implement the above-described method for in-vehicle CAN intrusion detection based on image mapping and boundary enhancement.

[0082] The present invention also provides a computer-readable medium having a computer program stored thereon, which, when executed by a processor, implements the above-described method for intrusion detection of vehicle CAN based on image mapping and boundary enhancement.

[0083] Those skilled in the art will understand that all or part of the functions of the various methods / modules in the above embodiments can be implemented by hardware or by computer programs. When all or part of the functions in the above embodiments are implemented by computer programs, the program can be stored in a computer-readable storage medium, which may include: read-only memory, random access memory, disk, optical disk, hard disk, etc., and the above functions can be implemented by executing the program with a computer. For example, the program can be stored in the memory of a device, and when the program in the memory is executed by the processor, all or part of the above functions can be implemented.

[0084] In addition, when all or part of the functions in the above embodiments are implemented by computer programs, the programs can also be stored in storage media such as servers, other computers, disks, optical discs, flash drives, or portable hard drives. They can be downloaded or copied to the memory of the local device, or the system of the local device can be updated. When the program in the memory is executed by the processor, all or part of the functions in the above embodiments can be implemented.

[0085] The above-described specific examples are for illustrative purposes only and are not intended to limit the scope of the invention. Those skilled in the art can make various simple deductions, modifications, or substitutions based on the principles of this invention. Therefore, the scope of protection of this invention should be determined by the scope of the claims.

Claims

1. A method for intrusion detection of vehicle-mounted CAN based on image mapping and boundary enhancement, characterized in that, The method includes the following steps: Step S1. Data preprocessing: First, the raw data is parsed, and basic feature fields are constructed for each CAN message. Then, each type of raw message data is segmented according to time order, and divided into training set, validation set, and test set. Next, the features of the training set are standardized and fitted, and the same parameters are used to transform the validation set and test set. Then, the continuous message sequence is converted into a fixed-length window feature matrix to generate window-level labels. Finally, the window feature matrix is ​​mapped to image samples. Step S2. Construct a lightweight RepVGG-lite image classification network. The lightweight RepVGG-lite image classification network includes three cascaded feature extraction modules, an adaptive average pooling layer, a flattening layer, a shared feature layer, and two parallel main classification branches and boundary enhancement branches. The shared feature layer includes a fully connected layer, a GELU activation layer, and a random deactivation layer arranged sequentially. The main classification branch performs five classifications based on the shared features output by the shared feature layer and calculates the probability distributions of the five classes. The boundary enhancement branch is used to perform boundary enhancement constraints between the normal class and the easily confused Gear class based on the shared features. Step S3. Train the lightweight RepVGG-lite image classification network constructed in Step S2 based on the data obtained in Step S1. The training loss function consists of two parts: main classification loss and boundary enhancement loss. The boundary enhancement loss is constructed based on intra-class compactness and inter-class separability. Step S4. Based on the trained lightweight RepVGG-lite detection model, identify and classify the received CAN traffic data to determine the intrusion detection result.

2. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 1, characterized in that, In step S1, when splitting each type of raw message data according to time order, all data is first divided into a 70% development set and a 30% test set according to time order. Then, the development set is further divided into an 80% training set and a 20% validation set.

3. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 1, characterized in that, In step S1, when converting the continuous message sequence into a fixed-length window feature matrix, the window length is... window_size The sliding step size is stride Then from the length of From the message sequence, the window is extracted as follows: ; Each window contains a continuous window_size Each message is represented by an 8-dimensional feature vector, resulting in the following shape: The window feature matrix is ​​mapped to a fixed-size two-dimensional grayscale image through rearrangement or interpolation.

4. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 1, characterized in that, In step S1, when generating window-level labels, the category labels are defined as: Normal = 0; Dos = 1; Fuzzy = 2; Gear = 3; Rpm = 4. For normal data windows, the label is directly recorded as Normal. For windows generated by attack files, the proportion of injected packets inside the window is first calculated. The expression is: ; Then compare this ratio with the preset threshold min_attack_ratio = 0.

1. If attack_ratio If the value is ≥min_attack_ratio, then the window is marked as the corresponding attack category; if... attack_ratio If the value is less than min_attack_ratio, then the window rollback flag is set to Normal.

5. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 1, characterized in that, In step S2, the three cascaded feature extraction modules are the first feature extraction module, the second feature extraction module, and the third feature extraction module, respectively. The first feature extraction module is used to process the input image sample tensor to extract low-level local texture features. The second feature extraction module is used to process the low-level local texture features to extract mid-level structural features. The third feature extraction module is used to process the mid-level structural features to extract high-level discriminative semantic features and perform global feature compression.

6. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 5, characterized in that, The first feature extraction module includes parallel configurations. Convolutional branches and The convolutional branches are batch normalized after each convolution, and then the outputs of the two branches are added element by element and processed by a non-linear activation function before being output. The first feature extraction module is then connected to the first max pooling layer; The second feature extraction module includes sequentially connected... Pointwise convolutional layer Deep convolutional layers and The output consists of pointwise convolutional layers, each followed by batch normalization, and finally processed by a non-linear activation function. The second feature extraction module is then connected to the second max pooling layer; The third feature extraction module includes sequentially connected... Pointwise convolutional layer Deep convolutional layers and The output consists of pointwise convolutional layers, followed by batch normalization, and finally processed by a non-linear activation function. The third feature extraction module is followed by an adaptive average pooling layer.

7. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 6, characterized in that, The first, second, and third feature extraction modules employ the GELU non-linear activation function. The second feature extraction module combines the first two convolutional layers with the non-linear activation function. The first feature extraction module has 1 input channel and 48 output channels; the second feature extraction module has 48 input channels and 96 output channels; and the third feature extraction module has 96 input channels and 192 output channels. The adaptive average pooling layer is AdaptiveAvgPool2d. The fully connected layer within the shared feature layer is used to map the input features from 192 dimensions to 96 dimensions, and the inactivation rate of the random inactivation layer is 0.

3.

8. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 7, characterized in that, The expression for the training loss function in S3 is: ; in, This represents the primary classification loss for a five-class classification task; This represents the boundary augmentation loss constructed for the normal class and the Gear class; The weights representing the boundary augmentation loss; The main classification loss uses Focal Loss, and its expression is: ; in, This represents the model's predicted probability of the true class. Represents the category weight coefficient. This represents the focusing coefficient.

9. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 8, characterized in that, The boundary enhancement branch extracts sample features belonging to the Normal and Gear classes from the shared features, and constructs the Normal-Gear boundary enhancement loss based on intra-class compactness and inter-class separability, expressed as: ; ; ; Among them, the internal tightening loss is Inter-class separation loss is , Indicates the weight of compact items within the class. Indicates the weight of the separation item between classes. This represents the preset boundary margin, and the normal sample set is... The Gear class sample set is The center of the normal class and the center of the Gear class are respectively and .

10. The intrusion detection method for vehicle CAN based on image mapping and boundary enhancement according to claim 9, characterized in that, After completing the calculation of the training loss function, S3 uses the backpropagation algorithm to solve the gradient of the model parameters and uses the AdamW optimizer to iteratively update the model parameters. During the update, the gradient of each layer parameter is first calculated according to the loss function; then the gradient is adaptively adjusted based on the first and second moments; finally, a weight decay term is introduced during the update process.