A brain tumor image automatic classification method and system based on Swin Transformer

Through the ClassSwin network model based on Swin Transformer, combined with data enhancement technology, the problems of low efficiency and poor accuracy of deep learning in brain tumor image data processing are solved, and the classification accuracy and diagnostic efficiency of brain tumor images are significantly improved.

CN118247582BActive Publication Date: 2024-09-10CHANGCHUN UNIV OF SCI & TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202410657765.6
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-05-27
Publication Date
2024-09-10
Estimated Expiration
2044-05-27

AI Technical Summary

Technical Problem

Deep learning has low efficiency and poor accuracy in processing and analyzing brain tumor image data.

Method used

An automatic classification method for brain tumor images based on Swin Transformer is adopted. By constructing a ClassSwin network model, the convolutional Stem layer and ClassSwin Block are used to extract image features, and data enhancement techniques are used during the training process, including random rotation, flipping and gray value regression. Unification improves the generalization ability and robustness of the model.

Benefits of technology

It significantly improves the classification accuracy of brain tumor images, improves the accuracy and efficiency of diagnosis, enhances the model's ability to capture image details and global information, and improves the classification performance of brain tumor images.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118247582B
    Figure CN118247582B
Patent Text Reader

Abstract

A method and system for automatic classification of brain tumor images based on Swin Transformer, relating to the field of medical image processing, solves the problem of low efficiency and poor accuracy of deep learning in processing and analyzing a large amount of brain tumor image data in the prior art. The present invention includes the following technical scheme: the method includes the following steps: acquiring brain tumor automatic classification images and forming a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set; constructing a ClassSwin network model, inputting the training data set and the verification data set into the ClassSwin network model constructed in step 2, and training the ClassSwin network model; using a test data set to verify the trained ClassSwin network model, and using the verified ClassSwin network model to complete the automatic classification of brain tumor images. It is suitable for the fields of deep learning and computer vision.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The invention relates to the technical field of medical image processing. Background Art

[0002] Brain tumors are a serious threat to human health and are treated in a variety of ways, including surgical resection, chemotherapy, and radiotherapy. During the treatment process, accurate judgment of the type of tumor is crucial to developing a scientific and reasonable treatment plan. Traditional diagnostic methods rely on doctors to conduct manual evaluation based on imaging data. This process not only requires doctors to have rich professional knowledge and clinical experience, but also consumes a lot of time and resources. With the development of medical imaging technology, especially the application of deep learning in the field of image processing, a new type of brain tumor image classification auxiliary diagnosis technology has emerged. This technology can efficiently process and analyze a large amount of brain tumor image data, and significantly improves the accuracy and efficiency of diagnosis through automated image recognition and classification. Summary of the invention

[0003] The present invention aims at the problem that deep learning in the prior art has low efficiency and poor accuracy in processing and analyzing a large amount of brain tumor image data. To solve the above technical problems, the present invention is implemented through the following technical solutions:

[0004] The present invention proposes the following technical solutions:

[0005] Solution 1: A method for automatic classification of brain tumor images based on Swin Transformer, the method comprising the following steps:

[0006] Step 1: acquiring brain tumor automatic classification images and forming a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set;

[0007] Step 2: construct a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block;

[0008] Step 3: Input the training data set and the validation data set in step 1 into the ClassSwin network model constructed in step 2 to train the ClassSwin network model;

[0009] Step 4: The ClassSwin network model trained in step 3 is verified using a test data set, and the verified ClassSwin network model is used to complete the automatic classification of brain tumor images.

[0010] Further, a preferred embodiment is provided, in which the method for obtaining the brain tumor automatic classification image data set in step 1 is:

[0011] S1.1, converting the brain tumor automatic classification image into a grayscale image;

[0012] S1.2, use the zip function to separate the grayscale image and label described in S1.1, and process the grayscale image and label through the Transform network;

[0013] S1.3, define the training data set, which is used to train the images processed by the Transform network.

[0014] Labeled datasets;

[0015] S1.4. Define a validation dataset to validate the training dataset described in S1.3.

[0016] Further, a preferred implementation is provided, in which the method for constructing the ClassSwin network model in step 2 is:

[0017] S2.1, initialize the ClassSwin network model parameters, and define the parameters required to construct the ClassSwin network model parameters;

[0018] S2.2. Based on the parameters defined in S2.1, a hierarchical structure of the ClassSwin network model is constructed, wherein the hierarchical structure includes a convolutional layer, a PatchEmbed module, a position layer, a BasicLayer module, a normalization layer, an average pooling layer, and a linear classification layer;

[0019] S2.3, initialize the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model;

[0020] S2.4, process the input image through the PatchEmbed module, and pass it through each BasicLayer module in turn.

[0021] The block performs feature extraction, applies a normalization layer, reduces the dimension through an average pooling layer, and obtains the final output through a linear classification layer.

[0022] Further, a preferred embodiment is provided, in which the method for initializing the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model in S2.3 is:

