Cordyceps sinensis detection method based on knowledge distillation TinyViT network
By using knowledge distillation technology in Cordyceps detection, the ViT network is used as a teacher model to guide TinyViT model training, which solves the problem of poor performance of existing Cordyceps detection algorithms in small target recognition and achieves high efficiency and accuracy in resource-constrained environments. Cordyceps test.
Patent Information
- Application Number
- CN202410812728.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-06-22
- Publication Date
- 2024-09-17
AI Technical Summary
Existing Cordyceps detection algorithms are not effective in identifying small targets, especially in resource-constrained environments, making it difficult to achieve efficient and accurate Cordyceps detection.
Using the TinyViT network method based on knowledge distillation, the ViT network with excellent performance is used as a teacher model to guide the training of the lightweight TinyViT model. Through data preprocessing and model compression technology, the speed and accuracy of Cordyceps detection are improved.
It significantly improves the speed and accuracy of Cordyceps detection, enables efficient real-time detection under resource constraints, and keeps the model lightweight and computationally complex.
Smart Images

Figure CN118658157A
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of target detection, and in particular to a Cordyceps detection method based on a TinyViT network of knowledge distillation. Background Art
[0002] With the continuous development of science and technology, researchers have proposed a large number of excellent target detection algorithms, but in actual scenarios, the specific identification and classification of specific targets is also a direction that needs to be focused on. For various plants, there are slight differences in individual size and shape between artificially cultivated and wild plants. How to use algorithms to identify these subtle differences and screen out wild and cultivated species is much more difficult.
[0003] With the development and application of deep learning, many researchers have proposed a large number of excellent target detection algorithms, such as the classic R-CNN algorithm, YOLO algorithm and SSD algorithm. However, these classic target detection algorithms have good detection effects on medium and large targets, but for targets with small imaging areas, even if deep networks are used to extract features, the features extracted about small targets are limited, and the detection effect is not ideal. This problem is common in many target detection tasks, and it is also true for Cordyceps-related problems. Summary of the invention
[0004] In order to overcome the shortcomings of existing Cordyceps detection technology, this paper proposes a TinyViT network detection method based on knowledge distillation. This method combines knowledge distillation technology and uses the ViT network with excellent performance as a teacher model to guide the lightweight TinyViT model for training, thereby significantly improving the speed and accuracy of Cordyceps target detection under limited computing power, effectively solving the problem of poor Cordyceps detection effect.
[0005] The purpose of the present invention can be achieved through the following technical solutions:
[0006] Step 1: In the Cordyceps detection task, the construction and preprocessing of the dataset is a crucial step. A high-quality, accurately labeled dataset is essential for training a model with superior performance.
[0007] First, a large amount of Cordyceps image data needs to be collected. This data can come from various sources, such as field photography, web crawling, or public data sets. Ensure that the collected data is diverse, including Cordyceps images with different lighting conditions, different backgrounds, different angles, and different scales.
[0008] Next, we use open-source image annotation tools such as LabelMe to accurately annotate the Cordyceps images. During the annotation process, we need to assign the correct category labels to the Cordyceps body, grass head, and background, and ensure that the bounding box of each target surrounds the target as accurately as possible. Through the annotation function of LabelMe, we can generate an annotation file containing the target category and location information for each image.
[0009] After completing the data annotation, the dataset needs to be divided into training set, validation set and test set. The proportions of these three sets are divided according to approximately 70%, 15% and 15%. The training set is used to train the Cordyceps detection model, the validation set is used to evaluate the performance of the model during the training process, and the test set is used to finally evaluate the performance of the model. When dividing the dataset, it is necessary to ensure that the samples in each set are sufficiently diverse and representative.
[0010] Through the above steps, a high-quality and accurately labeled Cordyceps detection dataset can be constructed to provide strong support for subsequent model training.
[0011] Step 2: Preprocessing and mask generation before building the ViT network.
[0012] In order to accurately identify Cordyceps, we took a series of preprocessing steps before training the ViT network. First, we used SAM and yolov8 techniques to accurately cut out the Cordyceps body to avoid interference from background or other irrelevant objects.
[0013] Next, we generate a mask based on the segmented Cordyceps entity. The mask is a binary image that identifies the location of Cordyceps in the original image. The value of each pixel in the mask is determined according to the following formula:
[0014]
[0015] Where r represents the true bounding box of Cordyceps, i and j represent the horizontal and vertical coordinates in the image respectively. If the coordinate (i, j) is within the true bounding box of Cordyceps, the pixel value of the corresponding position in the mask is 1, otherwise it is 0.
[0016] By combining the generated mask with the original image, we can remove the redundant background in the image and keep only the parts related to Cordyceps. This processed image will be input into the ViT network as training data, which will help the network pay more attention to the characteristics of Cordyceps and improve the accuracy of recognition.
[0017] Step 3: Training of ViT network and knowledge distillation of TinyViT model.
[0018] After preparing the training data, we use the training set to train the ViT network. During the training process, the ViT network not only learns how to identify Cordyceps, but also acts as a teacher network to store each enhanced image A and its corresponding predicted probability vector y.
[0019] =T(A), where T represents the prediction function of the ViT network. These stored data pairs (A, T(A)) will play a key role in the subsequent training of the TinyViT model.
[0020] Since random numbers are involved in the data augmentation process, the (A, T(A)) saved in different iterations may not be exactly the same. However, this diversity helps the TinyViT model learn more robust feature representations.
[0021] After training, we use the test set to evaluate the performance of the ViT Cordyceps detection model. During the test, the input Cordyceps images are first preprocessed by SAM and YOLO technology to remove background noise and interference factors. Then, these preprocessed images will be sent to the ViT model for testing to verify its accuracy and efficiency in identifying Cordyceps.
[0022] Next, we use the trained ViT model as a teacher network to guide the training of the TinyViT model. The TinyViT model is a lightweight neural network designed for fast and accurate Cordyceps detection in resource-constrained environments. During training, the TinyViT model reads the enhancement parameters of the teacher network (ViT), performs the same enhancement processing on the input image, and trains using the cross-entropy loss function L. Through this knowledge distillation method, the TinyViT model can inherit the excellent performance of the ViT model while maintaining a small model size and computational complexity.
[0023] Finally, we use the test set to evaluate the trained TinyViT Cordyceps detection model to verify its detection effect and accuracy in real scenarios. This knowledge distillation-based TinyViT network can not only improve the speed and accuracy of Cordyceps detection, but also achieve efficient real-time detection under limited computing power. BRIEF DESCRIPTION OF THE DRAWINGS
[0024] Figure 1 It is a schematic diagram of the process of the present invention;
[0025] Figure 2 It is a schematic diagram of the training process of the present invention. DETAILED DESCRIPTION
[0026] The following will be combined with the accompanying drawings to provide a detailed and clear description of the technical solutions in the embodiments of the present invention. It should be emphasized that the embodiments listed are only a part of the present invention, not all of them. For those of ordinary skill in the art, any other embodiments obtained by reasonable deduction or variation without departing from the creative concept of the present invention should be included in the protection scope of the present invention.
[0027] The technical solution adopted by the present invention is a Cordyceps detection method based on the TinyViT network of knowledge distillation, and the specific steps are as follows:
[0028] Step 1: First, in order to construct a dataset suitable for the target detection task, a series of preprocessing steps are required. First, the data is calibrated using the LabelMe tool, and the information of the Cordyceps body, grass head, and background are detailed to ensure the accuracy and completeness of the labels. Then, according to the pre-set ratio, the dataset is scientifically divided into training set, validation set, and test set. Such division helps to effectively evaluate the performance of the model and optimize it in subsequent model training.
[0029] Step 2: After data preprocessing, a key step was added before the ViT network to improve the accuracy of Cordyceps identification. This step combines the fine-tuned SAM technology and yolov8 technology to accurately cut out the Cordyceps body from the image. Through this technology, we successfully generated a mask of the Cordyceps body and combined it with the original image to effectively remove unnecessary background information. Subsequently, these processed images were used to train the model to ensure that the model can focus more on the characteristics of Cordyceps, thereby improving recognition accuracy. The introduction of this step not only optimizes the data quality, but also provides more accurate data support for subsequent model training.
[0030]
[0031] r represents the ground-truth box, i and j refer to the horizontal and vertical coordinates of the feature map respectively. If (i, j) belongs to the ground truth, then M i,j =1, otherwise 0.
[0032] Then, we start training the ViT model. We use the preprocessed images as input data and feed them into the model in batches through the data loader for training. In each iteration, the model extracts the features of the image and calculates the loss function based on the annotated Cordyceps information. Through the back-propagation algorithm, the model continuously optimizes its own parameters to minimize the loss function and improve recognition accuracy.
[0033] During the training process, we will also use the validation set to evaluate the performance of the model. By calculating the accuracy, recall and other indicators on the validation set, we can understand the performance of the model on different data sets and adjust the training strategy based on the evaluation results, such as learning rate adjustment, optimizer selection, etc.
[0034] Finally, when the model achieves satisfactory performance on the validation set, we use the test set to perform a final evaluation of the model. The test set is a dataset independent of the training set and validation set, and is used to evaluate the performance of the model in practical applications. Through the evaluation results on the test set, we can determine whether the model meets actual needs and make necessary adjustments or optimizations.
[0035] Step 3: Use the trained ViT as the teacher network. The following operations need to be performed during the training process:
[0036] First, for each image, the enhancement strategy is applied to obtain the enhanced version A, and the enhanced image is stored.
[0037] Next, the teacher network predicts the enhanced image A and generates a prediction probability vector y = T(A), where T represents the prediction function of the teacher network ViT. The enhanced image A and its corresponding prediction probability vector y are recorded together as (A, T(A)).
[0038] It should be noted that since random numbers are involved in the data augmentation process, even if the same augmentation parameters are used, the augmented images obtained each time may not be completely consistent. Therefore, in order to ensure the stability and reliability of model training, data pairs such as (A, T(A)) need to be saved at different iteration positions.
[0039] After the ViT Cordyceps detection model training is completed, we use the previously divided test set to verify the performance of the model. This step is crucial because it can help us understand the performance of the model in practical applications.
[0040] When testing the model, we also used the previously fine-tuned SAM and YOLO techniques to accurately cut the Cordyceps entity from the image, and used the masked image as the final input image for prediction. This ensures that the model is more focused on the characteristics of the Cordyceps entity and improves the accuracy of detection.
[0041] Through model testing, we can get the detection results and detection accuracy of the ViT Cordyceps detection model. Once the model accuracy reaches the expected requirements, we will use the trained ViT Cordyceps detection model as a teacher model to further train the TinyViT network as a student model.
[0042] During the training process of the TinyViT network, we introduced the same SAM and YOLO operations as the ViT network, aiming to remove noise from the input image and improve the robustness of the model.
[0043] The student network will read the enhancement parameters of the teacher network and perform enhancement optimization on the image. The optimization function for image enhancement is defined as:
[0044] L = CE(y, S(A(x)))
[0045] Among them, A(x) represents the enhanced image, S(A(x)) is the predicted probability distribution of the student model, y is the predicted probability distribution of the teacher model, and CE represents the cross entropy loss. By optimizing this function, we can make the student model better learn the predictive ability of the teacher model.
[0046] The compression of the TinyViT student model adopts a progressive model compression method, which extracts key parts from the large model through pruning operations to form a small model. During the compression process, we adjusted multiple shrinkage factors, including the dimension of the embedding, the number of blocks in each stage, the window size, the channel expansion rate, and the dimension of the multi-head attention mechanism, to achieve a reduction in model size while maintaining model performance.
[0047] The TinyViT network structure consists of four stages, each of which contains downsampling operations. Among them, block embedding uses two convolutional layers, the first stage uses the MBConv structure, and the remaining three stages are based on the Transformer structure of window attention. Residual connections are used between stages, the activation function uses the ReLU function, the convolutional layer uses batch normalization, and the linear layer uses layer normalization.
[0048] Finally, the implementation of the TinyViT model is lighter than the baseline ViT model, containing only 28M parameters. Despite the reduction in the number of parameters, TinyViT's accuracy does not drop significantly compared to the baseline model, demonstrating that it achieves effective model compression while maintaining performance.
Claims
1. A Cordyceps detection method based on TinyViT network with knowledge distillation, characterized in that The following steps are involved: Step 1: Construct a dataset and preprocess it: Use LabelMe to calibrate the data, which includes the category information of Cordyceps body, grass head and background, to achieve label annotation for the target detection task; divide the dataset into training set, validation set and test set according to the preset ratio; Step 2: Build an improved ViT network; Step 3: Train the ViT network using the training set samples in step 1; Step 4, detect the Cordyceps image: use the test set data in step 1 to input the ViT network trained in step 3, complete the detection of the Cordyceps image, obtain the detection result and calculate the detection accuracy; Step 5: Use the knowledge distillation method to compress the original network, select the TinyViT network as the student network, and use the ViT Cordyceps identification network as the teacher network; the global knowledge distillation method guides the training of the TinyViT network. The algorithm uses the knowledge distillation method to compress the model; Step 6: Use the test set in step 1 to input the trained TinyViT network to test the performance of TinyViT.
2. The Cordyceps detection method based on the TinyViT network of knowledge distillation according to claim 1, characterized in that: The improved ViT network in step 2 includes: generating a mask by combining SAM and YOLO to separate the background and cordyceps in the cordyceps image; The target mask is generated as follows: r represents the ground-truthbox, i and j refer to the horizontal and vertical coordinates of the feature map respectively. If (i, j) belongs to the ground truth, then M i,j =1, otherwise 0.
3. The Cordyceps detection method based on the TinyViT network of knowledge distillation according to claim 1, characterized in that: The compression of the TinyViT student model in step 5 adopts a progressive model compression method, which prunes a large model into a small model. The shrinkage factors involved include six: the dimension of the embedding, the number of blocks in each stage, the window size of the last three stages, the channel expansion rate of the MbConv block, the channel expansion rate of the multi-layer perceptron in the transformer, and the dimension of each head in the multi-head attention mechanism. The model adopts four stages, and downsampling is performed in each stage. The patch embedding uses two convolutions with a kernel size of 3 and a stride of 2. The first stage uses the MBConv structure of MobileNetV2, and the remaining three stages are all transformer structures with window attention mechanisms. Residual connections are used in each stage, and the activation function uses the ReLU function. The convolution layer uses batch normalization, while the linear layer uses layer normalization. In the pre-training phase of the teacher network, two pieces of information are stored: the image enhancement A and the teacher network’s predicted probability vector for the image. Recorded as (A, T(A)), since there are random numbers in data enhancement, even if the same enhancement parameters are used, the enhanced images obtained are inconsistent, so (A, T(A)) needs to be saved at different iteration positions; During the training phase, the student network will read the enhancement parameters of the teacher network for the same image and enhance the image. The optimization goal is: Where A(x) is the enhanced image, S(A(x)) is the predicted probability distribution of the student model, is the probability distribution predicted by the teacher, and CE is the cross entropy loss.
