Lightweight encrypted traffic identification method based on pulse image coding and timing convolution network

CN123020093APending Publication Date: 2026-10-30NAVAL UNIV OF ENG PLA
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202511658215.7
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-11-13
Publication Date
2026-10-30

AI Technical Summary

Technical Problem

[0011]有鉴于此,本发明的主要目的在于提供基于脉冲图像编码与时序卷积网络的轻量级加密流量识别方法,旨在解决现有加密流量识别方法在模型轻量化、特征表征有效性以及不平衡数据适应能力等方面仍存在明显不足,难以在边缘计算、嵌入式网络设备等资源受限环境下同时实现高效率与高精度的实时识别等问题

Benefits of technology

[0103]1.在特征表征方面,本发明构建了一种鲁棒的时空脉冲图像,极大提升了特征的判别力。具体操作上,将双向网络会话流拆分成两行脉冲序列,用包长度映射像素灰度,直观保留负载规模信息。同时,采用首包时间对齐及对数等比分级策略,把时间增量映射为图像列间距,有效克服了网络抖动和多尺度延时变化的影响,形成了对会话流量行为模式稳定且表达力强的特征表示。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123020093A_ABST
    Figure CN123020093A_ABST
Patent Text Reader

Abstract

The present application relates to the technical field of network security, and in particular to a lightweight encrypted traffic identification method based on pulse image coding and time sequence convolution network. First, the pcap file is subjected to session flow extraction; the arrival time increment is calculated by aligning the first packet time, and the time information is coded by means of logarithmic hierarchical method; the packet length is mapped into gray intensity, the session flow is mapped into two rows of two-dimensional pulse images, and the time interval level is mapped into column spacing to generate a fixed-width pulse graph. For a few long session flow samples of the minority class, multi-segment division is performed to realize class augmentation. The generated pulse graph is input into a classification model, the model adopts a time sequence convolution network (TCN) with a multi-layer dilated convolution structure, and realizes end-to-end prediction in combination with global pooling and a classification head. The present application does not need decryption or deep packet analysis, has the advantages of light structure, sensitivity to multiple time scales, adaptation to embedded deployment, etc., and is suitable for rapid and accurate identification of multiple categories of encrypted traffic.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of network security technology, and specifically relates to a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks. Background Technology

[0002] With the widespread application of encryption protocols such as TLS 1.3 and QUIC, the privacy and integrity of network data transmission have been effectively guaranteed. However, this has also posed a serious challenge to traditional session traffic identification technologies that rely on deep packet inspection (DPI). Against this backdrop, encrypted traffic identification methods based on session traffic statistical characteristics have become a research hotspot. Their core lies in identifying encrypted traffic without parsing the packet payload content, but rather by utilizing metadata generated during communication. Currently, while deep learning-based encrypted traffic identification methods have made some progress, several key technical bottlenecks still exist in practical deployments, restricting their effective application in resource-constrained scenarios. These bottlenecks are mainly manifested in the following aspects:

[0003] (1) The model structure is complex and the computation and storage overhead is large.

[0004] To improve recognition accuracy, existing methods often employ deep learning models with large parameter scales and high computational complexity. For example, methods based on recurrent neural networks (such as LSTM) rely on sequential processing, making parallel computation difficult and resulting in low inference efficiency. While models based on Transformer architectures (such as ET-BERT) possess strong sequence modeling capabilities, the computational complexity of their self-attention mechanism increases quadratically with sequence length, leading to significant resource consumption when processing long session traffic sequences. Furthermore, methods such as graph neural networks (such as GraphDapp) require additional construction of session traffic graph structures, further increasing the preprocessing burden. Although some research has attempted to design lightweight models (such as FS-Net) to reduce computational burden by simplifying network structures, their feature extraction capabilities are often limited, making it difficult to achieve high-accuracy recognition while maintaining lightweight design, thus posing a challenge in balancing accuracy and efficiency. All of the above models are difficult to adapt to embedded devices with limited storage and computing power, such as routers and edge gateways, limiting the feasibility of real-time session traffic analysis.

[0005] (2) Limited feature representation capabilities, key information not fully extracted.

[0006] Existing methods have significant shortcomings in representing session traffic features. Some methods based on convolutional neural networks (CNNs) simply map session traffic sequences into one-dimensional or two-dimensional vectors, often introducing a large number of padding values ​​to standardize the input size, resulting in information redundancy. More importantly, these methods typically fail to effectively distinguish the bidirectional session traffic interaction features between client-to-server (C2S) and server-to-client (S2C) communication, weakening their ability to model the directionality of communication behavior. Furthermore, packet time intervals, as an important feature reflecting application behavior patterns, are mostly treated linearly or used as auxiliary feature inputs in most methods, failing to effectively characterize their multi-scale, nonlinear dynamic patterns (such as burst transmissions and heartbeat cycles). Even efficiency-focused models like FS-Net still have shortcomings in the nonlinear encoding of temporal features and the deep representation of bidirectional session flow interaction patterns, limiting the model's ability to identify complex session traffic patterns.

[0007] (3) Poor adaptability to long-tail categories and insufficient model generalization performance.

[0008] In real-world network environments, session traffic categories are extremely unevenly distributed, with a scarcity of samples representing many rare applications or novel threats, resulting in a typical long-tail distribution. Existing models such as CNNs and LSTMs tend to overfit to the majority class, while performing poorly in identifying the tail classes. Although imbalanced learning has been extensively studied, existing encrypted traffic identification methods (including lightweight models like FS-Net) often lack built-in data augmentation or class balancing mechanisms tailored to the characteristics of session traffic data. This leads to weak generalization ability when dealing with skewed sample distributions, making it difficult to meet the business requirements of high recall rates for minority classes in scenarios such as security monitoring.

[0009] In summary, existing encrypted traffic identification methods (including lightweight models such as FS-Net) still have significant shortcomings in terms of model lightweighting, feature representation effectiveness, and adaptability to imbalanced data, making it difficult to achieve both high efficiency and high accuracy in real-time identification in resource-constrained environments such as edge computing and embedded network devices.

[0010] Based on this, the present invention proposes a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks to solve the problems existing in the prior art. Summary of the Invention

[0011] In view of this, the main objective of this invention is to provide a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks. This method aims to address the significant shortcomings of existing encrypted traffic identification methods in terms of model lightweighting, feature representation effectiveness, and adaptability to imbalanced data. It also addresses the difficulty in achieving both high efficiency and high accuracy in real-time identification under resource-constrained environments such as edge computing and embedded network devices.

[0012] The technical solution of this invention is implemented as follows:

[0013] A lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks includes the following steps:

[0014] Step 1: Extract session streams from the pcap raw session traffic file and generate a packet length sequence with direction symbols and an absolute timestamp sequence for each session stream;