[0023] S2.3.1. Construct a convolutional Stem layer to extract local features of the input image.

[0024] S2.3.2. Use the PatchEmbed module to split the feature map after the convolutional Stem layer into at least one non-overlapping patch;

[0025] S2.3.3, introduce a position dropout layer to discard non-overlapping patches during the training of the ClassSwin network model;

[0026] S2.3.4, construct BasicLayer module sequence to construct the hierarchical structure of ClassSwin network model;

[0027] S2.3.5, build the SCAB module, add the SCAB module to the ClassSwin network model, and then obtain the spatial and channel features of the image;

[0028] S2.3.6, remove the position encoding in the ClassSwin network model;

[0029] S 2.3.7, apply the normalization layer. After constructing the BasicLayer module sequence in S2.3.4, use the normalization layer to process the features;

[0030] S2.3.8, use average pooling layer to reduce dimension;

[0031] S2.3.9. Based on S2.3.1 to S2.3.8, complete the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model.

[0032] Further, a preferred implementation is provided, in which the training of the ClassSwin network model in step 3 comprises the following steps:

[0033] S3.1. Create a data loader and set the same parameters as the training data loader;

[0034] S3.2, build the ClassSwin network model based on the parameters set in S3.1 and load the pre-trained weights;

[0035] S3.3, traverse all parameters of the ClassSwin network model, and freeze the weights of all parameter layers except the classification head of the ClassSwin network model;

[0036] S3.4, create an optimizer, select and freeze all parameters except the classification head of the ClassSwin network model from the ClassSwin network model for optimization;

[0037] S3.5, train and evaluate the ClassSwin network model processed by S3.1 to S3.4;

[0038] S3.6. Save the weights of the trained ClassSwin network model to complete the training.

[0039] Further, a preferred implementation is provided, in which the ClassSwin network model trained in step 3 is verified using a test data set in step 4, comprising the following steps:

[0040] S4.1. Prepare the test data set and define the conversion process of the test data set;

[0041] S4.2, loading the ClassSwin network model based on the test data set prepared in S4.1;

[0042] S4.3, initialize the evaluation indicators of the ClassSwin network test model;

[0043] S4.4. Traverse the test data set and calculate the evaluation indicators to complete the verification.

[0044] Furthermore, a preferred embodiment is provided, in which the conversion process of the test data set defined in S4.1 includes the steps of graying, resizing, center cropping, converting to tensor and normalizing.

[0045] Solution 2: A brain tumor image automatic classification method system based on Swin Transformer, the system comprising:

[0046] A data acquisition module, used for acquiring brain tumor automatic classification images to form a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set;

[0047] A model building module, used to build a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block;

[0048] A training module is used to input the training data set and the validation data set into the ClassSwin network model constructed in step 2 to train the ClassSwin network model;

[0049] The classification module is used to verify the trained ClassSwin network model using a test set, and use the verified ClassSwin network model to complete the automatic classification of brain tumor images.

[0050] Solution 3: A computer-readable storage medium, wherein the computer-readable storage medium is used to store a computer program, and the computer program executes the automatic classification method system for brain tumor images based on Swin Transformer described in any one of Solution 1.

[0051] Solution 4: A computer device includes a memory and a processor, wherein the memory stores a computer program. When the processor runs the computer program stored in the memory, the processor executes the automatic classification method system for brain tumor images based on Swin Transformer as described in any one of Solution 1.

[0052] The present invention is beneficial in that:

[0053] The present invention proposes a brain tumor classification model of the ClassSwin network, which introduces a new spatial channel attention block to effectively capture the complex spatial-channel features in brain tumor images. In addition, the brain tumor classification model of the ClassSwin network introduces a convolutional Stem layer structure in the early stage, which is specially designed to enhance the model's capture and understanding of image details. The automatic image classification method of the present invention simultaneously obtains global information and local information of brain tumor images, thereby improving the classification accuracy of brain tumor images.

[0054] The present invention uses data enhancement techniques in the training process of the brain tumor classification model of the ClassSwin network. These techniques include random rotation, flipping and gray value normalization, which are intended to increase the diversity of training data, thereby helping the model to learn more effectively, and thus improving the generalization ability and robustness of the model.

[0055] The present invention is also applicable to the fields of deep learning and computer vision. BRIEF DESCRIPTION OF THE DRAWINGS

[0056] Figure 1 This is a flow chart of the automatic classification method of brain tumor images based on Swin Transformer described in Implementation Example 1.

[0057] Figure 2 This is a schematic diagram of the structure of the convolutional Stem layer in the automatic classification method of brain tumor images based on Swin Transformer described in Implementation Example 1.

[0058] Figure 3 Schematic diagram of the structure of ClassSwin Block in the automatic classification method of brain tumor images based on Swin Transformer described in Implementation Example 1.

[0059] Figure 4 Schematic diagram of the confusion matrix for four-class classification of brain tumor images using the ClassSwin model described in Implementation Example 11. DETAILED DESCRIPTION

