Leukocyte classification method based on improved YOLOv7
By improving the YOLOv7 model, combined with the GhostV2 module and the attention mechanism, the problem of slow detection speed and low accuracy in white blood cell classification is solved, efficient classification of white blood cells of different scales and shapes is achieved, and classification accuracy and diagnostic support are improved.
Patent Information
- Application Number
- CN202410452341.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-04-16
- Publication Date
- 2024-08-23
AI Technical Summary
The existing technology has the problems of slow detection speed, low accuracy and poor generalization ability in white blood cell classification. It is especially difficult to process white blood cell images of different scales and shapes.
The improved YOLOv7 model is used to process the white blood cell data set through data enhancement and noise reduction, combined with the GhostV2 module and SimAM and MHSA attention mechanisms, to replace the original convolution kernel, and introduce the Focal Loss loss function to improve the model's feature extraction capabilities and Classification accuracy of indistinguishable samples.
It significantly improves the accuracy and efficiency of white blood cell classification, enhances the model's ability to identify white blood cells of different scales and shapes, solves the problem of class imbalance, and provides more objective and effective diagnostic support.
Smart Images

Figure HDA0004793050870000012 
Figure HDA0004793050870000011 
Figure HDA0004793050870000022
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of medical microscopic image classification, and in particular to a leukocyte classification method based on improved YOLOv7. Background Art
[0002] White blood cells are an important component of blood and are also the main immune cells of the human body. They play a pivotal role in maintaining immunity and phagocytizing pathogens and bacteria. Therefore, accurate identification of different types of white blood cells is of great significance for auxiliary diagnosis of corresponding diseases. Correct classification of white blood cells is also a key step in the automatic analysis of cell images.
[0003] However, there are still some problems with the current classification and recognition technology for white blood cells. Traditional image processing methods often require manual design of features and rules, and it is difficult to accurately classify white blood cells of different scales and shapes. At the same time, traditional deep learning models often have problems with slow detection speed, low accuracy and poor generalization ability in white blood cell classification tasks. Therefore, it is necessary to develop a new white blood cell classification technology to improve the accuracy and efficiency of classification.
[0004] YOLOv7 is a deep learning model for object detection, which has many advantages over other networks. First, YOLOv7 has faster detection speed and higher accuracy. It uses a new detection method, which can greatly improve the detection speed without losing accuracy, which is of great significance for large-scale white blood cell classification. Secondly, YOLOv7 has better generalization ability and can adapt to white blood cells of different scales and shapes, thereby improving the accuracy and robustness of classification. In addition, YOLOv7 also has better scalability and flexibility, and can be easily applied to different white blood cell classification tasks.
[0005] Based on the above background technology, we proposed a patented technology for white blood cell classification based on YOLOv7. This technology uses the fast detection and high accuracy of YOLOv7, combined with the advantages of deep learning, to achieve fast and accurate classification of white blood cells of different scales and shapes. At the same time, this technology also has good generalization ability and flexibility, and can adapt to different white blood cell classification tasks. Through this technology, the accuracy and efficiency of white blood cell classification can be effectively improved, providing better support for clinical diagnosis and treatment. Summary of the invention
[0006] 1. Technical issues to be resolved
[0007] In view of the shortcomings of the prior art, the present invention provides a white blood cell classification method based on an improved YOLOv7, which solves the problems of complex background, unbalanced data, and large similarity between classes of white blood cell images, reduces the number of parameters of the YOLOv7 network model, and improves the classification accuracy, which will provide objective and effective reference opinions in medical pathology diagnosis.
[0008] (II) Technical solution
[0009] In order to achieve the above-mentioned purpose, the present invention specifically adopts the following technical solutions:
[0010] A white blood cell classification method based on improved YOLOv7, comprising the following steps:
[0011] S1. Collect multiple public white blood cell datasets and perform data enhancement and denoising operations on the datasets. Data enhancement uses rotation of 90°, 180°, 270° and flipping methods to increase the number of white blood cell images in the dataset to five times the original number. Noise reduction uses a combination of nonlinear filtering methods, median filtering and bilateral filtering, which can better protect image edge information while suppressing image noise.
[0012] S2. Annotate the white blood cell image obtained in step S2 using the VOC format and the Labelimg tool.
[0013] S3. Randomly divide the labeled data set into training set, test set and validation set according to the proportion, and create three folders train, test and val to place them respectively in preparation for subsequent network training and prediction.
[0014] S4. Build the basic model of YOLOv7 network structure to improve the YOLOv7 network structure.
[0015] S5. Set specific parameters of the improved YOLOv7 network structure, input image size img_size = 640 × 640, training batch size batch_size = 4, training iteration number Epoch = 100, learning rate lr = 0.0001, decay decay = 0.00001, label smoothing label-smoothing = 0.1, and use adam optimizer as optimizer. Put the improved YOLOv7 network structure with set parameters into a computer with a configured environment and use it to train the white blood cell images in the train folder generated in step S3.
[0016] S6. During training, as the number of iterations increases, the training loss and test loss slowly converge to a stable value, the difference between the two does not change, and the accuracy tends to be stable, indicating that the expected training effect has been achieved. At the same time, the classification results of the test set will also be saved in the form of pictures in the run folder. The folder is divided into two folders, train and test. After the network training is completed, the training results and weights will be output under the train folder. At this time, we select the optimal weight in the training process to test the test set to obtain the optimal test result, and finally save the result to the test folder under the run folder.
[0017] S7. Analyze the prediction results, count the misclassified results, and generate the corresponding confusion matrix heat map to facilitate the subsequent calculation of evaluation indicators.
[0018] S8. In order to verify the effectiveness of the white blood cell classification and recognition model more fairly and objectively, four indicators, namely accuracy, precision, recall and F1-score, are introduced to evaluate the model.
[0019] (III) Beneficial effects
[0020] Compared with the prior art, the present invention provides a white blood cell classification method based on an improved YOLOv7, which has the following beneficial effects:
[0021] 1. The present invention replaces the four 3×3 convolution kernels in the ELAN-1 structure of the Backbone part with a lightweight GhostV2 module, thereby reducing the computational complexity and generating more feature maps, thereby reducing the computational time and improving the classification accuracy.
[0022] 2. The present invention integrates SimAM and MHSA attention into the ELAN-2 structure of the Head part, so that the network pays more attention to the granular features of the cell image surface during the classification process, which significantly helps the network to distinguish between granular cells and non-granular cells.
[0023] 3. The present invention adopts the improved Focal Loss to replace the cls Loss in the original YOLOv7, dynamically reduces the weight of easy-to-distinguish samples during training, and quickly focuses on those difficult-to-distinguish samples, which is equivalent to increasing the weight of difficult-to-distinguish samples in the loss function, making the loss function tend to difficult-to-distinguish samples, and at the same time solves the problem of imbalanced white blood cell image categories. BRIEF DESCRIPTION OF THE DRAWINGS
[0024] Figure 1 is a flow chart of the method of the present invention;
[0025] Figure 2 This is the improved YOLOv7 network structure diagram;
[0026] Figure 3 These are the five types of white blood cell images in the dataset;
[0027] Figure 4 This is a partial classification result diagram. DETAILED DESCRIPTION
[0028] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0029] Example
[0030] like Figure 1-4 As shown, a method for classifying white blood cells based on an improved YOLOv7 network proposed in one embodiment of the present invention includes the following steps:
[0031] S1. Collect multiple public white blood cell datasets and perform data enhancement and denoising operations on the datasets. Data enhancement uses rotation of 90°, 180°, 270° and flipping methods to increase the number of white blood cell images in the dataset to five times the original number. Noise reduction uses a combination of nonlinear filtering methods, median filtering and bilateral filtering, which can better protect image edge information while suppressing image noise.
[0032] S2. Use the Labelimg tool to annotate the white blood cell image obtained in step S2 as neutrophils, eosinophils, basophils, monocytes and lymphocytes respectively. The VOC format is used for saving. A new folder Annotations is generated under the folder where the white blood cell image is saved to save the generated xml file.
[0033] S3. Randomly divide the labeled data set into training set, test set and validation set in the ratio of 7:1:2, and create three folders train, test and val to place them respectively in preparation for subsequent network training and prediction.
[0034] S4. Build the basic model of YOLOv7 network structure to improve the YOLOv7 network structure. The specific steps are as follows:
[0035] S4-1. First, the ELAN-1 module is improved. Four convolutions with a size of 3×3 in ELAN-1 are replaced by GhostV2 (Long-distance attention mechanism to enhance cheap operations). The original GhostV1 is composed of two Ghost modules stacked together. This Ghost Block adopts a reverse bottleneck structure. The first Ghost module acts as an expansion layer to increase the number of output channels, and the second Ghost module reduces the number of channels to match the shortcut path. This structure helps to improve the abstraction ability and representation quality of features. GhostNet is a lightweight convolutional neural network, which is designed to generate more feature maps with fewer parameters. It divides the output channel into two identical parts: one part is a regular convolution, which is a normal implementation without any difference. The other part is a cheap operation, which is no longer implemented by regular convolution, but is generated by a simple linear transformation. Finally, the results of the two parts are spliced together to get the final output. GhostV2 is an improvement on GhostV1. The DFC attention branch is paralleled with the first Ghost module to enhance the extended features. The enhanced features are then sent to the second Ghost module to generate output features to capture the long-range dependencies between pixels in different spatial positions, enhancing the model's expressiveness and detail information processing capabilities. The improved ELAN-1 module replaces the first and fourth ELAN-1 modules in the Backbone part of the original YOLOv7 structure, thereby enhancing the feature extraction capabilities of the YOLOv7 network structure.
[0036] S4-2.SimAM attention mechanism is a new type of attention mechanism derived from the existing channel or spatial attention mechanism. This attention mechanism does not need to add additional parameters to derive 3D attention weights for feature maps. Most of its operations are based on the defined energy function selection, thus avoiding excessive structural adjustments. The energy function formula is as follows:
[0037]
[0038] in t and x i They refer to the target neuron and other neurons of the input feature X, i refers to the index in the spatial dimension, M = H × W refers to the number of all neurons in a certain channel, and w t and b t Refers to the "weight" and "bias" of a neuron transformation, respectively, and introduces binary labels instead of y t and y0, find the solution to minimize e t , which is equivalent to finding the linear separability of the target neuron and other neurons. The specific steps are as follows:
[0039] S4-2-1. Input feature map: SimAM will receive the input feature map as input. Assume that the size of the input feature map is H×W×C, where H and W represent the height and width of the feature map, and C represents the number of channels.
[0040] S4-2-2. Reshaping of feature maps: First, SimAM reshapes the input feature map and converts it into a two-dimensional feature matrix of size N×C, where N=H×W represents the total number of pixels in the feature map. This is done to convert spatial information into channel dimensions for subsequent attention calculations.
[0041] S4-2-3. Calculate channel attention weights: Next, SimAM calculates the attention weights of each channel. A simple calculation method is used here, which is to normalize the feature vector of each channel and then use it as the attention weight of the channel. This can make the weights of important channels higher without the need for additional parameters to learn.
[0042] S4-2-4. Apply attention weights: After calculating the attention weights of the channels, SimAM applies these weights to each channel of the input feature map. Specifically, for each channel, its corresponding attention weight is multiplied by the feature value in the channel to enhance the feature representation of important channels.
[0043] S4-2-5. Reconstruct feature map: Finally, the attention-adjusted feature map is reassembled into the original three-dimensional feature map form so that it can be passed to the subsequent network layers for feature extraction and learning.
[0044] S4-3.MHSA is a further improvement on the attention mechanism and self-attention mechanism. It can focus on different positions and features at the same time, improving the representation ability of features. In addition, the attention calculation is divided into multiple heads for parallel calculation, which also improves the calculation efficiency of the model. The specific steps are as follows:
[0045] S4-3-1. Input sequence: MHSA receives an input sequence, usually represented as X = {x1, x2, x3...x n}where n represents the length of the sequence, x i Represents the feature representation of the i-th element in the sequence.
[0046] S4-3-2. Generate query, key, value: For each element x in the input sequence i , MHSA generates three sets of vectors through linear transformation: query vector Q i , key vector K i Sum value vector V i . These vectors will be used to calculate the attention weights and generate the output.
[0047] S4-3-3. Calculate attention weight: For each query vector Q i , MHSA calculates its relationship with all key vectors K j The similarity is usually calculated using dot product or other similarity calculation methods. These similarities are then converted into attention weights through the Softmax function, indicating the degree of association between the query vector and different positions.
[0048] S4-3-4. Weighted summation: Using the calculated attention weights, MHSA sums the value vector V j Perform weighted summation to obtain the query vector Q i This allows important information to receive more attention, while unimportant information is suppressed.
[0049] S4-3-5. Multi-head mechanism: MHSA usually uses multiple heads to calculate attention in parallel, and each head independently learns different query, key, and value mapping relationships. Finally, the outputs of multiple heads are concatenated or weighted summed to obtain richer and more complex representation capabilities.
[0050] S4-3-6. Residual connection and layer normalization: In each MHSA module, residual connection and layer normalization are usually used to stabilize the training process, making it easier for the model to learn effective representations. This can avoid problems such as gradient disappearance or explosion.
[0051] After the present invention integrates SimAM and MHSA into CAT in the ELAN-2 module, the two enable the YOLOv7 network to more accurately and efficiently capture and characterize the features of particles on the image surface, thereby improving the accuracy of white blood cell classification.
[0052] S4-4. Further, we use Focal Loss instead of CLS Loss, which is a dynamic scaling cross entropy loss function based on binary cross entropy CE. By introducing a dynamic scaling factor, the weight of easily distinguishable samples can be reduced during training, thereby quickly focusing on those difficult-to-distinguish samples. The following is its specific form:
[0053]
[0054] make
[0055] Unify the Focal loss expression into one expression:
[0056] L fl =-(1-p t ) γ log(p t )
[0057] It introduces a decay factor p t , when a sample is misclassified, this factor can amplify the loss, making the difficult-to-classify samples occupy a larger weight in the loss function, thereby guiding the model to focus more on the difficult-to-classify samples.
[0058] To solve the problem of class imbalance, I add a weight factor β to the formula t ∈[0,1]:
[0059]
[0060] Then the final balanced loss function is:
[0061] L′ fl =-β t (1-p t ) γ tog(p t )
[0062] S5. Set specific parameters of the improved YOLOv7 network structure, input image size imgsize = 640 × 640, training batch size batch_size = 4, training iteration number Epoch = 100, learning rate lr = 0.0001, decay decay = 0.00001, label smoothing label-smoothing = 0.1, and use adam optimizer as optimizer. Put the improved YOLOv7 network structure with set parameters into a computer with a configured environment and use it to train the white blood cell images in the train folder generated in step S3.
[0063] S6. During training, as the number of iterations increases, the training loss and test loss slowly converge to a stable value, the difference between the two does not change, and the accuracy tends to be stable, indicating that the expected training effect has been achieved. At the same time, the classification results of the test set will also be saved in the form of pictures in the run folder. The folder is divided into two folders, train and test. After the network training is completed, the training results and weights will be output under the train folder. At this time, we select the optimal weight in the training process to test the test set to obtain the optimal test result, and finally save the result to the test folder under the run folder.
[0064] S7. Analyze the prediction results, count the misclassified results, and generate the corresponding confusion matrix heat map to facilitate the subsequent calculation of evaluation indicators.
[0065] S8. In order to verify the effectiveness of the white blood cell classification and recognition model more fairly and objectively, four indicators, namely accuracy, precision, recall and F1-score, are introduced to evaluate the model.
[0066] Precision refers to the proportion of all the results predicted by the model as positive samples that are accurately predicted. The calculation formula is as follows:
[0067]
[0068] Recall represents the proportion of data that are correctly predicted among the data whose true values are positive samples. The calculation formula is as follows:
[0069]
[0070] The F1-Score indicator combines the results of precision and recall. Its value range is from 0 to 1. If the value is 1, it means the model has the best output, and if the value is 0, it means the model has the worst output. Its calculation formula is as follows:
[0071]
[0072] Accuracy is an indicator used to evaluate the performance of a classification model, indicating the proportion of correct classifications among all predictions made by the model. Accuracy is usually expressed as a percentage, and the higher the percentage, the better the classification performance of the model. The calculation formula is as follows:
[0073]
[0074] Finally, it should be noted that the above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Although the present invention has been described in detail with reference to the aforementioned embodiments, those skilled in the art can still modify the technical solutions described in the aforementioned embodiments or replace some of the technical features therein by equivalents. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
Claims
1. A leukocyte classification method based on an improved YOLOv7 network, characterized in that: The following steps are involved: S1. Collect a white blood cell dataset and preprocess the collected white blood cell microscopic images, including noise reduction and data enhancement operations; S2. The images processed by S1 are labeled into categories: neutrophils (NEU), eosinophils (EOS), basophils (BAS), monocytes (MON), and lymphocytes (LYM); S3. The leukocyte microscopic image dataset processed by S2 is randomly divided into a training set, a test set, and a validation set in a ratio of 7:2:1; S4. Improve the original YOLOv7 network structure. S5. Put the training set, test set and validation set divided by S3 into corresponding folders, run the network to train the improved network structure and classify the test set, and save the final result in the run folder. S6. Analyze the final data results and use accuracy, precision, recall and F1-score as evaluation indicators.
2. A method for classifying leukocytes based on an improved YOLOv7 network according to claim 1, characterized in that: The filter function used for noise reduction in step S1 is to eliminate the influence of noise as much as possible while maintaining the characteristics of useful information in the image. For the white blood cell image, we use a combined filtering method of first performing median filtering and then performing bilateral filtering, including: Median filter calculation formula: Where k = 1, 2, 3, ..., M is the median value of the data in the observation window, x1, x2, x3 ... x n is the gray value of the pixels in the neighborhood of the original image, and they are sorted by size as x i1 ≤x i2 ≤x i3 …≤x in . Bilateral filtering calculation formula: Where i, j are the coordinates of the current convolved pixel, k, l are the coordinates of the neighboring pixels, and w is the weighting coefficient, which is determined by the domain kernel and the range kernel and is their product.
3. A method for classifying leukocytes based on an improved YOLOv7 network according to claim 1, characterized in that: The specific steps for improving the YOLOv7 network structure in step S4 are as follows: S3-1. Replace the four parallel convolutional layers in the first and fourth ELAN-1 modules in the Backbone part with GhostV2 modules in turn; the GhostV2 module adds DFC attention on the basis of the original GhostV1, and uses a simpler and easier to implement fully connected layer with fixed weights to generate an attention map with a global receptive field. S3-2. The SimAM attention mechanism and MHSA are integrated into the ELAN-2 module in the Head part; the SimAM attention mechanism does not need to add additional parameters to the original network to derive the attention weights for the feature map. Most operations are based on the defined energy function selection, avoiding excessive structural adjustments, and paying more attention to the presence or absence of particles on the surface of white blood cells. MHSA is a further improvement of the attention mechanism and self-attention mechanism, which can pay attention to different positions and features at the same time, improving the representation ability of features. S3-3. In order to make the model pay more attention to the difficult-to-classify white blood cell samples, thereby improving the classification effect and alleviating the imbalance problem of white blood cell image categories, the improved Focal Loss is used to replace the cls Loss in the original loss function.
4. A method for classifying leukocytes based on an improved YOLOv7 network according to claim 1, characterized in that: The data set in step S5 described in claim 1 is divided into a training set, a test set and a validation set in proportion and placed in a folder specified by the network, and then passed to the network for training and prediction, and the results are saved in a run folder, which is divided into two folders, train and test. After the network training is completed, the training results and weights will be output in the train folder. At this time, we select the optimal weight in the training process to test the test set to obtain the optimal test result, and finally save the result to the test folder under the run folder.
5. The method for classifying white blood cells based on the improved YOLOv7 network according to claim 1, characterized in that: At the end of the prediction, accurate and rich evaluation indicators are also included to illustrate the advantages of the improved YOLOv7 network structure in the field of white blood cell classification, including accuracy, precision, recall and F1-score.
Citation Information
Patent Citations
Deep learning-based micro component defect detection system and method
CN113920087A
Abnormal cell detection method based on improved YOLOv7 and Swinin-Unet
CN115965602A
Improved YOLOv7-based cervical cell pathological image target detection method
CN116958043A
Coal gangue detection method based on Transform and CNN (Convolutional Neural Network)
CN117058074A
Cited By
Method and equipment for testing saturated water absorption rate of traditional Chinese medicine decoction pieces based on water content identification
CN118896874A
Testing Method and Equipment for Saturated Water Absorption Rate of Chinese Herbal Pieces Based on Water Content Identification
CN118896874B
Patient gait recognition algorithm based on improved Lite-HRNet model
CN119229536A