[0015] Step 2: Calculate the cumulative relative time series of each session stream from the first packet, aggregate the simplified session stream data into JSON format by category and persist it;

[0016] Step 3: Initialize a two-dimensional digital canvas with a height of 2 and a width of N, and set the upper bound of the packet length normalization, the background pixel value, and the logarithmic hierarchical encoding parameters of the time interval;

[0017] Step 4: Map the packet length of the session stream to the grayscale value of the canvas pixels;

[0018] Step 5: Map the data packet time interval of the session stream directly to the column gaps of the canvas pixels according to a preset logarithmic order;

[0019] Step 6: Generate a (2,N) grayscale pulse image based on the feature values ​​of each session stream obtained in Step 4 and Step 5, and store it efficiently in NPY format;

[0020] Step 7: Identify the minority class with a small sample size, slice its information-rich long conversation streams into equal-length slices, and independently generate new pulse images to expand the training samples.

[0021] Step 8: Divide the complete dataset into hierarchical segments according to labels and perform normalization on the loaded data;

[0022] Step 9: Build a lightweight TCN model by stacking convolutional blocks with increasing dilation rates to expand the temporal receptive field;

[0023] Step 10: Train the TCN model using a comprehensive strategy that includes imbalance handling;

[0024] Step 11: Use the TCN model to perform inference on the test set and fully evaluate its performance;

[0025] Step 12: Deploy and configure resources for the TCN model.

[0026] In a preferred embodiment of the present invention, step 1, extracting the session stream from the pcap raw session traffic file, includes:

[0027] Step 1.1: Process the encrypted session traffic dataset using a session traffic extraction tool, group the data packets according to the five-tuple in the network protocol, and thus reconstruct the Transmission Control Protocol or User Datagram Protocol session flow;

[0028] Step 1.2: For each reconstructed session stream, extract the packet length sequence and timestamp sequence of the session stream;

[0029] Step 1.3: Use the packet length filtering mechanism to discard session streams with too few packets.

[0030] In a preferred embodiment of the present invention, step 2, which calculates the cumulative relative time series of each session stream from the first packet, and aggregates the simplified session stream data into JSON format by category and persists it, includes:

[0031] Step 2.1: For each session stream's timestamp sequence, perform time relativization processing and calculate the cumulative time increment sequence;

[0032] Step 2.2: After completing the processing in Step 2.1, aggregate all session stream data under each category and store them as a separate JSON file, with the filename corresponding to the category name;

[0033] In the JSON file, each session stream is a separate object, which contains at least two key fields: packet_length and arrival_time_delta.

[0034] In a preferred embodiment of the present invention, step 3, which initializes a two-dimensional digital canvas with a height of 2 and a width of N, and sets the packet length normalization upper bound, background pixel values, and logarithmic hierarchical encoding parameters for time intervals, includes:

[0035] Step 3.1: Set the canvas size;

[0036] Create a two-dimensional digital canvas with a fixed height of 2 pixels and a configurable width of IMAGE_WIDTH. The 0th row is fixed to represent session traffic in the C2S direction, and the 1st row is fixed to represent session traffic in the S2C direction.

[0037] Step 3.2: Normalization and background parameters;

[0038] (1) Let the maximum transmission unit (MTU) be the normalized upper bound for the packet length to grayscale mapping. Any packet larger than the MTU will be considered as the MTU when calculating the grayscale.

[0039] (2) Define the background pixel value as 255. In an 8-bit grayscale space (0-255), 255 represents pure white and is used to fill the area on the canvas where there is no data packet information.

[0040] Step 3.3: Set the logarithmic gradation parameters for the time interval:

[0041] (1) MIN_TIME_INTERVAL: Minimum time interval threshold;

[0042] (2) MAX_TIME_INTERVAL: Maximum time interval threshold

[0043] (3) NUM_TIME_LEVELS: The number of discrete levels of the time interval;

[0044] Based on the above parameters, a geometrically bounded array is pre-calculated at microsecond precision. This array is used to quickly map any time interval to an integer level. Its specific construction method is as follows:

[0045] Level 0 coverage interval [0, MIN), Level NUM_TIME_LEVELS-1 coverage interval [MAX, +∞); other levels are calculated using the following formula:

[0046] r = (MAX / MIN) 1 / (NUM_TIME_LEVELS - 2) ;

[0047] Boundary points at each level are MIN * r k k∈[1,NUM_TIME_LEVELS-2], and finally generate an array containing NUM_TIME_LEVELS + 1 boundary values, which is used for fast table lookup in step 5.

[0048] In a preferred embodiment of the present invention, step 4, mapping the data packet length of the session stream to the grayscale value of the canvas pixel, includes:

[0049] Step 4.1: For a given session stream packet length size, take the absolute value of each packet length in the packet_length sequence from Step 2, limit this absolute value to the range [0, MTU], and calculate its grayscale value using the following linear mapping formula:

[0050] color_value = 254 - (size / MTU) * 254;

[0051] Step 4.2: For each data packet in the session stream, fill the corresponding row at the current column pointer position on the canvas with the grayscale value according to the sign of its original packet_length.

[0052] In a preferred embodiment of the present invention, step 5, which maps the data packet time interval of the session stream directly to the inter-column gap of the canvas pixels according to a preset logarithmic order, includes:

[0053] Step 5.1: Interval calculation;

[0054] For any two consecutive data packets i and i+1 in the session stream, the time interval between them is calculated as follows:

[0055] Δt = arrive_time_delta[i+1] - arrive_time_delta[i];

[0056] Step 5.2: Logarithmic hierarchical search;

[0057] Using the pre-calculated geometric boundary array from step 3, look up Δt in a table to determine its integer level.

[0058] Step 5.3: Direct mapping from level to pixel gap;

[0059] The found integer level is directly used as the pixel gap pixel_gap, i.e., pixel_gap = level;

[0060] Step 5.4: Column pointer update and truncation;

[0061] After a data packet is drawn in step 4, the column pointer used to indicate the next drawing position will move forward by 1 + pixel_gap units. If the updated column pointer position exceeds the canvas width N, all subsequent data packets of this session stream will be discarded, the image generation process will be terminated in advance, and the ultra-long session stream will be truncated.

[0062] In a preferred embodiment of the present invention, step 6, which generates a (2,N) grayscale pulse image based on the feature values ​​of each session stream obtained in steps 4 and 5, and efficiently stores it in NPY format, includes:

[0063] Step 6.1: Image generation and filling;

[0064] For each session stream, the loop process of steps 4 and 5 is executed, eventually generating a numpy array with shape (2, N) and data type uint8; if the encoding process of the session stream ends before the column pointer reaches N, then the remaining unwritten columns on the canvas will automatically retain the background value of 255 initialized in step 3, forming the tail padding of the short session stream.