[0060] In order to make the purpose, technical solutions and advantages of the implementation methods of the present application clearer, the technical solutions in the implementation methods of the present application will be clearly and completely described below in conjunction with the drawings in the implementation methods of the present application. Obviously, the described implementation methods are only part of the implementation methods of the present application, not all of the implementation methods.

[0061] Embodiment 1: This embodiment provides a method for automatic classification of brain tumor images based on Swin Transformer, the method comprising the following steps:

[0062] Step 1: acquiring brain tumor automatic classification images and forming a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set;

[0063] Step 2: construct a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block;

[0064] Step 3: Input the training data set and the validation data set in step 1 into the ClassSwin network model constructed in step 2 to train the ClassSwin network model;

[0065] Step 4: The ClassSwin network model trained in step 3 is verified using a test data set, and the verified ClassSwin network model is used to complete the automatic classification of brain tumor images.

[0066] Embodiment 2: This embodiment further limits the method for automatic classification of brain tumor images based on Swin Transformer described in embodiment 1. The method for obtaining the automatic classification image of brain tumor to form a data set in step 1 is:

[0067] S1.1, converting the brain tumor automatic classification image into a grayscale image;

[0068] S1.2, use the zip function to separate the grayscale image and label described in S1.1, and process the grayscale image and label through the Transform network;

[0069] S1.3, define the training data set, which is used to train the images processed by the Transform network.

[0070] Labeled datasets;

[0071] S1.4. Define a validation dataset to validate the training dataset described in S1.3.

[0072] Embodiment 3: This embodiment further limits the automatic classification method of brain tumor images based on Swin Transformer described in Embodiment 1. The method of constructing the ClassSwin network model in step 2 is:

[0073] S2.1, initialize the ClassSwin network model parameters, and define the parameters required to build the ClassSwin network model;

[0074] S2.2, based on the parameters defined in S2.1, construct the hierarchical structure of the ClassSwin network model.

[0075] The hierarchical structure includes convolution layer, PatchEmbed module, position layer, BasicLayer module, normalization layer, average pooling layer, and linear classification layer;

[0076] S2.3, initialize the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model;

[0077] S2.4, process the input image through the PatchEmbed module, and pass it through each BasicLayer module in turn.

[0078] The block performs feature extraction, applies a normalization layer, reduces the dimension through an average pooling layer, and obtains the final output through a linear classification layer.

[0079] Embodiment 4: This embodiment further limits the brain tumor image automatic classification method based on Swin Transformer described in Embodiment 3. The method for initializing the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model in S2.3 is:

[0080] S2.3.1. Construct a convolutional Stem layer to extract local features of the input image.

[0081] S2.3.2. Use the PatchEmbed module to split the feature map after the convolutional Stem layer into at least one non-overlapping patch;

[0082] S2.3.3, introduce a position dropout layer to discard non-overlapping patches during the training of the ClassSwin network model;

[0083] S2.3.4, construct BasicLayer module sequence to construct the hierarchical structure of ClassSwin network model;

[0084] S2.3.5, build the SCAB module, add the SCAB module to the ClassSwin network model, and then obtain the spatial and channel features of the image;

[0085] S2.3.6, remove the position encoding in the ClassSwin network model;

[0086] S 2.3.7, apply the normalization layer. After constructing the BasicLayer module sequence in S2.3.4, use the normalization layer to process the features;

[0087] S2.3.8, use average pooling layer to reduce dimension;

[0088] S2.3.9. Based on S2.3.1 to S2.3.8, complete the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model.

[0089] Embodiment 5: This embodiment further limits the brain tumor image automatic classification method based on Swin Transformer described in Embodiment 1. In step 3, training the ClassSwin network model includes the following steps:

[0090] S3.1. Create a data loader and set the same parameters as the training data loader;

[0091] S3.2, build the ClassSwin network model based on the parameters set in S3.1 and load the pre-trained weights;

[0092] S3.3, traverse all parameters of the ClassSwin network model, and freeze the weights of all parameter layers except the classification head of the ClassSwin network model;

[0093] S3.4, create an optimizer, select and freeze all parameters except the classification head of the ClassSwin network model from the ClassSwin network model for optimization;

[0094] S3.5, train and evaluate the ClassSwin network model processed by S3.1 to S3.4;

[0095] S3.6. Save the weights of the trained ClassSwin network model to complete the training.

[0096] Embodiment 6: This embodiment further limits the brain tumor image automatic classification method based on Swin Transformer described in embodiment 1. In step 4, the ClassSwin network model trained in step 3 is verified using a test data set, which includes the following steps:

[0097] S4.1. Prepare the test data set and define the conversion process of the test data set;

[0098] S4.2, loading the ClassSwin network model based on the test data set prepared in S4.1;

[0099] S4.3, initialize the evaluation indicators of the ClassSwin network test model;

[0100] S4.4. Traverse the test data set and calculate the evaluation indicators to complete the verification.

[0101] Embodiment 7: This embodiment further limits the brain tumor image automatic classification method based on Swin Transformer described in Embodiment 6. The conversion process of the test data set defined in S4.1 includes the steps of graying, resizing, center cropping, conversion to tensor and normalization.

[0102] Embodiment 8: This embodiment proposes a brain tumor image automatic classification method system based on Swin Transformer, the system comprising:

[0103] A data acquisition module, used for acquiring brain tumor automatic classification images to form a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set;

[0104] A model building module, used to build a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block;

[0105] A training module is used to input the training data set and the validation data set into the ClassSwin network model constructed in step 2 to train the ClassSwin network model;

[0106] The classification module is used to verify the trained ClassSwin network model using a test set, and use the verified ClassSwin network model to complete the automatic classification of brain tumor images.

[0107] Embodiment 9: This embodiment proposes a computer device, including a memory and a processor, wherein the memory stores a computer program, and when the processor runs the computer program stored in the memory, the processor executes the method described in any one of embodiments 1 to 7.

[0108] Embodiment 10: A computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the method described in any one of embodiments 1 to 7 are implemented.

[0109] Implementation method 11: See Figures 1 to 4 This embodiment is described. This embodiment provides an example, which is used to explain the above-mentioned embodiments 1 to 10. The specific examples are as follows:

[0110] A method for automatically classifying brain tumor images based on Swin Transformer, the method comprising the following steps:

[0111] Step 1: acquiring brain tumor automatic classification images and forming a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set;

[0112] 5712 brain tumor images in the Kaggle public dataset were converted into the input required by the network. Then, the brain tumor images were preprocessed. During training and testing, to ensure the consistency of the model input, the input images were cropped from 219×234 to 512×512 pixels to 224×224; this ensures that the images received by the model during training have a uniform dimension, thereby improving training efficiency and model performance;

[0113] In order to improve the generalization and robustness of the model, the ClassSwin model uses data augmentation techniques during training. These techniques include random rotation, flipping, and grayscale value normalization, which are designed to increase the diversity of training data, thereby helping the model learn more effectively;

[0114] Step 2: construct a ClassSwin network model, wherein the ClassSwin network includes a convolutional Stem layer and multiple ClassSwin Blocks;

[0115] Step 3: Input the training data set and the validation data set in step 1 into the ClassSwin network model constructed in step 2 to train the ClassSwin network model;

[0116] Step 4: The ClassSwin network model trained in step 3 is verified using a test data set, and the verified ClassSwin network model is used to complete the automatic classification of brain tumor images.

[0117] Furthermore, the step 1 is specifically as follows:

[0118] Step 1.1: Import the required libraries;

[0119] The step 1.1 specifically includes PIL, torch and torch.utils.data;

[0120] Step 1.2: Create a MyDataSet(Dataset) class. Define the MyDataSet class, which inherits from the Dataset class. In the constructor __init__, accept two parameters: images_path and images_class. images_path is a list containing the path of the image files, and images_class is a list corresponding to images_path, containing the category label of each image. In the __len__ method, the length of the dataset, that is, the length of the images_path list, is returned. In the __getitem__ method, use the Image.open function to open the image file of the specified path and convert it to a grayscale image. Then, get the category label corresponding to the image from the images_class list. If the transform parameter is provided, the image will undergo the specified transformation operation. Finally, __getitem__ returns a tuple containing the processed image and its corresponding label.

[0121] Step 1.3: Define the collate_fn function, which accepts a batch of images and labels as input. Use the zip function to separate the batch of images and labels, and use the torch.stack and torch.as tensor functions to stack them into batch tensors and tensors respectively. Then, return a tuple containing the stacked images and labels.

[0122] Step 1.4: Define the training dataset MyDataSet and instantiate a dataset class named MyDataSet for training data. The parameters passed to the constructor include images_path, images_class, and transform. images_path is a list containing the training image file paths, images_class is a list corresponding to images_path, containing the category label of each image, and transform is an image transformation operation.

[0123] Specifically, the step 1.4 is: RandomResizedCrop: randomly resize and crop the image to increase data diversity. RandomHorizontalFlip: randomly flip the image horizontally to enhance the robustness of the model to the image direction. ToTensor: convert the PIL image or NumPy array to a PyTorch tensor. Normalize: normalize the tensor to make the data more stable during training.

[0124] Step 1.5: Define the validation dataset MyDataSet and instantiate another dataset class named MyDataSet for validation data. The parameters passed to the constructor include images_path, images_class, and transform. images_path is a list containing the validation image file paths, images_class is a list corresponding to images_path, containing the category labels for each image, and transform is an image transformation operation.

[0125] The step 1.5 is specifically as follows: Resize: adjust the image size. CenterCrop: center crop the image to ensure that the image size of the input model is consistent. ToTensor: convert the image to a tensor as above. Normalize: normalize the tensor as above.

[0126] Furthermore, the step 2 is specifically as follows:

[0127] Step 2.1: Define the ClassSwin class, which inherits from nn.Module and is used to implement the ClassSwin model.