[0065] Step 6.2: Category Aggregation;

[0066] Stack the (2, N) arrays generated from all session streams under a category in the 0th dimension to form a larger three-dimensional NumPy array;

[0067] Step 6.3: Efficient Storage;

[0068] Save this three-dimensional array as a binary *.npy file, and the final array shape will be (num_flows, 2, N);

[0069] Where num_flows is the total number of session flows in this category, and the *.npy file format supports memory-mapped reading.

[0070] In a preferred embodiment of the present invention, step 8, which involves hierarchically dividing the complete dataset by label and performing normalization processing on the loaded data, includes:

[0071] Step 8.1: Dataset partitioning;

[0072] First, collect all samples of all categories and their corresponding category labels after step 7 is completed;

[0073] Then, the dataset is divided according to a preset ratio;

[0074] In the process of partitioning, a fixed random seed is used. After partitioning, the pulse image data and label data of the three subsets are saved as independent *.npy files. At the same time, a metadata JSON file is generated to record the configuration information of this partitioning.

[0075] Step 8.2: Loading and Normalization;

[0076] During the model training or inference phase, the data loader reads data from the aforementioned *.npy file;

[0077] Before feeding the data into the model, an important preprocessing step is performed:

[0078] Normalization converts the pixel value storage type of the pulse image from uint8 to floating-point numbers and scales it to the [0, 1] interval that the model is more suited to; subsequently, the data is organized into batch form with tensor shape (B, 2, N);

[0079] Where B is the batch size.

[0080] In a preferred embodiment of the present invention, step 9, constructing a lightweight TCN model, involves expanding the temporal receptive field by stacking convolutional blocks with increasing dilation rates.

[0081] Step 9.1: Construct the input layer;

[0082] The model receives an input tensor of shape (B, 2, N), which is first passed through a stem layer; this stem layer consists of a Conv1d convolution, a BatchNorm1d, and a GELU activation function.

[0083] Step 9.2: Construct the main body of the model;

[0084] The main body of the model consists of multiple cascaded BottleneckTCNBlocks, each block following a three-step structure of "expansion-depth convolution-projection":

[0085] Step 9.3: Construct the tail and output;

[0086] After passing through all TCN blocks, the resulting feature map is globally averaged pooled in the time dimension, compressing it from (B, C_final, N) to (B, C_final). Finally, this fixed-length vector is fed into a standard fully connected classification head, which outputs the unactivated raw scores logits, with a dimension of num_classes.

[0087] In a preferred embodiment of the present invention, step 10, which involves training the TCN model using a comprehensive strategy including imbalance handling, includes:

[0088] Step 10.1: Optimizer;

[0089] AdamW optimizer was selected;

[0090] Step 10.2: Learning rate scheduling;

[0091] A dynamic learning rate strategy combining warm-up and cosine annealing is adopted. In the first few epochs of training, the learning rate increases linearly from a very small value to a preset initial learning rate. After the warm-up, the learning rate decays smoothly to a minimum value close to zero following a cosine function curve.

[0092] Step 10.3: Loss Function;

[0093] The standard option is labeled smooth cross-entropy loss; Focal Loss is chosen, which introduces a modulation factor (1-p_t). γ This reduces the contribution of easily classifiable samples to the loss, allowing the model to focus more on learning samples that are difficult to distinguish.

[0094] Here, γ is an adjustable hyperparameter;

[0095] Step 10.4: Handling class imbalance;

[0096] (1) Class weights: When calculating cross-entropy loss, each class is assigned a weight;

[0097] (2) Weighted random sampler: When building the data loader, a sampling weight is assigned to each sample in the training set. The weight is also inversely proportional to the frequency of the class to which the sample belongs.

[0098] Step 10.5: Regularization and stability;

[0099] (1) Dropout is used inside the model block to randomly deactivate neurons to prevent overfitting;

[0100] (2) Gradient clipping is used to limit the norm of the gradient to a threshold after backpropagation and before the optimizer is updated, in order to prevent gradient explosion.

[0101] (3) Early stop: Monitor key performance indicators on the validation set. If the indicator does not improve for several consecutive epochs, terminate training early and save the best performing model so far.

[0102] Compared with existing technologies, this invention provides a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks, which has the following advantages:

[0103] 1. In terms of feature representation, this invention constructs a robust spatiotemporal pulse image, which greatly improves the discriminative power of features. Specifically, the bidirectional network session stream is split into two pulse sequences, and the packet length is used to map pixel grayscale, intuitively preserving load scale information. Simultaneously, a first-packet time alignment and logarithmic proportional grading strategy are adopted to map the time increment to the image column spacing, effectively overcoming the influence of network jitter and multi-scale latency variations, forming a stable and expressive feature representation of session traffic behavior patterns.

[0104] 2. This invention designs a lightweight and high-throughput end-to-end recognition architecture, highly adaptable to resource-constrained environments. This architecture treats pulse images as one-dimensional temporal signals input to a lightweight temporal convolutional network (TCN), utilizing dilated convolutions and the BottleneckTCN module (which integrates 1×1 convolutions, depthwise separable dilated convolutions, and residual connections) to capture long-range dependencies with extremely low parameter counts. Furthermore, by replacing fully connected layers with global average pooling, computational complexity and inference speed are significantly optimized, perfectly suited for high-concurrency edge deployment scenarios.

[0105] 3. To address the prevalent class imbalance problem in real-world networks, this invention introduces a segmented augmentation mechanism for long session streams of a minority class. This mechanism is automatically triggered when a severe class skew is detected, generating multiple pulse images by segmenting the long session stream to augment the tail samples. This mechanism can be used in conjunction with strategies such as Focal Loss to systematically improve the model's ability to identify sparse class samples, effectively improving key metrics such as the macro-average F1 score.

[0106] 4. This method possesses inherent privacy and security, as well as broad protocol generalization capabilities. Its processing relies solely on packet-level metadata, requiring no decryption or deep packet parsing, fundamentally avoiding privacy compliance risks. Furthermore, this protocol-independent characteristic allows it to be seamlessly applied to existing and future encryption environments such as TLS and QUIC, demonstrating excellent forward compatibility.

[0107] 5. Extensive experiments have validated the comprehensive advantages of this invention. Test results on multiple public datasets show that, compared to the baseline model of the main session flow, this invention improves the macro F1 score, especially in tail category recognition. This fully demonstrates that this invention has achieved significant progress in feature design, model lightweighting, and imbalanced learning, providing a precise, efficient, and easy-to-deploy new approach for encrypted traffic identification.