[0128] Step 2.2: Initialize the model parameters. In the constructor __init__ of the ClassSwin class, receive multiple parameters, including: patch_size is set to 4: the patch size for dividing the image. in_chans is set to 1: the number of channels of the input image. num_classes is set to 4: the number of categories for the classification task. embed_dim is set to 96: the embedding dimension, that is, the feature dimension of each patch embedding. depths is set to 2, 2, 6, 2: the depth of each ClassSwin layer. num_heads is set to 3, 6, 12, 24: the number of attention heads in different layers. window_size is set to 7: the window size, used for local self-attention calculation. mlp_ratio is set to 4: the ratio of the MLP hidden dimension to the embedding dimension. qkv_bias is set to True: whether to add bias terms for query, key, and value. drop_rate, attn_drop_rate: set the dropout rate and attention dropout rate respectively, both set to 0.1. drop_path rate is set to 0.1: the random depth rate, used for regularization. norm_layer: Normalization layer type. patch_norm: Whether to add normalization after patch embedding. use_checkpoint: Whether to use checkpointing to save memory for defining the parameters of the model.

[0129] Step 2.3: Build the model structure and use nn.ModuleList to build the hierarchical structure of the model, including:

[0130] A convolutional Stem to obtain local information of the image, a PatchEmbed module to split the input image into non-overlapping patches and embed them. A position dropout layer to randomly discard some patches during training. A series of BasicLayer modules, each containing multiple ClassSwin blocks, to build the hierarchical structure of the model. A normalization layer to normalize the final features. An average pooling layer for dimensionality reduction. A linear classification layer for the final classification task.

[0131] Step 2.4: Weight initialization, implement the __init__ weights method to initialize the weights of the linear layer and normalization layer in the model.

[0132] Step 2.5: Forward propagation. In the forward method, define the forward propagation logic of the model: first process the input image through the PatchEmbed module. Apply positional dropout. Perform feature extraction through each BasicLayer module in turn. Apply normalization. Reduce the dimension through the average pooling layer. Flatten the features and get the final output through the linear classification layer.

[0133] Furthermore, the step 2.3 is specifically as follows:

[0134] Step 2.3.1: Construct the convolutional Stem, Figure 2 The structure diagram of the convolutional Stem of the present invention is a sequence of convolutional layers used to extract local features of the input image. Figure 2 The d in the figure represents depth-wise separable convolution.

[0135] Step 2.3.2: Apply the PatchEmbed module, which is used to split the feature map after the convolutional Stem layer into a series of non-overlapping patches. Each patch is a small image block, which will be flattened and embedded into a high-dimensional space for subsequent processing.

[0136] Step 2.3.3: Introduce a position dropout layer. After the PatchEmbed module, introduce a position dropout layer to enhance the generalization ability of the model. The position dropout layer randomly discards a part of the patch during training, forcing the network to learn more robust feature representations.

[0137] Step 2.3.4: Build a BasicLayer module sequence. Create a series of BasicLayer modules, each containing multiple ClassSwin blocks. Figure 3 It is a structural diagram of the ClassSwin Block of the present invention. Figure 3 middle represents the input of LN, and represents the output of MLP, and Represents the output of SCAB. These modules are responsible for building the hierarchical structure of the model to enhance segmentation performance by capturing image features at different scales. Each BasicLayer module will have different window sizes, depths, and the number of attention heads to adapt to features at different levels.

[0138] Step 2.3.5: Construct SCAB module. ClassSwin block adds SCAB module to obtain the spatial and channel features of the image.

[0139] Step 2.3.6: Remove the position code in the ClassSwin block;

[0140] Step 2.3.7: Apply Normalization Layer. After the BasicLayer module sequence, a normalization layer is used to process the features.

[0141] Step 2.3.8: Use average pooling layer to reduce dimensionality. Apply an average pooling layer to further reduce the spatial dimension of the feature. The average pooling operation calculates the average value of each local region, which helps to extract global context information.

[0142] Step 2.3.9: Finally, implement the linear classification layer and use a linear classification layer to complete the final classification task. This layer maps the output of the previous layer to predefined categories to distinguish between four types of brain tumor images: no tumor, glioma, meningioma, and pituitary tumor.

[0143] Furthermore, the step 2.3.1 is specifically as follows:

[0144] Step 2.3.1.1: Initialize the ConvNeBlock class. In the constructor __init__, receive dim, drop_path, and layer_scale_init_value as parameters.

[0145] Step 2.3.1.2: Define a depthwise separable convolutional layer. Use nn.Conv2d to create a depthwise separable convolutional layer with parameters including dim, number of output channels 4*dim, kernel size 7, padding 3, and number of groups dim.

[0146] Step 2.3.1.3: Define the normalization layer. Use nn.LayerNorm to create a normalization layer with parameters including dim and eps.

[0147] Step 2.3.1.4: Define the first dot convolution layer. Use nn.Linear to create the first dot convolution layer. The parameters include input dimension 1 and output dimension dim.