[0108] This addresses the significant shortcomings of existing encrypted traffic identification methods in terms of model lightweighting, feature representation effectiveness, and adaptability to imbalanced data, making it difficult to achieve both high efficiency and high accuracy in real-time identification under resource-constrained environments such as edge computing and embedded network devices. Attached Figure Description

[0109] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.

[0110] Figure 1 This is a session flowchart of the lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks of the present invention.

[0111] Figure 2 This is a schematic diagram of the pulse image encoding of the present invention;

[0112] Figure 3 The figure shows the comparison test results between the method described in this invention and existing methods. Detailed Implementation

[0113] The principle and usage of this lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks will be further explained in detail below with reference to the accompanying drawings and embodiments of the present invention.

[0114] It should be noted that, unless otherwise specified, the embodiments and features described in this application can be combined with each other. The present invention will now be described in detail with reference to the accompanying drawings and embodiments.

[0115] The following is in conjunction with the instruction manual appendix. Figure 1 - Appendix Figure 3 This invention describes the principle and usage of a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks. To address the significant shortcomings of existing encrypted traffic identification methods in areas such as model lightweighting, feature representation effectiveness, and adaptability to imbalanced data, making it difficult to achieve both high efficiency and high accuracy in real-time identification under resource-constrained environments such as edge computing and embedded network devices, this invention proposes a lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks. This method utilizes session traffic metadata to construct a highly discriminative spatiotemporal pulse representation, and then performs efficient modeling through a lightweight TCN network, achieving accurate identification of multiple categories of encrypted traffic. The specific process includes:

[0116] Step 1: Extract session streams from the pcap raw session traffic file and generate a packet length sequence with direction symbols and an absolute timestamp sequence for each session stream;

[0117] This step aims to extract structured session flow information from raw network session traffic data, which can be used for subsequent processing.

[0118] Step 1.1: For the encrypted traffic dataset (pcap file), use a session traffic extraction tool (such as the open-source library flowcontainer) to process it. Group the data packets according to the five-tuple (source IP, destination IP, source port, destination port, protocol type) in the network protocol to reconstruct the Transmission Control Protocol (TCP) or User Datagram Protocol (UDP) session flow.

[0119] Step 1.2: For each reconstructed session stream, extract the following two core sequences;

[0120] (1) Packet length sequence (packet_length). This is a list of signed integers. The sign is used to encode the direction of data packet transmission: the packet length from client to server (C2S) is recorded as a positive number, and the packet length from server to client (S2C) is recorded as a negative number. Its absolute value represents the size of the data packet in bytes.

[0121] (2) Timestamp sequence (packet_timestamps). This is a list of floating-point numbers used to record the absolute timestamp of each packet at the time of collection, usually accurate to the microsecond level.

[0122] Step 1.3: To eliminate noise and ensure the effectiveness of subsequent processing, this step includes a packet length filtering mechanism: This mechanism sets a filtering threshold to discard session flows with too few packets. For example, a filtering threshold of 2 means that any session flow with fewer than 2 packets will be ignored, as at least two packets are required to calculate a valid time interval.

[0123] Step 2: Calculate the cumulative relative time series of each session stream from the first packet, aggregate the simplified session stream data into JSON format by category and persist it;

[0124] This step aims to normalize and simplify the raw session stream information extracted in step 1, generating a compact and self-contained intermediate representation specifically for subsequent pulse image generation.

[0125] Step 2.1: For each session stream's timestamp sequence (packet_timestamps), perform time relativization processing and calculate the cumulative time increment sequence (arrive_time_delta).

[0126] The arrival_time_delta[0] of the first data packet is set to 0.0. For the subsequent i-th packet:

[0127] arrive_time_delta[i]= packet_timestamps[i] - packet_timestamps[0];

[0128] This operation normalizes the start time of all session streams to the same starting point, allowing the model to focus on the temporal patterns within the session streams rather than their absolute occurrence times.

[0129] Step 2.2: After completing the processing in Step 2.1, aggregate all session stream data under each category and store them as a separate JSON file, with the filename corresponding to the category name. In this JSON file, each session stream is represented as an independent object, which contains at least two key fields:

[0130] (1) packet_length: The length of the tagged packet generated in step 1.

[0131] (2)arrive_time_delta: The cumulative time increment sequence calculated in step 2.1.

[0132] This step is designed to decouple the raw parsing of session traffic from feature encoding, and the generated JSON file serves as a standardized input, providing data support for all subsequent steps.

[0133] Step 3: Initialize a two-dimensional digital canvas with a height of 2 and a width of N, and set the upper bound of the packet length normalization, the background pixel value, and the logarithmic hierarchical encoding parameters of the time interval;

[0134] This step prepares the session stream sequence for conversion into a pulse image, defining the canvas used for encoding and all relevant parameters.

[0135] Step 3.1: Canvas Size Setting. Create a two-dimensional digital canvas with a fixed height of 2 pixels and a width of a configurable parameter IMAGE_WIDTH, such as 300 or 1000 pixels. The design of a height of 2 is one of the core features of this invention, where row 0 is fixed to represent session traffic in the C2S direction, and row 1 is fixed to represent session traffic in the S2C direction.

[0136] Step 3.2: Normalization and background parameters.

[0137] (1) Set the maximum transmission unit (MTU), for example, 1500 bytes, as the normalized upper bound for packet length to grayscale mapping. Any packet larger than the MTU will be considered as part of the MTU when calculating grayscale.

[0138] (2) Define the background pixel value as 255. In an 8-bit grayscale space (0-255), 255 represents pure white, which is used to fill the area on the canvas where there is no data packet information.

[0139] Step 3.3: Set the logarithmic time interval parameters. To achieve effective discretization of the time interval, set the following three parameters:

[0140] (1) MIN_TIME_INTERVAL: Minimum time interval threshold, for example, 10 -6 Second.

[0141] (2)MAX_TIME_INTERVAL: Maximum time interval threshold, for example, 1.0 seconds.

[0142] (3) NUM_TIME_LEVELS: The number of discrete levels of the time interval, for example, 20.

[0143] Based on the above parameters, a geometrically bounded array is pre-calculated at microsecond precision. This array is used to quickly map any time interval to an integer level. The specific construction method is as follows:

[0144] Level 0 coverage interval [0, MIN), Level NUM_TIME_LEVELS-1 coverage interval [MAX, +∞). Other levels are calculated using the following formula:

[0145] r = (MAX / MIN) 1 / (NUM_TIME_LEVELS - 2) ;

[0146] Boundary points at each level are MIN * r k k∈[1,NUM_TIME_LEVELS-2], and finally an array containing NUM_TIME_LEVELS + 1 boundary values ​​is generated, which is used for fast table lookup in step 5.

[0147] Step 4: Map the packet length of the session stream to the grayscale value of the canvas pixels;

[0148] This step defines how to encode the size information of session stream packets into visible features (grayscale) on an image.

[0149] Step 4.1: For a given session stream packet length size, its grayscale value is:

[0150] color_value = 254 - (size / MTU) * 254;

[0151] This formula implements a reverse mapping: small packets of 0 bytes are mapped to 254 (light gray, close to white), while large packets that reach or exceed the MTU are mapped to 0 (pure black). This design makes larger data packets stand out more visually. The grayscale dynamic range is [0, 254], distinguishable from the background value of 255.

[0152] The detailed session flow is as follows:

[0153] (1) Take the absolute value of the length of each packet in the packet_length sequence in step 2.

[0154] (2) Limit the absolute value to the range of [0, MTU].

[0155] (3) Apply the above linear mapping formula to calculate its gray value.

[0156] Step 4.2: For each packet in the session stream, fill the grayscale value at the current column pointer position and the corresponding row (>0 in row 0, <0 in row 1) according to the sign of its original packet_length.

[0157] Step 5: Map the data packet time intervals of the session stream directly to the column gaps of canvas pixels according to a preset logarithmic order;

[0158] This step is another core innovation of the present invention, defining how to encode the temporal dynamic characteristics of a session stream into spatial features on an image.

[0159] Step 5.1: Interval Calculation. For any two consecutive data packets (the i-th and i+1-th) in the session stream, calculate the time interval between them as follows:

[0160] Δt = arrive_time_delta[i+1] - arrive_time_delta[i];

[0161] Step 5.2: Logarithmic hierarchical lookup. Using the pre-calculated geometric boundary array from Step 3, look up Δt in the table to determine its integer level.

[0162] If Δt is less than MIN_TIME_INTERVAL, then level is 0;

[0163] If Δt is greater than or equal to MAX_TIME_INTERVAL, then the level is NUM_TIME_LEVELS – 1;

[0164] Otherwise, find the level in the boundary array such that:

[0165] boundary[level] ≤ Δt < boundary[level+1];

[0166] Step 5.3: Direct mapping from level to pixel gap. The found integer level is directly used as the pixel gap, i.e., pixel_gap = level.

[0167] This means that a time interval of level 0 corresponds to a gap of 0 pixels (i.e., the next packet is drawn immediately after the current packet), while a time interval of level 10 corresponds to a gap of 10 pixels.

[0168] Step 5.4: Column Pointer Update and Truncation. After drawing a data packet (occupying 1 column of pixels) in Step 4, the column pointer used to indicate the next drawing position will move forward by 1 + pixel_gap units. If the updated column pointer position exceeds the canvas width N, all subsequent data packets of this session stream will be discarded, the image generation process will terminate prematurely, and thus the truncation of excessively long session streams will be naturally achieved.

[0169] Step 6: Generate a (2,N) grayscale pulse image based on the feature values ​​of each session stream obtained in Step 4 and Step 5, and store it efficiently in NPY format;

[0170] This step completes the conversion of a single session stream into images and aggregates and efficiently stores all images of the same category.

[0171] Step 6.1: Image Generation and Filling. For each session stream, the iterative process of steps 4 and 5 is executed, ultimately generating a NumPy array of shape (2, N) with data type uint8. If the encoding process of a session stream ends before the column pointer reaches N (i.e., the session stream itself is short), then the remaining unwritten columns on the canvas will automatically retain the background value of 255 initialized in step 3, which constitutes the tail padding for short session streams.

[0172] Step 6.2: Category Aggregation. Stack the (2, N) arrays generated by all session streams under a category in the 0th dimension to form a larger three-dimensional NumPy array.

[0173] Step 6.3: Efficient Storage. Save this 3D array as a binary *.npy file. The final array shape is (num_flows, 2, N), where num_flows is the total number of session flows for this category. The *.npy format supports memory-mapped reading, which can improve data loading efficiency during model training.

[0174] Step 6.4: Visual Verification (Optional). To facilitate debugging and intuitive understanding of the encoding effect, the system can selectively save each (2, N) pulse image as a separate PNG image. By observing the PNG image, it can be verified whether the packet length, direction, and time interval have been correctly converted to grayscale, row position, and column spacing.

[0175] Step 7: Identify the minority class with a small sample size, slice its information-rich long conversation streams into equal-length slices, and independently generate new pulse images to expand the training samples.

[0176] This step aims to alleviate class imbalance caused by data collection through data augmentation, especially for the "minority class" with extremely small sample sizes. The core idea of ​​this augmentation method is to utilize the information-rich "long conversation streams" within the minority class.

[0177] Step 7.1: Minority Class Identification. First, the system counts the number of pulse images generated for each class in Step 6. Then, it calculates the ratio between the number of samples in each class and the number of samples in the largest class in the dataset. If this ratio exceeds a preset "imbalance threshold" (in one embodiment of the invention, this threshold is set to 20:1), the class is marked as "minority class," and subsequent augmentation operations are triggered.

[0178] Step 7.2: "Long Session Stream" Potential Assessment. For each category labeled as a minority class, the system iterates through each session stream within it. For each session stream, an untruncated pulse image generation process is simulated to calculate the maximum pixel width max_width that the session stream can generate without considering the canvas width N constraint. This max_width reflects the potential for the "length" or information content of the session stream.

[0179] Step 7.3: Determine the number of slices. Based on the calculated max_width and the preset canvas width N, determine how many independent pulse image segments the session stream can be divided into. The formula for calculating the number of slices num_segments is:

[0180] num_segments = max(1, floor(max_width / N));

[0181] Here, `floor` is the floor function. This means that slicing will only occur when the width of the session stream exceeds N. To prevent over-enhancement, an expansion limit can be set; for example, a single session stream can be sliced ​​into a maximum of 100 segments.

[0182] Step 7.4: Slicing and Independent Generation. For the session stream that needs slicing, its original packet_length and arrive_time_delta sequences are divided into num_segments according to the principle of equal length (each segment corresponds to a data packet contained in N pixels of width). For each data segment, its relative time increment is reset, that is, the arrive_time_delta of subsequent packets is recalculated with the timestamp of the first data packet of the segment as the new starting point. Then, for each processed data segment, the pulse image generation session flow of steps 4 to 6 is executed independently to generate additional training samples for this minority class. These newly generated enhanced images are merged with the original images of this class and stored together in the final *.npy file.

[0183] Step 8: Divide the complete dataset into hierarchical segments according to labels and perform normalization on the loaded data;

[0184] This step is responsible for organizing all the pulse images generated in step 6 or step 7 into a standard machine learning dataset format and preparing them for model training.

[0185] Step 8.1: Dataset Splitting. First, collect all samples and their corresponding class labels for all categories after processing in Step 7. Then, split the dataset according to a preset ratio (e.g., 80% training set, 10% validation set, and 10% test set). To ensure the reproducibility of the experiment, a fixed random seed is used for the splitting process. After the split, save the pulse image data and label data of the three subsets as separate *.npy files, and generate a metadata JSON file to record the configuration information of this split for future reference and use.