[0148] Step 2.3.1.5: Define the activation function. Create an activation function using nn.GELU.

[0149] Step 2.3.1.6: Define the second dot convolution layer. Use nn.Linear to create the second dot convolution layer with parameters including input dimension 4*dim and output dimension dim.

[0150] Step 2.3.1.7: Define the scaling parameter. Use nn.Parameter to create a scaling parameter, the parameter includes layer_scale_init_value multiplied by torch.ones((dim)) if layer_scale_init_value>0, otherwise it is set to None.

[0151] Step 2.3.1.8: Define DropPath layer. Use DropPath to create a DropPath layer with parameters including drop_path. If drop_path <= 0, use nn.Identity().

[0152] Step 2.3.1.9: Define the forward propagation method. In the forward method, the input x is first transformed to meet the requirements of subsequent operations. A series of convolution and activation operations are performed using pwconv1, norm, dwconv, act, and pwconv2. If there is a gamma parameter, it is applied to the output. The input and the transformed output are added and passed through the drop_path layer. The final output is returned.

[0153] Furthermore, the step three is specifically as follows:

[0154] Step 3.1: Create a data loader. Use torch.utils.data.DataLoader to create a training data loader train_loader, pass in the training dataset train_dataset, and set appropriate parameters, such as batch size batch_size set to 8, shuffle data, use memory mapping pin_memory, number of worker threads num_workers to 8, and a custom batch function collate_fn. Similarly, create a validation data loader val_loader, pass in the validation dataset val_dataset, set similar parameters to the training data loader, but do not need to shuffle the data.

[0155] Step 3.2: Build the model, do not load the pre-trained weights, call the create_model function to create a model instance, and pass in the number of categories num_classes. Move the model to the specified device device.

[0156] Step 3.3: Unfreeze the model layer.

[0157] Step 3.4: Initialize the optimizer and select the parameters that need gradient updates from the model (i.e. the parameters for which requires_grad is true). Use optim.AdamW to create an optimizer instance, passing in the above parameters, a learning rate of args.lr of 0.0001, and a weight decay rate of 5E-2.

[0158] Step 3.5: Train and evaluate the model. For each training cycle epoch: Call the train_one_epoch function to perform a training cycle, passing in the model, optimizer, training data loader, device, and current cycle number. Calculate and return the training loss train_loss and training accuracy train_acc. Call the evaluate function to evaluate the performance of the model on the validation set, and calculate the validation loss val_loss and validation accuracy val_acc. Use the TensorBoard recorder tb_writer to record the training and validation loss, accuracy, and learning rate.

[0159] Step 3.6: Save the model weights. At the end of each training cycle, use the torch.save function to save the model's current state dictionary to a file with the file name containing the cycle number epoch.

[0160] Furthermore, the step 4 is specifically as follows:

[0161] Step 4.1: Prepare the test dataset and define the path test_path of the test dataset. Set the image size img_size to 224 and the number of categories num_classes to 4. Define the data transformation process data_transform, including grayscale, resizing, center cropping, conversion to tensor and normalization. Use ImageFolder to create the test dataset test_dataset. Create a test data loader test_loader, set the batch size to 8, do not shuffle the data, and do not use additional worker threads.

[0162] Step 4.2: Load the class index and model. Confirm that the class index file class_indices.json exists and load the file content into class_indict. Create a model instance model according to the number of classes num_classes. Load the pre-trained model weights into model. Set the model to evaluation mode model.eval().

[0163] Step 4.3: Initialize the evaluation indicators and the confusion matrix. Define the category label list labels. Initialize the accuracy accuracy_sum, the number of samples sample_num, the precision precision_sum, the recall recall_sum and the F1 score f1_sum.

[0164] Step 4.4: Loop through the test data and calculate the evaluation metrics, using torch.no_grad() to disable gradient calculation. Loop through each batch of data in test_loader: Get the input image and the true label. Use the model to predict the image and get the output outputs. Apply the softmax function to the output. Use torch.argmax to get the predicted category. Calculate and accumulate accuracy, precision, recall, and F1 score. Update the confusion matrix confusion. Convert the true label and predicted category to NumPy arrays to calculate precision, recall, and F1 score.

[0165] Step 4.5: Calculate and print the final evaluation metrics. Calculate the final accuracy, precision, recall, and F1 score. Use the plot and summary methods of the confusion matrix to visualize and summarize the evaluation results. Use logging.info to print the values ​​of the evaluation metrics. Figure 4 This is the confusion matrix of the ClassSwin model of the present invention for the four classifications of brain tumor images. It can be seen that the classification accuracy of the ClassSwin model of the present invention is very high.

[0166] Furthermore, the step 4.1 is specifically as follows:

[0167] Step 4.1.1: Create a data transformation process. Use transforms.Compose to create a data transformation process that will be applied to each image in the dataset.

[0168] Step 4.1.2: Grayscale the image. Apply transforms.Grayscale to convert the color image to a grayscale image. Set the num_output_channels parameter to 1 to output a single-channel grayscale image.

[0169] Step 4.1.3: Resize the image using transforms.Resize. Calculate the new size by multiplying the target image size img_size by a scaling factor (1.14) and converting it to an integer. Apply transforms.Resize to resize the image to the new size.

[0170] Step 4.1.4: Center crop the image. Apply transforms.CenterCrop to center crop the resized image to ensure that the image size is consistent.

[0171] Step 4.1.5: Convert to Tensor. Use transforms.ToTensor to convert the cropped image to a PyTorch tensor.

[0172] Step 4.1.6: Normalize the image and apply transforms.Normalize to normalize the tensor. Set the normalization parameters to normalize each element of the tensor using the mean [0.5] and standard deviation [0.5].

[0173] By following these steps, a complete preprocessing pipeline can be created for the images in the dataset, including grayscale, resizing, cropping, conversion to tensors, and normalization for use in model training and validation.

[0174] For the purposes of the embodiments of this specification, "computer-readable medium" may be any device that can contain, store, communicate, propagate or transmit a program for use in an instruction execution system, device or apparatus or in conjunction with these instruction execution systems, devices or apparatuses. More specific examples (non-exhaustive list) of computer-readable media include the following: an electrical connection portion (electronic device) with one or N wirings, a portable computer disk case (magnetic device), a random access memory (RAM), a read-only memory (ROM), an erasable and editable read-only memory (EPROM or flash memory), an optical fiber device, and a portable compact disk read-only memory (CDROM). In addition, the computer-readable medium may even be paper or other suitable medium on which the program may be printed, because the program may be obtained electronically, for example, by optically scanning the paper or other medium, followed by editing, interpreting or processing in other suitable ways as necessary, and then stored in a computer memory. It should be understood that the various parts of the present invention may be implemented in hardware, software, firmware or a combination thereof. In the above embodiments, the N steps or methods may be implemented in software or firmware stored in a memory and executed by a suitable instruction execution system. For example, if implemented in hardware, as in another embodiment, it can be implemented using any one of the following technologies known in the art or a combination thereof: a discrete logic circuit having a logic gate circuit for implementing a logic function on a data signal, a dedicated integrated circuit having a suitable combination of logic gate circuits, a programmable gate array (PGA), a field programmable gate array (FPGA), etc.

[0175] Those skilled in the art will appreciate that the above are only preferred embodiments of the present invention, and the various embodiments of the present disclosure and / or the features described in the claims may be combined or combined in various ways, even if such combinations or combinations are not explicitly described in the present disclosure. It 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 may still modify the technical solutions described in the aforementioned embodiments, or perform equivalent substitutions on some of the technical features therein. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principles of the present invention shall be included in the protection scope of the present invention.

[0176] Although preferred embodiments of the present invention have been described, additional changes and modifications may be made to these embodiments by those skilled in the art once the basic inventive concepts are known. Therefore, the appended claims are intended to be interpreted as including the preferred embodiments and all changes and modifications that fall within the scope of the present invention. Obviously, those skilled in the art may make various changes and modifications to the present invention without departing from the spirit and scope of the present invention. Thus, if these modifications and variations of the present invention fall within the scope of the claims of the present invention and their equivalents, the present invention is also intended to include these modifications and variations.

Claims

1. A brain tumor image automatic classification method based on Swin Transformer, characterized in that: The method comprises the following steps: Step 1: acquiring brain tumor automatic classification images and forming a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training data set and a verification data set; Step 2: construct a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block; Step 3: Input the training data set and the validation data set in step 1 into the ClassSwin network model constructed in step 2 to train the ClassSwin network model; Step 4: The ClassSwin network model trained in step 3 is verified using a test data set, and the verified ClassSwin network model is used to complete the automatic classification of brain tumor images; The method for constructing the ClassSwin network model in step 2 is: S2.1, initialize the ClassSwin network model parameters, and define the parameters required to build the ClassSwin network model; S2.

2. Based on the parameters defined in S2.1, a hierarchical structure of the ClassSwin network model is constructed, wherein the hierarchical structure includes Convolutional layer, PatchEmbed module, position layer, BasicLayer module, normalization layer, average pooling layer, linear classification layer; S2.3, initialize the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model; S2.4, process the input image through the PatchEmbed module, and perform feature extraction through each BasicLayer module in turn. Take, apply a normalization layer, reduce the dimension through an average pooling layer, and get the final output through a linear classification layer; The method for initializing the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model in S2.3 is: S2.3.

1. Construct a convolutional Stem layer to extract local features of the input image. S2.3.

2. Use the PatchEmbed module to split the feature map after the convolutional Stem layer into at least one non-overlapping patch; S2.3.3, introduce a position dropout layer to discard non-overlapping patches during the training of the ClassSwin network model; S2.3.4, construct BasicLayer module sequence to construct the hierarchical structure of ClassSwin network model; S2.3.5, build the SCAB module, add the SCAB module to the ClassSwin network model, and then obtain the spatial and channel features of the image; S2.3.6, remove the position encoding in the ClassSwin network model; S 2.3.7, apply the normalization layer. After constructing the BasicLayer module sequence in S2.3.4, use the normalization layer to process the features; S2.3.8, use average pooling layer to reduce dimension; S2.3.