[0186] Step 8.2: Loading and Normalization. During model training or inference, a data loader (such as PyTorch's DataLoader) reads data from the aforementioned *.npy files. Before feeding the data into the model, an important preprocessing step is performed: normalization. Since the pixel values ​​of the pulse images are stored as uint8 types (range 0-255), they need to be converted to floating-point numbers and scaled to the [0, 1] interval that the model is more suited to. This is done by dividing each pixel value by 255.0. Subsequently, the data is organized into batches with tensor shapes of (B, 2, N);

[0187] Where B is the batch size.

[0188] Step 9: Build a lightweight TCN model by stacking convolutional blocks with increasing dilation rates to expand the temporal receptive field;

[0189] This step describes the core neural network architecture used to recognize pulse images—a lightweight temporal convolutional network (TCN) optimized for one-dimensional temporal data.

[0190] Step 9.1: Construct the input layer. The model receives an input tensor of shape (B, 2, N). The input first passes through a stem layer, which consists of a Conv1d convolution, a BatchNorm1d (batch normalization), and a GELU activation function. The stem layer's role is to initially extract low-level features and expand the input channels to dimensions more suitable for deep network processing.

[0191] Step 9.2: Constructing the main body of the model. The main body of the model consists of multiple cascaded BottleneckTCNBlocks. This is key to the lightweight and efficient nature of the model in this invention. Each block follows a three-step structure of "expansion-depthmolecular convolution-projection":

[0192] (1) Expansion: A 1x1 convolution expands the number of input channels from C_in to C_in * expand_ratio, where expand_ratio is usually 4.

[0193] (2) Depthwise dilatable temporal convolution: A depthwise separable convolution operates on the time dimension to capture temporal relationships. This convolution is dilatable, and by setting different dilation values, it can exponentially expand the receptive field without increasing the number of parameters.

[0194] (3) Projection: Another 1x1 convolution projects the number of channels back to C_out from the expanded dimension.

[0195] The entire block contains batch normalization, activation functions, and Dropout. When C_in == C_out, a residual connection is introduced, which directly adds the block's input to its output to facilitate gradient flow and stabilize training.

[0196] When multiple BottleneckTCNBlocks are concatenated, their dilation values ​​increase in powers of 2, for example, [1, 2, 4, 8, 16, 32]. This design allows the model's effective receptive field to quickly cover most or even all of the input sequence length N.

[0197] Step 9.3: Constructing the Tail and Output. After passing through all TCN blocks, the resulting feature map undergoes global average pooling in the time dimension, compressing it from (B, C_final, N) to (B, C_final). Finally, this fixed-length vector is fed into a standard fully connected classification head, outputting the unactivated raw scores logits, with a dimension of num_classes.

[0198] Step 9.4: Optional Model Enhancements. To handle more complex datasets or pursue higher performance, an enhanced version of TCN can be adopted. Enhancements include: using a larger inflation rate cap (e.g., 512) to cover longer sequences; increasing network depth and the number of channels (e.g., 384); introducing a channel attention module (e.g., a simple MLP consisting of 1x1 convolutions followed by a sigmoid function) before global pooling, allowing the model to adaptively learn the importance of different feature channels.

[0199] Step 10: Train the TCN model using a comprehensive strategy that includes imbalance handling;

[0200] This step details how to efficiently and stably train the TCN model built in this step.

[0201] Step 10.1: Optimizer. The AdamW optimizer is selected. Unlike the standard Adam, AdamW decouples weight decay from gradient updates, typically resulting in better generalization performance. In one embodiment of this invention, the model parameters are grouped: for non-one-dimensional parameters such as the weight matrix, a set weight_decay is applied; while for bias and batch normalization layer parameters, weight decay is disabled.

[0202] Step 10.2: Learning Rate Scheduling. A dynamic learning rate strategy combining warmup and cosine annealing is employed. During the first few epochs of training (e.g., 10), the learning rate linearly increases from a very small value to a preset initial learning rate. After warmup, the learning rate smoothly decays to a near-zero minimum following a cosine function curve. This strategy helps stabilize the model in the early stages of training and allows for fine-tuning later.

[0203] Step 10.3: Loss Function. The standard option is cross-entropy loss with label smoothing. Label smoothing is an effective regularization technique that prevents the model from becoming overconfident by slightly "softening" the hard labels (one-hot).

[0204] To address class imbalance, Focal Loss can be used. Focal Loss introduces a modulation factor (1-p_t). γ This reduces the contribution of easily classifiable samples to the loss, allowing the model to focus more on learning samples that are difficult to distinguish. Here, γ is an adjustable hyperparameter, for example, between 2 and 4.

[0205] Step 10.4: Handling class imbalance (training level);

[0206] (1) Class weights: When calculating the cross-entropy loss, each class is assigned a weight. The weights are inversely proportional to the class frequency, or can be calculated using the balanced mode provided by the scikit-learn library.

[0207] (2) Weighted Random Sampler: When building the data loader, a sampling weight can be assigned to each sample in the training set. The weight is inversely proportional to the frequency of the class to which the sample belongs. In this way, samples from the minority class will have a higher probability of being selected in each training batch.

[0208] Step 10.5: Regularization and stability;

[0209] (1) Dropout is used inside the model block to randomly deactivate neurons to prevent overfitting.

[0210] (2) Gradient clipping is used to limit the norm of the gradient to a threshold (such as 0.5) after backpropagation and before the optimizer is updated, in order to prevent gradient explosion, especially in the early stage of training.

[0211] (3) Early Stopping: Monitor key performance metrics on the validation set, such as the Macro-F1 score. If the metric does not improve for several consecutive epochs, terminate training early and save the best performing model to date.

[0212] Step 11: Use the TCN model to perform inference on the test set and fully evaluate its performance;

[0213] This step describes how to use the trained model to make predictions and comprehensively evaluate its performance.

[0214] Step 11.1: Inference Process. For a new encrypted traffic to be classified, first execute the complete session flow from steps 1 to 6, converting it into a (2, N) pulse image. Then, perform the normalization operation in step 8, constructing a (1, 2, N) batch input. Feed this input into the TCN model loaded with the optimal weights, obtaining a logits vector of length num_classes. Finally, obtain the final predicted class by taking the index of the element with the largest value in this vector.

[0215] Step 11.2: Performance Evaluation. Perform a comprehensive evaluation on the test set, calculate and report the following metrics:

[0216] (1) Average loss: The average loss value of the model on the test set.

[0217] (2) Top-k accuracy: In particular, Top-1 (standard accuracy) and Top-3 accuracy, the latter measuring the proportion of the true class appearing in the top 3 classes with the highest predicted probability by the model, is of reference value for multi-class classification tasks.

[0218] (3) Macro-F1 score: The arithmetic mean of the F1 scores for each class is calculated without considering the class sample size. It is the core indicator for measuring the overall performance of the model on an imbalanced dataset.

[0219] (4) Confusion matrix: A matrix of num_classes x num_classes that visually shows the distribution of the model’s predictions for each class, which helps to identify which classes are easily confused.

[0220] (5) Class-by-class metrics report: Provides precision, recall and F1 score for each class, which facilitates in-depth analysis of the model’s strengths and weaknesses in specific classes, especially the performance of the head and tail classes.

[0221] Step 12: Deploy and configure resources for the TCN model;

[0222] This step focuses on the practical application and flexibility of the method of the present invention.

[0223] (1) Resource configurability: The computation and memory usage of this method are adjustable. By adjusting the width N of the pulse image (e.g., selected between 200 and 1000) and the base_ch and depth of the TCN model (e.g., selected between 32 and 128), a balance can be achieved between different performance and resource consumption. This allows the method to be deployed on powerful cloud servers as well as on resource-constrained edge computing devices or terminals.

[0224] (2) Deployment advantages:

[0225] Privacy-friendly. The entire identification process does not require decrypting the session traffic payload, but only relies on the metadata of the data packets (length, time, and direction), which naturally meets the requirements of privacy protection.

[0226] Low computational overhead. Compared to models that require Fourier transforms to generate spectrograms or use complex 2D-CNN / Transformer models, the one-dimensional TCN model of this invention has fewer parameters and is more computationally efficient.

[0227] The end-to-end session flow is streamlined. In the deployment environment, only two core modules, "pulse coding + 1D convolutional inference," need to be implemented. The session flow is clear and easy to implement and maintain in an engineering manner.

[0228] Example 1:

[0229] To demonstrate the effectiveness of the lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks described above, this embodiment is designed for verification:

[0230] Without decrypting the payload, the orientation and temporal structure are compactly encoded using "2×N pulse images" and combined with a lightweight one-dimensional TCN (dilated convolution to expand the receptive field) to achieve high-accuracy and low-computational-cost encrypted traffic identification, which is suitable for real-time deployment at the edge / terminal.

[0231] On large-scale multi-class classification tasks (CSTNET-TLS 1.3, 120 classes), the method described in this invention achieves Acc = 0.9447 and F1 = 0.9306, which are approximately +0.37 and +0.20 percentage points higher than the ET-BERT(flow) model (Acc = 0.9410, F1 = 0.9286), respectively. Although the results are similar, the running time is significantly reduced.

[0232] On a small-scale imbalanced task (ISCX-nonTor, 8 classes), the method described in this invention achieves Acc = 0.9603 and F1 = 0.9016. The Macro-F1 score is approximately +6.54 percentage points higher than the second-best method ET-BERT(flow) (F1 = 0.8365), demonstrating robustness to class imbalance. The Acc score is also better than FS-Net (0.95788), with an improvement of approximately +0.24 percentage points.

[0233] The above results show that the method of the present invention can complete the encoding and recognition by relying only on the message timing and length metadata, which reduces the high overhead of feature engineering and 2D convolution / Transformer, and has comprehensive advantages such as privacy friendliness, low resource consumption and convenient deployment.

[0234] The above-described embodiments are merely illustrative of several implementations of the present invention, and while the descriptions are specific and detailed, they should not be construed as limiting the scope of the invention. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of the present invention, and these modifications and improvements all fall within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the appended claims.

Claims

1. A lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks, characterized in that, Including the following steps: Step 1: Extract session streams from the pcap raw session traffic file and generate a packet length sequence with direction symbols and an absolute timestamp sequence for each session stream; Step 2: Calculate the cumulative relative time series of each session stream from the first packet, aggregate the simplified session stream data into JSON format by category and persist it; Step 3: Initialize a two-dimensional digital canvas with a height of 2 and a width of N, and set the upper bound of the packet length normalization, the background pixel value, and the logarithmic hierarchical encoding parameters of the time interval; Step 4: Map the packet length of the session stream to the grayscale value of the canvas pixels; Step 5: Map the data packet time interval of the session stream directly to the column gaps of the canvas pixels according to a preset logarithmic order; Step 6: Generate a (2,N) grayscale pulse image based on the feature values ​​of each session stream obtained in Step 4 and Step 5, and store it efficiently in NPY format; Step 7: Identify the minority class with a small sample size, slice its information-rich long conversation streams into equal-length slices, and independently generate new pulse images to expand the training samples. Step 8: Divide the complete dataset into hierarchical segments according to labels and perform normalization on the loaded data; Step 9: Build a lightweight TCN model by stacking convolutional blocks with increasing dilation rates to expand the temporal receptive field; Step 10: Train the TCN model using a comprehensive strategy that includes imbalance handling; Step 11: Use the TCN model to perform inference on the test set and fully evaluate its performance; Step 12: Deploy and configure resources for the TCN model.

2. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 1, the process of extracting the session stream from the pcap raw session traffic file, includes: Step 1.1: Process the encrypted traffic dataset using a session traffic extraction tool, group the data packets according to the five-tuple in the network protocol, and thus reconstruct the Transmission Control Protocol or User Datagram Protocol session flow; Step 1.2: For each reconstructed session stream, extract the packet length sequence and timestamp sequence of the session stream; Step 1.3: Use the packet length filtering mechanism to discard session streams with too few packets.

3. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 2 calculates the cumulative relative time series of each session stream from the first packet, and aggregates the simplified session stream data into JSON format by category and persists it. The process includes: Step 2.1: For each session stream's timestamp sequence, perform time relativization processing and calculate the cumulative time increment sequence; Step 2.2: After completing the processing in Step 2.1, aggregate all session stream data under each category and store them as a separate JSON file, with the filename corresponding to the category name; In the JSON file, each session stream is a separate object, which contains at least two key fields: packet_length and arrival_time_delta.

4. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 3 involves initializing a two-dimensional digital canvas with a height of 2 and a width of N, and setting the upper bound of the packet length normalization, the background pixel values, and the logarithmic hierarchical encoding parameters for the time interval. Step 3.1: Set the canvas size; Create a two-dimensional digital canvas with a fixed height of 2 pixels and a configurable width of IMAGE_WIDTH. The 0th row is fixed to represent session traffic in the C2S direction, and the 1st row is fixed to represent session traffic in the S2C direction. Step 3.2: Normalization and background parameters; (1) Let the maximum transmission unit (MTU) be the normalized upper bound for the packet length to grayscale mapping. Any packet larger than the MTU will be considered as the MTU when calculating the grayscale. (2) Define the background pixel value as 255. In an 8-bit grayscale space (0-255), 255 represents pure white and is used to fill the area on the canvas where there is no data packet information. Step 3.3: Set the logarithmic gradation parameters for the time interval: (1) MIN_TIME_INTERVAL: Minimum time interval threshold; (2) MAX_TIME_INTERVAL: Maximum time interval threshold (3) NUM_TIME_LEVELS: The number of discrete levels of the time interval; Based on the above parameters, a geometrically bounded array is pre-calculated at microsecond precision. This array is used to quickly map any time interval to an integer level. Its specific construction method is as follows: Level 0 coverage interval [0, MIN), Level NUM_TIME_LEVELS-1 coverage interval [MAX, +∞); other levels are calculated using the following formula: r = (MAX / MIN) 1 / (NUM_TIME_LEVELS - 2) ; Boundary points at each level are MIN * r k k∈[1,NUM_TIME_LEVELS-2], and finally generate an array containing NUM_TIME_LEVELS+1 boundary values, which is used for fast table lookup in step 5.

5. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 4, mapping the packet length of the session stream to grayscale values ​​of canvas pixels, includes: Step 4.1: For a given session stream packet length size, take the absolute value of each packet length in the packet_length sequence from Step 2, limit this absolute value to the range [0, MTU], and calculate its grayscale value using the following linear mapping formula: color_value = 254 - (size / MTU) * 254; Step 4.2: For each data packet in the session stream, fill the corresponding row at the current column pointer position on the canvas with the grayscale value according to the sign of its original packet_length.

6. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 5, which maps the data packet time intervals of the session stream directly to the inter-column gaps of canvas pixels according to a preset logarithmic order, includes: Step 5.1: Interval calculation; For any two consecutive data packets i and i+1 in the session stream, the time interval between them is calculated as follows: Δt = arrive_time_delta[i+1] - arrive_time_delta[i]; Step 5.2: Logarithmic hierarchical search; Using the pre-calculated geometric boundary array from step 3, look up Δt in a table to determine its integer level. Step 5.3: Direct mapping from level to pixel gap; The found integer level is directly used as the pixel gap pixel_gap, i.e., pixel_gap = level; Step 5.4: Column pointer update and truncation; After a data packet is drawn in step 4, the column pointer used to indicate the next drawing position will move forward by 1 + pixel_gap units. If the updated column pointer position exceeds the canvas width N, all subsequent data packets of this session stream will be discarded, the image generation process will be terminated in advance, and the ultra-long session stream will be truncated.

7. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 6, which generates a (2,N) grayscale pulse image based on the feature values ​​of each session stream obtained in steps 4 and 5 and efficiently stores it in NPY format, includes the following steps: Step 6.1: Image generation and filling; For each session stream, the loop process of steps 4 and 5 is executed, eventually generating a numpy array with shape (2, N) and data type uint8; if the encoding process of the session stream ends before the column pointer reaches N, then the remaining unwritten columns on the canvas will automatically retain the background value of 255 initialized in step 3, forming the tail padding of the short session stream. Step 6.2: Category Aggregation; Stack the (2, N) arrays generated from all session streams under a category in the 0th dimension to form a larger three-dimensional NumPy array; Step 6.3: Efficient Storage; Save this three-dimensional array as a binary *.npy file, and the final array shape will be (num_flows, 2, N); Where num_flows is the total number of session flows in this category, and the *.npy file format supports memory-mapped reading.

8. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 8 involves stratifying the complete dataset by label and performing normalization on the loaded data, which includes: Step 8.1: Dataset partitioning; First, collect all samples of all categories and their corresponding category labels after step 7 is completed; Then, the dataset is divided according to a preset ratio; In the process of partitioning, a fixed random seed is used. After partitioning, the pulse image data and label data of the three subsets are saved as independent *.npy files. At the same time, a metadata JSON file is generated to record the configuration information of this partitioning. Step 8.2: Loading and Normalization; During the model training or inference phase, the data loader reads data from the aforementioned *.npy file; Before feeding the data into the model, an important preprocessing step is performed: Normalization converts the pixel value storage type of the pulse image from uint8 to floating-point numbers and scales it to the [0, 1] interval that the model is more suited to; subsequently, the data is organized into batch form with tensor shape (B, 2, N); Where B is the batch size.

9. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 9, constructing a lightweight TCN model, involves expanding the temporal receptive field by stacking convolutional blocks with increasing dilation rates. Step 9.1: Construct the input layer; The model receives an input tensor of shape (B, 2, N), which is first passed through a stem layer; this stem layer consists of a Conv1d convolution, a BatchNorm1d, and a GELU activation function. Step 9.2: Construct the main body of the model; The main body of the model consists of multiple cascaded BottleneckTCNBlocks, and each block follows a three-step structure of "expansion-depth convolution-projection": Step 9.3: Construct the tail and output; After passing through all TCN blocks, the resulting feature map is globally averaged pooled in the time dimension, compressing it from (B, C_final, N) to (B, C_final). Finally, this fixed-length vector is fed into a standard fully connected classification head, which outputs the unactivated raw scores logits, with a dimension of num_classes.

10. The lightweight encrypted traffic identification method based on pulse image coding and temporal convolutional networks as described in claim 1, characterized in that, Step 10 involves training the TCN model using a comprehensive strategy that includes imbalance handling. Step 10.1: Optimizer; AdamW optimizer was selected; Step 10.2: Learning rate scheduling; A dynamic learning rate strategy combining warm-up and cosine annealing is adopted. In the first few epochs of training, the learning rate increases linearly from a very small value to a preset initial learning rate. After the warm-up, the learning rate decays smoothly to a minimum value close to zero following a cosine function curve. Step 10.3: Loss Function; The standard option is labeled smooth cross-entropy loss; Focal Loss is chosen, which introduces a modulation factor (1-p_t). γ This reduces the contribution of easily classifiable samples to the loss, allowing the model to focus more on learning samples that are difficult to distinguish. Here, γ is an adjustable hyperparameter; Step 10.4: Handling class imbalance; (1) Class weights: When calculating cross-entropy loss, each class is assigned a weight; (2) Weighted random sampler: When building the data loader, a sampling weight is assigned to each sample in the training set. The weight is also inversely proportional to the frequency of the class to which the sample belongs. Step 10.5: Regularization and stability; (1) Dropout is used inside the model block to randomly deactivate neurons to prevent overfitting; (2) Gradient clipping is used to limit the norm of the gradient to a threshold after backpropagation and before the optimizer is updated, in order to prevent gradient explosion. (3) Early stop: Monitor key performance indicators on the validation set. If the indicator does not improve for several consecutive epochs, terminate training early and save the best performing model so far.