9. Based on S2.3.1 to S2.3.8, complete the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model.

2. The method for automatic classification of brain tumor images based on Swin Transformer according to claim 1, characterized in that: The method for obtaining the brain tumor automatic classification image data set in step 1 is: S1.1, converting the brain tumor automatic classification image into a grayscale image; S1.2, use the zip function to separate the grayscale image and label described in S1.1, and process the grayscale image and label through the Transform network; S1.3, define the training data set, which is used to train the images processed by the Transform network. Labeled datasets; S1.

4. Define a validation dataset to validate the training dataset described in S1.

3.

3. The automatic classification method of brain tumor images based on Swin Transformer according to claim 1, characterized in that: Training the ClassSwin network model in step 3 includes the following steps: S3.

1. Create a data loader and set the same parameters as the training data loader; S3.2, build the ClassSwin network model based on the parameters set in S3.1 and load the pre-trained weights; S3.3, traverse all parameters of the ClassSwin network model, and freeze the weights of all parameter layers except the classification head of the ClassSwin network model; S3.4, create an optimizer, select and freeze all parameters except the classification head of the ClassSwin network model from the ClassSwin network model for optimization; S3.5, train and evaluate the ClassSwin network model processed by S3.1 to S3.4; S3.

6. Save the weights of the trained ClassSwin network model to complete the training.

4. The method for automatic classification of brain tumor images based on Swin Transformer according to claim 1, characterized in that: In step 4, the ClassSwin network model trained in step 3 is verified using a test data set, which includes the following steps: S4.

1. Prepare the test data set and define the conversion process of the test data set; S4.2, loading the ClassSwin network model based on the test data set prepared in S4.1; S4.3, initialize the evaluation indicators of the ClassSwin network test model; S4.

4. Traverse the test data set and calculate the evaluation indicators to complete the verification.

5. The method for automatic classification of brain tumor images based on Swin Transformer according to claim 4, characterized in that: The conversion process of the test dataset defined in S4.1 includes the steps of grayscale, resizing, center cropping, conversion to tensor, and normalization.

6. A brain tumor image automatic classification method system based on Swin Transformer, characterized in that: The system comprises: A data acquisition module, used for acquiring brain tumor automatic classification images to form a data set, performing image enhancement on the data set, and dividing the enhanced data set into a training set and a validation set; A model building module, used to build a ClassSwin network model, wherein the ClassSwin network model includes a convolutional Stem layer and at least one ClassSwin Block; A training module is used to input the training and validation sets into the ClassSwin network model constructed in step 2 to train the ClassSwin network model; A classification module is used to verify the trained ClassSwin network model using a test set, and use the verified ClassSwin network model to complete the automatic classification of brain tumor images; The method for building the ClassSwin network model in the model building module is: S2.1, initialize the ClassSwin network model parameters, and define the parameters required to build the ClassSwin network model; S2.

2. Based on the parameters defined in S2.1, a hierarchical structure of the ClassSwin network model is constructed, wherein the hierarchical structure includes Convolutional layer, PatchEmbed module, position layer, BasicLayer module, normalization layer, average pooling layer, linear classification layer; S2.3, initialize the weights of the linear layer and the normalization layer in the hierarchical structure of the ClassSwin network model; S2.4, process the input image through the PatchEmbed module, and perform feature extraction through each BasicLayer module in turn. Take, apply a normalization layer, reduce the dimension through an average pooling layer, and get the final output through a linear classification layer; The method for initializing the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model in S2.3 is: S2.3.

1. Construct a convolutional Stem layer to extract local features of the input image. S2.3.

2. Use the PatchEmbed module to split the feature map after the convolutional Stem layer into at least one non-overlapping patch; S2.3.3, introduce a position dropout layer to discard non-overlapping patches during the training of the ClassSwin network model; S2.3.4, construct BasicLayer module sequence to construct the hierarchical structure of ClassSwin network model; S2.3.5, build the SCAB module, add the SCAB module to the ClassSwin network model, and then obtain the spatial and channel features of the image; S2.3.6, remove the position encoding in the ClassSwin network model; S2.3.7, apply the normalization layer. After constructing the BasicLayer module sequence in S2.3.4, use the normalization layer to process the features; S2.3.8, use average pooling layer to reduce dimension; S2.3.

9. Based on S2.3.1 to S2.3.8, complete the weights of the linear layer and normalization layer in the hierarchical structure of the ClassSwin network model.

7. A computer device comprising a memory and a processor, characterized in that A computer program is stored in the memory. When the processor runs the computer program stored in the memory, the processor executes the method according to any one of claims 1 to 5.

8. A computer-readable storage medium, characterized in that The computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the method according to any one of claims 1 to 5 are implemented.