A small sample image classification method based on weighted aggregation of textual cues

By introducing text prompt weighted aggregation technology in small sample image classification, using large language models to generate diverse text prompts and performing confidence calculation and weighted aggregation, the problem of insufficient text feature diversity and low classifier robustness is solved, significantly. Improved image classification accuracy.

CN118298213BActive Publication Date: 2024-10-15NAT UNIV OF DEFENSE TECH
View PDF 4 Cites 0 Cited by

Patent Information

Application Number
CN202410268180.5
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-03-09
Publication Date
2024-10-15
Estimated Expiration
2044-03-09

AI Technical Summary

Technical Problem

Existing small-sample image classification methods have shortcomings in image classification accuracy, especially the insufficient diversity of text features and low robustness of text classifiers, resulting in a need to improve classification accuracy.

Method used

A small-sample image classification method based on weighted aggregation of text prompts is adopted. By building a system consisting of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module and a soft weighting module, a large language model is used to generate diverse text hints and improve the robustness of text classifiers through confidence calculation and weighted aggregation.

Benefits of technology

The accuracy of image classification is significantly improved. Compared with existing methods, the classification accuracy on multiple data sets is greatly improved, and a more robust text classifier is achieved, which is suitable for small sample image classification scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118298213B_ABST
    Figure CN118298213B_ABST
Patent Text Reader

Abstract

The present invention discloses a small sample image classification method based on text prompt weighted aggregation, and the purpose is to solve the problem of low classification accuracy of existing small sample image classification methods. The technical scheme is: construct a small sample image classification system based on text prompt weighted aggregation, which is composed of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module. Construct a training set, a validation set, and a test set. The training set is used to train the small sample image classification system and the validation set is used to test the trained small sample image classification system. The hyperparameters containing the best text classifier are loaded into the small sample image classification system to obtain a trained small sample image classification system with the best performance; the trained small sample image classification system classifies the image input by the user to obtain the image category. The present invention can alleviate the lack of diversity of text features and improve classification accuracy.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of small sample image classification, and in particular to a small sample image classification method based on text prompt weighting for optimizing image classification accuracy. Background Art

[0002] Inspired by the ability of humans to learn quickly, researchers hope that after learning a large amount of data, the model can quickly learn new categories with only a small number of samples. In the era of big data, data acquisition is becoming easier and easier. Models trained with sufficient data have achieved excellent performance in the corresponding fields, but when faced with new data, the original models need to be retrained to achieve better performance. In many real-world application scenarios, such as in the fields of medicine, military, and finance, it is difficult to obtain enough labeled training samples due to factors such as privacy, security, or high data labeling costs. Few-Shot Learning is the main method to solve the above problems, and has been widely used in image classification, object detection and other fields.

[0003] Existing small sample image classification methods are generally divided into two categories: traditional small sample image classification methods and small sample image classification methods based on large models. Traditional small sample image classification methods include three mainstream methods: data enhancement, metric learning and meta-learning. Data enhancement is usually used as a data preprocessing method, using flipping, cropping and other methods in combination; metric learning maps data to feature space and uses metric methods such as Euclidean distance and cosine similarity to complete the classification task; meta-learning aims to obtain a parameter initialization state with high sensitivity, and only needs to be quickly fine-tuned when facing new data. The above three traditional methods still need to train the model on a large amount of data to enable it to have the ability to judge similarities and differences, but the data used by this method is relatively small, and training requires a lot of time and computing power. In recent years, the visual-language large model has developed rapidly and has become a current research hotspot. The visual-language large model uses a large number of image-text pairs for pre-training, and has strong zero-sample and inductive capabilities. CLIP (see the paper "Alec Radford, et al. Learning transferable visual models from natural language supervision. International conference on machine learning. PMLR, 2021." Alec Radford et al.'s paper: Learning transferable visual models from natural language supervision) is a classic large-scale vision-language model. It collects 400 million image-text pairs from the Internet as training sets, and trains the model on the ResNet series and ViT (Vision Transformer) series neural networks to obtain a pre-trained model with strong zero-sample and inductive capabilities. A large number of researchers have used the CLIP model for small-sample image classification and achieved remarkable results.

[0004] The paper "Zhang Renrui, et al. Prompt, generate, then cache: Cascade of foundation models makes strong few-shot learners. In: Proceedings of the IEEE / CVF Conference on Computer Vision and Pattern Recognition. 2023. p. 15211-15222." (CaFo) introduces a small sample image classification method based on a large visual-language model, which uses a large visual-language model to generate a large number of text prompts for each category, aggregates a large number of text prompts with equal weights, and uses the text classifier for classification. However, the contributions of these text prompts of varying quality to the text classifier are obviously different, and equal-weight aggregation is a sub-optimal method. The paper "Sachit Menon, Carl Vondrick. Visual classification via description from large language models. arXiv preprint arXiv: 2210.07183, 2022." (CBD) designs a text prompt template that focuses on category attribute information, but it still uses equal-weight aggregation for weighting.

[0005] The above two small sample image classification methods based on large vision-language models both utilize the high-quality text prompts generated by the large language model to achieve a text classifier with strong robustness. They have great performance advantages, but because they do not take into account the problem of different quality of text prompts, there is still room for improvement in image classification accuracy.

[0006] How to improve the accuracy of image classification remains a technical issue of great concern to those skilled in the art. Summary of the invention

[0007] The technical problem to be solved by the present invention is to propose a small sample image classification method based on text prompt weighted aggregation in view of the problems that the existing small sample image classification methods have insufficient text feature diversity, low robustness of text classifiers, and image classification accuracy needs to be improved. Diversified text prompts are introduced, and text prompt weighted aggregation technology is used to increase a small amount of calculation, alleviate the problems of insufficient text feature diversity and low classifier robustness, and improve classification accuracy.

[0008] In order to solve the above technical problems, the technical solution of the present invention is: construct a small sample image classification system based on text prompt weighted aggregation. The system consists of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module. Prepare and construct the data set required for the small sample image classification system, and divide the data set into a training set, a validation set, and a test set. The confidence calculation module and the soft weighting module in the small sample image classification system are trained using the training set to obtain a more robust trained small sample image classification system. The trained small sample image classification system is tested using the validation set, and the hyperparameters with the best performance of the best text classifier are assigned to the trainable modules (confidence calculation module, soft weighting module) in the small sample image classification system to obtain the best performance trained small sample image classification system; finally, the best performance trained small sample image classification system is used to classify the image input by the user to obtain the category of the image.

[0009] The present invention comprises the following steps:

[0010] The first step is to build a small sample image classification system based on weighted aggregation of textual cues. Figure 1 As shown in the figure, the small sample image classification system consists of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module.

[0011] The text prompt generation module is connected to the text feature extraction module. The text prompt generation module introduces existing large language models (such as GPT-3 (see the document "Tom Brown, et al. Language models are few-shot learners. Advances in neural information processing systems, 2020, 33: 1877-1901." Tom Brown et al.'s paper: Language models are small sample learners) and ChatGLM (see the document "Zeng, Aohan, et al. The Eleventh International Conference on Learning Representations. 2022." Zeng, Aohan et al.'s paper GLM-130B: Open bilingual pre-trained model)) as the prompt generation engine, and obtains category-related text prompts by designing question templates to inquire the large language model.Specifically, the text prompt generation module uses a large language model as the engine for text prompt generation and adopts 6 question templates (see the literature "Sarah Pratt, et al. What does a platypus look like? generating customized prompts for zero-shot image classification. In: Proceedings of the IEEE / CVF International Conference on Computer Vision. 2023. p. 15691-15701." Sarah Pratt et al.'s paper: What does a platypus look like? Generate customized prompts for zero-shot image classification; and "Menon Sachit, et al. Visual classification via description from large language models. arXiv preprint arXiv: 2210.07183 (2022)." Menon Sachit et al.'s paper: Visual classification via description from large language models): (1) "Describe what a(n){} looks like.", (2) "How can you identify a(n){}?", (3) "What does a(n){} look like?", (4) "A caption of an image of a(n){}.",(5)"Describe an image from the internet of a(n){}.",(6)"What are useful visual features for distinguishing a(n){}in a photo?"), and obtain rich text prompts by communicating with the large language model, and send the text prompts to the text feature extraction module.

[0012] The text feature extraction module is connected to the text prompt generation module, the confidence calculation module, and the soft weighting module. The text feature extraction module extracts features from the text prompts received from the text prompt generation module to obtain text features, sends the text features to the confidence calculation module for confidence calculation, and sends the text features to the soft weighting module to obtain a text classifier. The text feature extraction module uses the Transformer architecture for feature extraction, and its parameters use the parameters pre-trained in the Transformer architecture by CLIP (see the document "Alec Radford, et al. Learning transferable visual models from natural language supervision. International conference on machine learning. PMLR, 2021." Alec Radford et al.'s paper: Learning transferable visual models from natural language supervision). The Transformer architecture mainly consists of two parts: an encoder and a decoder. The encoder is used to understand the input sequence, while the decoder is used to generate the output sequence. Both the encoder and the decoder are stacked with multiple identical layers, usually 6 layers. Each layer contains two sub-layers: one is a multi-head self-attention module, which uses a self-attention mechanism to allow a large language model to focus on other elements in a sequence while processing an element of a sequence, thereby capturing the dependencies between them. The other is a fully connected layer, and the two sub-layers are connected via residuals. The use of Transformer can capture the dependencies between different positions in the input sequence and obtain global contextual information, making it particularly effective in semantic feature extraction. In addition, the self-attention module of Transformer allows the network to perform attention calculations between inputs at different positions. This calculation can be easily parallelized, which can improve computational efficiency.

[0013] The image feature extraction module is connected to the confidence calculation module and the main task module. During training, the image feature extraction module extracts the image features of the training set and sends the image features of the training set to the confidence calculation module to prepare for the confidence calculation and obtaining the hyperparameters; when verifying the accuracy of the hyperparameters, the image feature extraction module extracts the image features of the verification set and sends the image features of the verification set to the main task module; when classifying the image to be classified input by the user, the image features to be classified input by the user are sent to the main task module. The image feature extraction module uses ResNet (see the document "Kaiming He, et al. Deep Residual Learning for Image Recognition [J]. Proceedings of the IEEE conference on computer vision and pattern recognition. 2016: 770-778" Kaiming He et al.'s paper: Deep residual learning for image recognition) or ViT (Vision Transformer) (see the document "Dosovitskiy Alexey, et al. An image is worth 16x16 words: Transformers for image recognition at scale. arXiv: 2010.11929 (2020)." Dosovitskiy Alexey et al.'s paper: An image is worth 16x16 words: Transformers for scale image recognition), both of which can effectively extract image features. The ResNet network is constructed by stacking a series of residual blocks, which are composed of convolutional layers and normalization layers. Depending on the depth of the network, variants of the ResNet network (such as ResNet50, ResNet101, and other networks) are often used in specific applications; the core idea of ​​ViT is to divide the image into a series of small patches, and then treat these small patches as sequence data and process them through the Transformer model. In specific applications, variants of the ViT network, such as ViT-B / 32, ViT-B / 16, and ViT-L / 14, are often used. The ResNet network has smaller parameters, shorter training time, and better feature extraction capabilities; the ViT network has more parameters, longer training time, and better feature extraction capabilities.In the present invention, according to specific scenarios and requirements, any one of the networks including ResNet50, ResNet101, ViT-B / 32, ViT-B / 16 and ViT-L / 14 (a variant model of ViT, B represents the base model, L represents the Large model; 16 represents that the input is a small block of 16×16 pixels) trained on 400 million image-text pairs can be used as an image feature extraction module for CLIP.

[0014] The confidence calculation module is connected to the image feature extraction module, the text feature extraction module, and the soft weighting module. Its function is to calculate the confidence score of each text prompt. By using the mutual supervision relationship between text and image in the same feature space, the confidence score is calculated for the text features obtained from the text feature extraction module and the image features obtained from the image feature extraction module to measure the quality of each text. Specifically, firstly, the images of the same category n are screened (using the set express and text (with collection express, K represents the number of small samples used in this invention, usually K∈{1,2,4,8,16}; secondly, for category n, use Respectively Confidence calculation is performed and summed to obtain the confidence score S corresponding to the kth text prompt; similarly, the confidence calculation module performs the same operation on all categories in the small sample image classification scene dataset and sends the final confidence score to the soft weighting module.

[0015] The soft weighting module is connected to the text feature extraction module, the confidence calculation module and the main task module. Its function is to further screen the text prompt features obtained from the text feature extraction module, and perform weighted aggregation on the text prompt features according to the confidence score to obtain the text classifier set W. C , the temperature coefficient t, the truncation factor l and the corresponding text classifier set W C Save it as a set of hyperparameters and send the text classifier in the hyperparameters to the main task module.

[0016] The main task module is connected to the image feature extraction module and the soft weighting module. It receives the text classifier from the soft weighting module. When verifying the accuracy of the hyperparameters, it receives the verification set image features from the image feature extraction module, and uses the verification set image features to test the text classifier to obtain the optimal text classifier. When classifying the image to be classified input by the user, it receives the features of the image to be classified input by the user from the image feature extraction module, and uses the optimal text classifier to classify the image to obtain the classification result.

[0017] The second step is to construct the training set, validation set, and test set by:

[0018] 2.1 Collect small sample scene images as small sample image classification scene dataset, the method is:

[0019] We use the general scene dataset ImageNet (see the paper "Jia Deng, et al. ImageNet: A Large-Scale Hierarchical Image Database [A]. 2009 IEEE Conference on Computer Vision and Pattern Recognition [C], 2009" Jia Deng et al.'s paper: Imgenet: A Large-Scale Hierarchical Image Database), the food dataset Food101 (see the paper "BOSSARD, Lukas, et al. Food-101—mining discriminative components with random forests. In: Computer Vision–ECCV 2014: 6-12, 2014. p. 446-461." BOSSARD, Lukas et al.'s paper: Food101: Random Forest Mining Discriminative Components), and the remote sensing image dataset Eurosat (see the paper "Patrick Helber, et al. Eurosat: A novel dataset and deep learning benchmark for land use and land cover classification (Article) [J]. IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, 2019, Vol. 12 (7): 2217-2226” Patrick Helber et al.’s paper: Eurosat: A new dataset and deep learning benchmark for land use and land cover classification), texture dataset DTD (see the literature “Mircea Cimpoi, et al. Describing Textures in the Wild [A]. 27th IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2014) [C], 2014” Mircea Cimpoi et al.’s paper: Describing Textures in the Wild), flower dataset Flowers102 (see the literature “Nilsback, et al. Automated Flower Classification over a Large Number of Classes [A].2008Sixth Indian Conference on Computer Vision, Graphics & Image Processing [C], 2008" Nilsback et al.'s paper: Automatic classification of a large number of categories of flowers), car dataset Stanford Cars (see the paper "Jonathan Krause, et al. 3D Object Representations for Fine-Grained Categorization [A]. 2013 IEEE International Conference on Computer Vision Workshops [C], 2013" Jonathan Krause et al.'s paper: 3D object representation for fine-grained classification), action dataset UCF101 (see the paper "Khurram Soomro, et al. UCF101: A Dataset of 101 Human Actions Classes From Videos in The Wild [J]. 2012" Khurram Soomro et al.'s paper: UCF101: A Dataset of 101 Human Actions Classes From Videos in The Wild [J]. 2012), object recognition dataset Caltech101 (see the paper "Li Fei-Fei, et al. Learning generative visual models from few training examples: An incremental Bayesian approach tested on 101 object categories [J]. Computer Vision and Image Understanding, 2007, Vol. 106 (1): 59-70 "Li Fei-Fei et al.'s paper: Learning to generate visual models from a small number of training samples: an incremental Bayesian approach tested on 101 object categories", scene classification dataset SUN397 (see the paper "Xiao Jianxiong, et al. SUN database: Large-scale scene recognition from abbey to zoo [A]. 2010" Xiao Jianxiong et al.'s paper: SUN dataset: Large-scale scene recognition from abbey to zoo [A]. 2010), aircraft classification dataset Aircraft (see the paper "Subhransu Maji, et al.There are 11 datasets as small sample image classification datasets, including Fine-Grained Visual Classification of Aircraft[J].2013" Subhransu Maji et al.'s paper: Fine-Grained Visual Classification of Aircraft[J].2013), pet classification dataset OxfordPets (see the document "CVJawahar,et al.Cats and dogs[A].2012IEEE Conference on Computer Vision and Pattern Recognition[C],2012" CVJawahar et al.'s document: Cats and Dogs). Each image in these 11 datasets is manually annotated, that is, each image is annotated with the category of the object and its corresponding true label.

[0020] 2.2 According to the dataset division file commonly used by researchers, the small sample image classification scene dataset is divided into training set D train , validation set D val , test set D test For example, the Food101 dataset is divided as follows: the total number of images in the training set is S (S = 101,000*5 / 10 = 50500), the total number of images in the validation set is V (V = 101,000*2 / 10 = 20200), and the total number of images in the test set is T (T = 101,000*3 / 10 = 30300).

[0021] 2.3 According to the number of samples K of each category set in the small sample image classification, from the training set D train Randomly sample K images from each category in to construct a list, and add this list to the new training set D′ train , D′ rain Contains N lists (N is the number of categories in the dataset), each list has K images. The method is:

[0022] 2.3.1 Let category n = 1 and create an empty training set D′ train Used to store sampled images;

[0023] 2.3.2 Create a list dataset to store the filtered n-th category images n =[];

[0024] 2.3.3 Find the training set D train To find images belonging to the nth category in the training set (i.e., find images with the same labels as n in the training set), do the following:

[0025] 2.3.3.1 If the number of images num in the nth category ≥ K, randomly select K images from the images in the nth category (at this time, no images among the K images are repeated), and go to 2.3.3.3;

[0026] 2.3.3.2 If the number of images num in the nth category < K, randomly select K images from the images in the nth category repeatedly (at this time, some images among the K images are repeated), and go to 2.3.3.3;

[0027] 2.3.3.3 Add the selected K images to dataset n ;

[0028] 2.3.3.4 Add dataset n to D′ train ;

[0029] 2.3.3.5 If n < N, let n = n + 1, and go to 2.3.2; if n ≥ N, obtain the final training set D′ train , D′ train = {dataset1, …, dataset n , …, dataset N}, and go to the third step.

[0030] Third step, construct diverse text prompts by:

[0031] 3.1 Obtain 6 question templates: Obtain 5 question templates (i.e., (1) to (5)) from CUPL (see the document "Sarah Pratt, et al. What does a platypus look like? Generating customized prompts for zero-shot image classification. In: Proceedings of the IEEE / CVF International Conference on Computer Vision. 2023. p. 15691-15701." Sarah Pratt et al.'s paper: What does a platypus look like? Generate customized prompts for zero-shot image classification.) and obtain 1 question template (the (6)) from the feature-related text prompt template of CBD (see the document "Menon Sachit, and Carl Vondrick. Visual classification via description from large language models. arXiv preprint arXiv: 2210.07183 (2022)." Menon Sachit et al.'s paper: Visual classification via description from large language models). The specific templates are as follows:

[0032] (1)“Describe what a(n){}looks like.”,

[0033] (2)"How can you identify a(n){}?",

[0034] (3) "What does a(n){}look like?",

[0035] (4)"Acaption of an image of a(n){}.",

[0036] (5) "Describe an image from the internet of a(n){}.",

[0037] (6) "What are useful visual features for distinguishing a(n){}in aphoto?".

[0038] It can be seen that the six question templates are numbered (1) to (6), and “{}” is used in the templates to represent replaceable category names.

[0039] 3.2 Set the category number n = 1 and initialize the text prompt dictionary P = {};

[0040] 3.3 Set the template number m = 1 and initialize the text prompt list L n = [];

[0041] 3.4 According to the category name class of the label corresponding to the nth category n , replace the "{}" in the mth template in step 3.1 with the category name class n (e.g., "dog") to obtain the mth question template Q m ;

[0042] 3.5 The text prompt generation module inputs the question template Q m into a large language model (such as GPT-3 or ChatGLM), obtains the corresponding text prompts from the large language model (including 5 - 10 text prompts), and adds these text prompts to the text prompt list L corresponding to the nth category n ;

[0043] 3.6 If m < 6, set m = m + 1 and go to 3.4; if m ≥ 6, go to 3.7;

[0044] 3.7 Combine the category name class of the label corresponding to the nth category n and the text prompt list L corresponding to this category n to form a key-value pair "class n :L n ", where class n is the key and L n is the value, and add "class n :L n " to the dictionary P;

[0045] 3.8 If n < N, set n = n + 1 and go to 3.3; if n ≥ N, go to 3.9;

[0046] 3.9 At this time, the text prompts for all N categories have been generated, and the final text prompt dictionary P is obtained, P = {class1:L1,...,class n :L n ,...,class N :L N}.

[0047] Step 4: Use the training set to train the few-shot image classification system based on text prompt weighted aggregation constructed in step 1 to obtain N m groups of hyperparameters, N m = 80. The method is:

[0048] 4.1 Initialize the model parameters of each module in the small sample image classification system. Use the pre-trained model CLIP to initialize the parameters of the Transformer in the text feature extraction module and the parameters of the ResNet or ViT in the image feature extraction module;

[0049] 4.2 Initialize the text classifier set W C = [], initialize the hyperparameter truncation factor l = 0.3;

[0050] 4.3 Let batch number b = 1, indicating the bth image batch, each batch has B = 256 images, and the total number of batches is N B

[0051] 4.4 Image feature extraction module from training set D′ train Read the B images of the bth batch, recorded as matrix form I train , I train It contains B H×W×3 images. H represents the height of the input image, W represents the width of the input image, and “3” represents the RGB channels of the image. B represents the number of images in a batch.

[0052] 4.5 Image feature extraction module uses image feature extraction method to filter out K image samples I of the category according to the category label n K (is a list of K images), extract I K The image feature f v (is a tensor with dimension (B, D), where D is the feature dimension), f v Send to the confidence calculation module;

[0053] 4.6 Text feature extraction module According to the category name class corresponding to the category label n n , from the text prompt dictionary P obtained in step 3.9, take out the words belonging to class n Text prompt list L n (is a list of M text prompts), using the Transformer network to extract L n The text prompt feature f t (is a tensor with dimension (M, D), where D is the feature dimension), f t Send to the confidence calculation module and the soft weighting module;

[0054] 4.7 The confidence calculation module receives the image feature f from the image feature extraction module v and the text hint feature f from the text feature extraction module t , calculate the confidence score to obtain the confidence score S. Specifically, as shown in formula (1):

[0055] S= <f v ·f t T > Formula (1)

[0056] Where <·> means calculating the inner product between two vectors and sending the confidence score S (dimension is (K, M)) to the soft weighting module;

[0057] 4.8 The soft weighting module sums the first dimension of the confidence score S to obtain the summed confidence score S1 (dimension M), and then sorts S1 from high to low to obtain the sorted confidence score S2 (dimension M). The hyperparameter cutoff factor l is used to filter the top confidence scores from S2. A confidence score S′ with a higher confidence level (dimension is ). The soft weighting module receives the text prompt features from the text feature extraction module and indexes the text prompt features f corresponding to S′ t ′, (i.e. find the corresponding text prompt according to the sequence number of the text prompt feature corresponding to the score), initialize the hyperparameter temperature coefficient t=1;

[0058] 4.9 The soft weighting module uses the hyperparameter temperature coefficient t to multiply the confidence score S′ to sharpen the confidence score to obtain the sharpened confidence score S″;

[0059] S″=S′·t Formula (2)

[0060] 4.10 The soft weighting module uses the softmax function to weight the text prompt feature f according to the sharpened confidence score S″ t ′ is weighted aggregation to obtain the text prompt feature W of the bth batch b , the specific process is shown in formula (3):

[0061] W b = <f t ′·softmax(S″)> Formula (3)

[0062] 4.11 The text prompt feature W at this time b Add to the text classifier set W C .

[0063] 4.12 If b <N B , let b=b+1, go to 4.4; if b≥N B , description text classifier set W C (It is a tensor with dimension (N, D), where D is the feature dimension) Construction is complete, go to 4.13;

[0064] 4.13 The temperature coefficient t, the truncation factor l and the corresponding text classifier set W at this time C Saved as a set of hyperparameters.

[0065] 4.14 If t<10, let t=t+1 and go to 4.9; if t≥10, go to 4.15;

[0066] 4.15 If l<1, let l=l+0.1 and go to 4.8; if l≥1, go to 4.16;

[0067] 4.16 Now we get N m (80) set of hyperparameters for validation set D val The soft weighting module will N m The text classifier in the group hyperparameters is sent to the main task module.

[0068] In the fifth step, the main task module uses the validation set to verify the accuracy of the hyperparameters obtained in the fourth step, retains the best performing hyperparameters as the hyperparameters of the small sample image classification system based on text prompt weighted aggregation, and obtains the best text classifier. and a trained few-shot image classification system based on weighted aggregation of textual cues by:

[0069] 5.1 Let variable n m =1, let the total number of correct classifications total_correct = 0;

[0070] 5.2 Main task module from N m Take the nth m The group hyperparameters l, t and corresponding W C , and read the verification set D val ;

[0071] 5.3 Let batch number c = 1, indicating the cth batch. Each batch contains B′ = 64 validation set images, and the total number of batches is N. C Let the total number of correct classifications total_correct = 0;

[0072] 5.4 Take out the B′=64 images of the validation set from the cth batch and record these B′ images in matrix form I val , I val contains B′ H×W×3 images;

[0073] 5.5 The image feature extraction module receives B′ validation set D val Image I val , use the ResNet or ViT network initialized in step 4.1 to extract I val The image feature f val(is a tensor with dimension (B′, D), where D is the feature dimension), and the validation set image feature f val Send to the main task module;

[0074] 5.6 Main Task Module Using Text Classifier W C and the validation set image features f val Perform similarity calculation to obtain the predicted probabilities of N categories logits (a tensor with dimension (B′, N)). The specific process is shown in formula (4):

[0075] logits= <f val ·W C T > Formula (4)

[0076] The category corresponding to the maximum value of the second dimension in logits is the final prediction result;

[0077] 5.7 Determine whether the predicted result is the same as the true label when the data set was obtained in step 2.1. If they are the same, it is a correct classification. The number of correct classifications is recorded as correct and go to 5.8. If they are not the same, go directly to 5.8.

[0078] 5.8 Add the correct number to the total number of correct classifications in the validation set, total_correct. The specific process is shown in formula (5):

[0079] total_correct=total_correct+correct formula (5)

[0080] 5.9 If c <N C , let c=c+1, go to 5.4; if c≥N C , indicating that the verification is complete, go to 5.10;

[0081] 5.10 Calculate the classification accuracy acc. The specific process is shown in formula (6):

[0082]

[0083] Where V is the number of images in the validation set.

[0084] 5.11 If n m <N m , let n m =n m +1, go to 5.2; if n m ≥N m , indicating that all hyperparameter combinations have been verified, go to 5.12;

[0085] 5.12 to N mThe accuracy of the hyperparameters is compared, and the hyperparameter with the highest accuracy is found. The hyperparameter (containing the best text prompt feature, i.e., the text classifier) ​​is ) as the hyperparameter selected by the small sample image classification system based on text prompt weighted aggregation, and the selected hyperparameter is loaded into the small sample image classification system based on text prompt weighted aggregation. The small sample image classification system based on text prompt weighted aggregation loaded with the selected hyperparameter becomes the trained small sample image classification system based on text prompt weighted aggregation. At this time, the main task module loads the optimal text classifier

[0086] The sixth step is to use the trained small sample image classification system based on text prompt weighted aggregation to classify the image to be classified input by the user to obtain the prediction result of the image to be classified. The method is:

[0087] 6.1 The image feature extraction module receives the image set I to be classified as input by the user test , I test The number of images in is N test ;

[0088] 6.2 Image Feature Extraction Module Extraction I test The image feature f test ;

[0089] 6.3 The main task module loads the optimal text classifier obtained in step 5.12 With the test set image features f test Perform similarity calculation to obtain the predicted probability of N categories logits_test (is a tensor with dimension (N test ,N)), the specific process is shown in formula (7):

[0090]

[0091] The category corresponding to the maximum value of the second dimension in logits_test is the prediction result of the image to be classified, and the image classification is completed.

[0092] The present invention can achieve the following beneficial effects:

[0093] The present invention proposes a small sample image classification method based on text prompt weighted aggregation. The present invention uses the rich knowledge and inductive ability of the pre-trained CLIP model to quickly learn new knowledge and realize the classification of new categories. It is suitable for most small sample image classification based on large models. The following effects can be achieved by using the present invention:

[0094] 1. The present invention constructs a small sample image classification system that integrates a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module, introduces a variety of text prompts generated by a large language model, and uses the rich knowledge and inductive ability of the visual-language large model, as well as the mutual supervision relationship between image and text features in the feature space of the visual-language large model, to design a small sample image classification method for weighted aggregation of text prompts that does not require training, uses the confidence calculation module to apply confidence scores to text prompts, and performs weighted aggregation on text prompts according to the confidence scores (see 4.10 for details), thereby improving the robustness of the text classifier and achieving a significant improvement in detection accuracy. The present invention is experimented with 11 data sets such as ImageNet, Food101, and Eurosat, and the present invention is compared with three methods, CaFo, Tip-Adapter-F, and CALIP-FS. The classification accuracy of the present invention is greatly improved compared with the above three methods.

[0095] 2. The text prompt generation module of the present invention utilizes a large language model to enhance the diversified text prompts. On this basis, the confidence calculation module utilizes the visual-language model CLIP to calculate the confidence score of the text prompt in step 4 (see 4.7 for details) to measure the quality of the text prompt; the soft weighting module performs weighted aggregation on the text prompts according to the confidence score in step 4 (see 4.10 for details), assigning higher weights to high-quality text prompts, alleviating the problem that the text prompt classifier is not robust enough, obtaining a more robust text classifier, and greatly improving the classification accuracy. BRIEF DESCRIPTION OF THE DRAWINGS

[0096] Figure 1 The logical structure diagram of the small sample image classification system constructed in the first step of the present invention.

[0097] Figure 2 It is the overall flow chart of the present invention.

[0098] Figure 3 It is a comparison chart of the classification results of the present invention and the results of the CaFo, Tip-Adapter-F, and CALIP-FS methods. Figure 3 (a)-(j) are the performance comparison diagrams of the present invention with the small sample image classification methods CaFo, Tip-Adapter-F and CALIP-FS on 10 datasets including StanfordCars, UCF101, Caltech101, Flowers102, SUN397, DTD, EuroSAT, FGVCAircraft, OxfordPets and Food101, respectively. The horizontal axis is the number of samples in each category and the vertical axis is the classification accuracy. DETAILED DESCRIPTION

[0099] The following is a description of specific examples of the present invention in conjunction with the accompanying drawings. Figure 2 As shown, the present invention comprises the following steps:

[0100] The first step is to build a small sample image classification system based on weighted aggregation of textual cues. Figure 1 As shown in the figure, the small sample image classification system consists of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module.

[0101] The text prompt generation module is connected to the text feature extraction module. The text prompt generation module introduces existing large language models (such as GPT-3 (see the document "Tom Brown, et al. Language models are few-shot learners. Advances in neural information processing systems, 2020, 33: 1877-1901." Tom Brown et al.'s paper: Language models are small sample learners) and ChatGLM (see the document "Zeng, Aohan, et al. The Eleventh International Conference on Learning Representations. 2022." Zeng, Aohan et al.'s paper GLM-130B: Open bilingual pre-trained model)) as the prompt generation engine, and obtains category-related text prompts by designing question templates to inquire the large language model.Specifically, the text prompt generation module uses a large language model as the engine for text prompt generation and adopts 6 question templates (see the literature "Sarah Pratt, et al. What does a platypus look like? Generating customized prompts for zero-shot image classification. In: Proceedings of the IEEE / CVF International Conference on Computer Vision. 2023. p. 15691-15701." Sarah Pratt et al.'s paper: What does a platypus look like? Generate customized prompts for zero-shot image classification; and "Menon Sachit, et al. Visual classification via description from large language models. arXiv preprint arXiv: 2210.07183 (2022)." Menon Sachit et al.'s paper: Visual classification via description from large language models): (1) "Describe what a(n){} looks like.", (2) "How can you identify a(n){}?", (3) "What does a(n){}look like?" like?", (4) "A caption of an image of a(n){}.", (5) "Describe an image from the internet of a(n){}.", (6) "What are useful visual features for distinguishing a(n){}in a photo?"), and obtain rich text prompts by communicating with the large language model, and send the text prompts to the text feature extraction module.

[0102] The text feature extraction module is connected to the text prompt generation module, the confidence calculation module, and the soft weighting module. The text feature extraction module extracts features from the text prompts received from the text prompt generation module to obtain text features, sends the text features to the confidence calculation module for confidence calculation, and sends the text features to the soft weighting module to obtain a text classifier. The text feature extraction module uses the Transformer architecture for feature extraction, and its parameters use the parameters pre-trained in the Transformer architecture by CLIP (see the document "Alec Radford, et al. Learning transferable visual models from natural language supervision. International conference on machine learning. PMLR, 2021." Alec Radford et al.'s paper: Learning transferable visual models from natural language supervision). The Transformer architecture mainly consists of two parts: an encoder and a decoder. The encoder is used to understand the input sequence, while the decoder is used to generate the output sequence. Both the encoder and the decoder are stacked with multiple identical layers, usually 6 layers. Each layer contains two sub-layers: one is a multi-head self-attention module, which uses a self-attention mechanism to allow a large language model to focus on other elements in a sequence while processing an element of a sequence, thereby capturing the dependencies between them. The other is a fully connected layer, and the two sub-layers are connected via residuals. The use of Transformer can capture the dependencies between different positions in the input sequence and obtain global contextual information, making it particularly effective in semantic feature extraction. In addition, the self-attention module of Transformer allows the network to perform attention calculations between inputs at different positions. This calculation can be easily parallelized, which can improve computational efficiency.

[0103] The image feature extraction module is connected to the confidence calculation module and the main task module. During training, the image feature extraction module extracts the image features of the training set and sends the image features of the training set to the confidence calculation module to prepare for the confidence calculation and obtaining the hyperparameters; when verifying the accuracy of the hyperparameters, the image feature extraction module extracts the image features of the verification set and sends the image features of the verification set to the main task module; when classifying the image to be classified input by the user, the image features to be classified input by the user are sent to the main task module. The image feature extraction module uses ResNet (see the document "Kaiming He, et al. Deep Residual Learning for Image Recognition [J]. Proceedings of the IEEE conference on computer vision and pattern recognition. 2016: 770-778" Kaiming He et al.'s paper: Deep residual learning for image recognition) or ViT (Vision Transformer) (see the document "Dosovitskiy Alexey, et al. An image is worth 16x16 words: Transformers for image recognition at scale. arXiv: 2010.11929 (2020)." Dosovitskiy Alexey et al.'s paper: An image is worth 16x16 words: Transformers for scale image recognition), both of which can effectively extract image features. The ResNet network is constructed by stacking a series of residual blocks, which are composed of convolutional layers and normalization layers. Depending on the depth of the network, variants of the ResNet network (such as ResNet50, ResNet101, and other networks) are often used in specific applications; the core idea of ​​ViT is to divide the image into a series of small patches, and then treat these small patches as sequence data and process them through the Transformer model. In specific applications, variants of the ViT network, such as ViT-B / 32, ViT-B / 16, and ViT-L / 14, are often used. The ResNet network has smaller parameters, shorter training time, and better feature extraction capabilities; the ViT network has more parameters, longer training time, and better feature extraction capabilities.In the present invention, according to specific scenarios and requirements, any one of the networks including ResNet50, ResNet101, ViT-B / 32, ViT-B / 16 and ViT-L / 14 (a variant model of ViT, B represents the base model, L represents the Large model; 16 represents that the input is a small block of 16×16 pixels) trained on 400 million image-text pairs can be used as an image feature extraction module for CLIP.

[0104] The confidence calculation module is connected to the image feature extraction module, the text feature extraction module, and the soft weighting module. Its function is to calculate the confidence score of each text prompt. By using the mutual supervision relationship between text and image in the same feature space, the confidence score is calculated for the text features obtained from the text feature extraction module and the image features obtained from the image feature extraction module to measure the quality of each text. Specifically, firstly, the images of the same category n are screened (using the set express and text (with collection express, K represents the number of small samples used in this invention, usually K∈{1,2,4,8,16}; secondly, for category n, use Respectively Confidence calculation is performed and summed to obtain the confidence score S corresponding to the kth text prompt; similarly, the confidence calculation module performs the same operation on all categories in the small sample image classification scene dataset and sends the final confidence score to the soft weighting module.

[0105] The soft weighting module is connected to the text feature extraction module, the confidence calculation module and the main task module. Its function is to further screen the text prompt features obtained from the text feature extraction module, and perform weighted aggregation on the text prompt features according to the confidence score to obtain the text classifier set W. C , the temperature coefficient t, the truncation factor l and the corresponding text classifier set W C Save it as a set of hyperparameters and send the text classifier in the hyperparameters to the main task module.

[0106] The main task module is connected to the image feature extraction module and the soft weighting module. It receives the text classifier from the soft weighting module. When verifying the accuracy of the hyperparameters, it receives the verification set image features from the image feature extraction module, and uses the verification set image features to test the text classifier to obtain the optimal text classifier. When classifying the image to be classified input by the user, it receives the features of the image to be classified input by the user from the image feature extraction module, and uses the optimal text classifier to classify the image to obtain the classification result.

[0107] The second step is to construct the training set, validation set, and test set by:

[0108] 2.1 Collect small sample scene images as small sample image classification scene dataset, the method is:

[0109] We use the general scene dataset ImageNet (see the paper "Jia Deng, et al. ImageNet: A Large-Scale Hierarchical Image Database [A]. 2009 IEEE Conference on Computer Vision and Pattern Recognition [C], 2009" Jia Deng et al.'s paper: Imgenet: A Large-Scale Hierarchical Image Database), the food dataset Food101 (see the paper "BOSSARD, Lukas, et al. Food-101—mining discriminative components with random forests. In: Computer Vision–ECCV 2014: 6-12, 2014. p. 446-461." BOSSARD, Lukas et al.'s paper: Food101: Random Forest Mining Discriminative Components), and the remote sensing image dataset Eurosat (see the paper "Patrick Helber, et al. Eurosat: A novel dataset and deep learning benchmark for land use and land cover classification (Article) [J]. IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, 2019, Vol. 12 (7): 2217-2226” Patrick Helber et al.’s paper: Eurosat: A new dataset and deep learning benchmark for land use and land cover classification), texture dataset DTD (see the literature “Mircea Cimpoi, et al. Describing Textures in the Wild [A]. 27th IEEE Conference on Computer Vision and Pattern Recognition (CVPR 2014) [C], 2014” Mircea Cimpoi et al.’s paper: Describing Textures in the Wild), flower dataset Flowers102 (see the literature “Nilsback, et al. Automated Flower Classification over a Large Number of Classes [A].2008Sixth Indian Conference on Computer Vision, Graphics & Image Processing [C], 2008" Nilsback et al.'s paper: Automatic classification of a large number of categories of flowers), car dataset Stanford Cars (see the paper "Jonathan Krause, et al. 3D Object Representations for Fine-Grained Categorization [A]. 2013IEEE International Conference on Computer Vision Workshops [C], 2013" Jonathan Krause et al.'s paper: 3D object representation for fine-grained classification), action dataset UCF101 (see the paper "Khurram Soomro, et al. UCF101: A Dataset of 101 Human Actions Classes From Videos in The Wild [J]. 2012" Khurram Soomro et al.'s paper: UCF101: A Dataset of 101 Human Actions Classes From Videos in The Wild [J]. 2012), object recognition dataset Caltech101 (see the paper "Li Fei-Fei, et al. Learning generative visual models from few training examples: An incremental Bayesian approach tested on 101 object categories [J]. Computer Vision and Image Understanding, 2007, Vol. 106 (1): 59-70 "Li Fei-Fei et al.'s paper: Learning to generate visual models from a small number of training samples: an incremental Bayesian approach tested on 101 object categories", scene classification dataset SUN397 (see the paper "Xiao Jianxiong, et al. SUN database: Large-scale scene recognition from abbey to zoo [A]. 2010" Xiao Jianxiong et al.'s paper: SUN dataset: Large-scale scene recognition from abbey to zoo [A]. 2010), aircraft classification dataset Aircraft (see the paper "Subhransu Maji, et al.There are 11 datasets as small sample image classification datasets, including Fine-Grained Visual Classification of Aircraft[J].2013" Subhransu Maji et al.'s paper: Fine-Grained Visual Classification of Aircraft[J].2013), pet classification dataset OxfordPets (see the document "CVJawahar,et al.Cats and dogs[A].2012IEEE Conference on Computer Vision and Pattern Recognition[C],2012" CVJawahar et al.'s document: Cats and Dogs). Each image in these 11 datasets is manually annotated, that is, each image is annotated with the category of the object and its corresponding true label.

[0110] 2.2 According to the dataset division file commonly used by researchers, the small sample image classification scene dataset is divided into training set D train , validation set D val , test set D test For example, the Food101 dataset is divided as follows: the total number of images in the training set is S (S = 101,000*5 / 10 = 50500), the total number of images in the validation set is V (V = 101,000*2 / 10 = 20200), and the total number of images in the test set is T (T = 101,000*3 / 10 = 30300).

[0111] 2.3 According to the number of samples K of each category set in the small sample image classification, from the training set D train Randomly sample K images from each category in to construct a list, and add this list to the new training set D′ train , D′ train Contains N lists (N is the number of categories in the dataset), each list has K images. The method is:

[0112] 2.3.1 Let category n = 1 and create an empty training set D′ train Used to store sampled images;

[0113] 2.3.2 Create a list dataset to store the filtered n-th category images n =[];

[0114] 2.3.3 Find the training set D train To find images belonging to the nth category in the training set (i.e., find images with the same labels as n in the training set), do the following:

[0115] 2.3.3.1 If the number of images num in the n-th category ≥ K, randomly select K images from the images in the n-th category (at this time, no images among the K images are repeated), go to 2.3.3.3;

[0116] 2.3.3.2 If the number of images num in the n-th category < K, randomly select K images from the images in the n-th category repeatedly (at this time, some images among the K images are repeated), go to 2.3.3.3;

[0117] 2.3.3.3 Add the selected K images to dataset n ;

[0118] 2.3.3.4 Add dataset n to D′ train ;

[0119] 2.3.3.5 If n < N, let n = n + 1, go to 2.3.2; if n ≥ N, obtain the final training set D′ train , D′ train = {dataset1, …, dataset n , …, dataset N}, go to the third step.

[0120] Third step, construct diverse text prompts by:

[0121] 3.1 Obtain 6 question templates: Obtain 5 question templates (i.e., (1) to (5)) from CUPL (see the document "Sarah Pratt, et al. What does a platypus look like? Generating customized prompts for zero-shot image classification. In: Proceedings of the IEEE / CVF International Conference on Computer Vision. 2023. p. 15691-15701." Sarah Pratt et al.'s paper: What does a platypus look like? Generate customized prompts for zero-shot image classification.) and obtain 1 question template (the (6)) from the feature-related text prompt template of CBD (see the document "Menon Sachit, and Carl Vondrick. Visual classification via description from large language models. arXiv preprint arXiv: 2210.07183 (2022)." Menon Sachit et al.'s paper: Visual classification via description from large language models). The specific templates are as follows:

[0122] (1)“Describe what a(n){}looks like.”,

[0123] (2)"How can you identify a(n){}?",

[0124] (3) "What does a(n){}look like?",

[0125] (4)“A caption of an image of a(n){}.”,

[0126] (5) "Describe an image from the internet of a(n){}.",

[0127] (6) "What are useful visual features for distinguishing a(n){}in aphoto?".

[0128] It can be seen that the six question templates are numbered (1) to (6), and “{}” is used in the templates to represent replaceable category names.

[0129] 3.2 Set the category number n = 1 and initialize the text prompt dictionary P = {};

[0130] 3.3 Set the template number m = 1 and initialize the text prompt list L n = [];

[0131] 3.4 According to the category name class of the label corresponding to the nth category n , replace the "{}" in the mth template in step 3.1 with the category name class n (e.g., "dog") to obtain the mth question template Q m ;

[0132] 3.5 The text prompt generation module inputs the question template Q m into a large language model (such as GPT-3 or ChatGLM), obtains the corresponding text prompts from the large language model (including 5-10 text prompts), and adds these text prompts to the text prompt list L corresponding to the nth category n ;

[0133] 3.6 If m < 6, set m = m + 1 and go to 3.4; if m ≥ 6, go to 3.7;

[0134] 3.7 Combine the category name class of the label corresponding to the nth category n and the text prompt list L corresponding to this category n to form a key-value pair "class n :L n ", where class n is the key and L n is the value, and add "class n :L n " to the dictionary P;

[0135] 3.8 If n < N, set n = n + 1 and go to 3.3; if n ≥ N, go to 3.9;

[0136] 3.9 At this time, the text prompts for all N categories have been generated, and the final text prompt dictionary P is obtained, P = {class1:L1,…,class n :L n ,…,class N :L N}.

[0137] Fourth, use the training set to train the few-shot image classification system based on text prompt weighted aggregation constructed in the first step to obtain N m groups of hyperparameters, N m = 80. The method is:

[0138] 4.1 Initialize the model parameters of each module in the small sample image classification system. Use the pre-trained model CLIP to initialize the parameters of the Transformer in the text feature extraction module and the parameters of the ResNet or ViT in the image feature extraction module;

[0139] 4.2 Initialize the text classifier set W C = [], initialize the hyperparameter truncation factor l = 0.3;

[0140] 4.3 Let batch number b = 1, indicating the bth image batch, each batch has B = 256 images, and the total number of batches is N B

[0141] 4.4 Image feature extraction module from training set D′ train Read the B images of the bth batch, recorded as matrix form I train , I train It contains B H×W×3 images. H represents the height of the input image, W represents the width of the input image, and “3” represents the RGB channels of the image. B represents the number of images in a batch.

[0142] 4.5 Image feature extraction module uses image feature extraction method to filter out K image samples I of the category according to the category label n K (is a list of K images), extract I K The image feature f v (is a tensor with dimension (B, D), where D is the feature dimension), f v Send to the confidence calculation module;

[0143] 4.6 Text feature extraction module According to the category name class corresponding to the category label n n , from the text prompt dictionary P obtained in step 3.9, take out the words belonging to class n Text prompt list L n (is a list of M text prompts), using the Transformer network to extract L n The text prompt feature f t (is a tensor with dimension (M, D), where D is the feature dimension), f t Send to the confidence calculation module and the soft weighting module;

[0144] 4.7 The confidence calculation module receives the image feature f from the image feature extraction module v and the text hint feature f from the text feature extraction module t , calculate the confidence score to obtain the confidence score S. Specifically, as shown in formula (1):

[0145] S= <f v ·f t T > Formula (1)

[0146] Where <·> means calculating the inner product between two vectors and sending the confidence score S (dimension is (K, M)) to the soft weighting module;

[0147] 4.8 The soft weighting module sums the first dimension of the confidence score S to obtain the summed confidence score S1 (dimension M), and then sorts S1 from high to low to obtain the sorted confidence score S2 (dimension M). The hyperparameter cutoff factor l is used to filter the top confidence scores from S2. A confidence score S′ with a higher confidence level (dimension is ). The soft weighting module receives the text prompt features from the text feature extraction module and indexes the text prompt features f corresponding to S′ t ′, (i.e. find the corresponding text prompt according to the sequence number of the text prompt feature corresponding to the score), initialize the hyperparameter temperature coefficient t=1;

[0148] 4.9 The soft weighting module uses the hyperparameter temperature coefficient t to multiply the confidence score S′ to sharpen the confidence score to obtain the sharpened confidence score S″;

[0149] S″=S′·t Formula (2)

[0150] 4.10 The soft weighting module uses the softmax function to weight the text prompt feature f according to the sharpened confidence score S″ t ′ is weighted aggregation to obtain the text prompt feature W of the bth batch b , the specific process is shown in formula (3):

[0151] W b = <f t ′·softmax(S″)> Formula (3)

[0152] 4.11 The text prompt feature W at this time b Add to the text classifier set W C .

[0153] 4.12 If b <N B , let b=b+1, go to 4.4; if b≥N B , description text classifier set W C (It is a tensor with dimension (N, D), where D is the feature dimension) Construction is complete, go to 4.13;

[0154] 4.13 The temperature coefficient t, the truncation factor l and the corresponding text classifier set W at this time C Saved as a set of hyperparameters.

[0155] 4.14 If t<10, let t=t+1 and go to 4.9; if t≥10, go to 4.15;

[0156] 4.15 If l<1, let l=l+0.1 and go to 4.8; if l≥1, go to 4.16;

[0157] 4.16 Now we get N m (80) set of hyperparameters for validation set D val The soft weighting module will N m The text classifier in the group hyperparameters is sent to the main task module.

[0158] In the fifth step, the main task module uses the validation set to verify the accuracy of the hyperparameters obtained in the fourth step, retains the best performing hyperparameters as the hyperparameters of the small sample image classification system based on text prompt weighted aggregation, and obtains the best text classifier. and a trained few-shot image classification system based on weighted aggregation of textual cues by:

[0159] 5.1 Let variable n m =1, let the total number of correct classifications total_correct = 0;

[0160] 5.2 Main task module from N m Take the nth m The group hyperparameters l, t and corresponding W C , and read the validation set D val ;

[0161] 5.3 Let batch number c = 1, indicating the cth batch. Each batch contains B′ = 64 validation set images, and the total number of batches is N. C Let the total number of correct classifications total_correct = 0;

[0162] 5.4 Take out the B′=64 images of the validation set from the cth batch and record these B′ images in matrix form I val , I val contains B′ H×W×3 images;

[0163] 5.5 The image feature extraction module receives B′ validation set D val Image I val , use the ResNet or ViT network initialized in step 4.1 to extract I val The image feature f val(is a tensor with dimension (B′, D), where D is the feature dimension), and the validation set image feature f val Send to the main task module;

[0164] 5.6 Main Task Module Using Text Classifier W C and the validation set image features f val Perform similarity calculation to obtain the predicted probabilities of N categories logits (a tensor with dimension (B′, N)). The specific process is shown in formula (4):

[0165] logits= <f val ·W C T > Formula (4)

[0166] The category corresponding to the maximum value of the second dimension in logits is the final prediction result;

[0167] 5.7 Determine whether the predicted result is the same as the true label when the data set was obtained in step 2.1. If they are the same, it is a correct classification. The number of correct classifications is recorded as correct and go to 5.8. If they are not the same, go directly to 5.8.

[0168] 5.8 Add the correct number to the total number of correct classifications in the validation set, total_correct. The specific process is shown in formula (5):

[0169] total_correct=total_correct+correct formula (5)

[0170] 5.9 If c <N C , let c=c+1, go to 5.4; if c≥N C , indicating that the verification is complete, go to 5.10;

[0171] 5.10 Calculate the classification accuracy acc. The specific process is shown in formula (6):

[0172]

[0173] Where V is the number of images in the validation set.

[0174] 5.11 If n m <N m , let n m =n m +1, go to 5.2; if n m ≥N m , indicating that all hyperparameter combinations have been verified, go to 5.12;

[0175] 5.12 to N mThe accuracy of the hyperparameters is compared, and the hyperparameter with the highest accuracy is found. The hyperparameter (containing the best text prompt feature, i.e., the text classifier) ​​is ) as the hyperparameter selected by the small sample image classification system based on text prompt weighted aggregation, and the selected hyperparameter is loaded into the small sample image classification system based on text prompt weighted aggregation. The small sample image classification system based on text prompt weighted aggregation loaded with the selected hyperparameter becomes the trained small sample image classification system based on text prompt weighted aggregation. At this time, the main task module loads the optimal text classifier

[0176] The sixth step is to use the trained small sample image classification system based on text prompt weighted aggregation to classify the image to be classified input by the user to obtain the prediction result of the image to be classified. The method is:

[0177] 6.1 The image feature extraction module receives the image set I to be classified as input by the user test , I test The number of images in is N test ;

[0178] 6.2 Image Feature Extraction Module Extraction I test The image feature f test ;

[0179] 6.3 The main task module loads the optimal text classifier obtained in step 5.12 With the test set image features f test Perform similarity calculation to obtain the predicted probability of N categories logits_test (is a tensor with dimension (N test ,N)), the specific process is shown in formula (7):

[0180]

[0181] The category corresponding to the maximum value of the second dimension in logits_test is the prediction result of the image to be classified, and the image classification is completed.

[0182] In order to verify the effect of the present invention, test set data from 11 data sets including ImageNet, StanfordCars, UCF101, Caltech101, Flowers102, SUN397, DTD, EuroSAT, FGVCAircraft, OxfordPets and Food101 are selected to replace the user's input image, and the numerical test of the classification accuracy Acc of the present invention is performed. The experimental environment is Ubuntu20.04 (a version of the Linux system), equipped with an Intel i9-10900K series CPU with a processing frequency of 3.70GHz, and four NVIDIA RTX 2080Ti image processors with a core frequency of 1635MHz and a video memory capacity of 12GB. The test sets of the above 11 data sets are input into the small sample image classification system of the present invention, the test set data is classified, the classification accuracy Acc is statistically calculated and compared with other methods to compare and measure the effectiveness of the present invention.

[0183] First, define the target detection algorithm performance evaluation index. This experiment uses a standard accuracy evaluation method with one specific index: Acc. Acc stands for accuracy, that is, the proportion of correct classifications. The larger the Acc value, the higher the classification accuracy.

[0184] According to the experimental results of the present invention, the experimental results of 11 data sets such as ImageNet and StanfordCars are analyzed. The performance comparison of the small sample image classification method in 10 data sets such as StanfordCars is shown in Figure 2. Figure 3 As shown, the performance comparison of the present invention between the current SOTA (best performance) method CaFo for small sample image classification and the classic small sample image classification methods Tip-Adapter-F, CLIP-Adapter and CALIP-FS is demonstrated.

[0185] like Figure 3 As shown in (a), the experimental results of 5 settings (1, 2, 4, 8, and 16 samples per category) on the StanfordCars dataset show that the horizontal axis is the number of samples in each category, and the vertical axis is the classification accuracy. Compared with CaFo, the accuracy of the present invention is improved by an average of 0.69%, and the highest improvement is 1.22%;

[0186] like Figure 3 As shown in (b), the experimental results of 5 settings on the UCF101 dataset show that the accuracy of the present invention is improved by an average of 1.33% compared with CaFo, and the highest improvement is 1.87%;

[0187] like Figure 3As shown in (c), the experimental results of 5 settings on the Caltech101 dataset show that the accuracy of the present invention is improved by an average of 0.60% compared with CaFo, and the highest improvement is 0.77%;

[0188] like Figure 3 As shown in (d), the experimental results of 5 settings on the Flowers102 dataset show that the accuracy of the present invention is improved by an average of 0.87% compared with CaFo, and the highest improvement is 1.74%;

[0189] like Figure 3 As shown in (e), the experimental results of 5 settings on the SUN397 dataset show that the accuracy of the present invention is improved by an average of 1.16% compared with CaFo, and the highest improvement is 1.51%;

[0190] like Figure 3 As shown in (f), the experimental results of 5 settings on the DTD dataset show that the accuracy of the present invention is improved by an average of 0.90% compared with CaFo, and the highest improvement is 1.59%;

[0191] like Figure 3 As shown in (g), the experimental results of 5 settings on the Eurosat data set show that the accuracy of the present invention is improved by an average of 0.74% compared with CaFo, and the highest improvement is 2.64%;

[0192] like Figure 3 As shown in (h), the experimental results of 5 settings on the FGVCAircraft dataset show that the accuracy of the present invention is improved by an average of 0.73% compared with CaFo, and the highest improvement is 1.74%;

[0193] like Figure 3 As shown in (i), the experimental results of 5 settings on the OxfordPets dataset show that the accuracy of the present invention is improved by an average of 0.94% compared with CaFo, and the highest improvement is 1.70%;

[0194] like Figure 3 As shown in (j), the experimental results of 5 settings on the Food101 dataset show that the accuracy of the present invention is improved by an average of 0.28% compared with CaFo, and the highest improvement is 0.40%;

[0195] The performance comparison of the small sample image classification algorithm of the present invention on the ImageNet dataset is shown in Table 1. The performance comparison of the present invention compared with the current SOTA small sample image classification method CaFo, and the classic small sample image classification algorithms CALIP-FS and Tip-Adapter-F is shown. From the experimental results, it can be seen that the present invention can quickly and accurately classify images and achieve consistent accuracy improvement. The present invention has been tested for accuracy on the ImageNet dataset (a more authoritative image classification dataset of 1,000 categories), wherein the present invention is improved by 0.14%, 0.35%, 0.11%, 0.16%, and 0.25% respectively compared with CaFo in the experimental settings of 1, 2, 4, 8, and 16 shots (the number of samples in each category).

[0196] Table 1

[0197]

[0198] In summary, except that the performance of the present invention is slightly lower than that of the CaFo method by 0.03% under the 16-shot setting of the Eurosat dataset, in the 54 settings of the remaining 11 datasets, the present invention achieves a new SOTA (best performance) in the field of small sample image classification.

Claims

1. A few-shot image classification method based on weighted aggregation of text prompts, characterized in that The following steps are involved: The first step is to build a small sample image classification system based on text prompt weighted aggregation; the small sample image classification system consists of a text prompt generation module, a text feature extraction module, an image feature extraction module, a confidence calculation module, a soft weighting module, and a main task module; The text prompt generation module is connected to the text feature extraction module. The text prompt generation module introduces a large language model as the engine for prompt generation. By designing 6 question templates to inquire the large language model, text prompts related to the category are obtained. The text prompt generation module uses the large language model as the engine for text prompt generation. It uses question templates and the large language model to obtain text prompts through dialogue, and sends the text prompts to the text feature extraction module. The text feature extraction module is connected to the text prompt generation module, the confidence calculation module, and the soft weighting module. The text feature extraction module adopts the Transformer architecture to extract features from the text prompt received from the text prompt generation module, obtain text features, and send the text features to the confidence calculation module and the soft weighting module; The image feature extraction module is connected to the confidence calculation module and the main task module. During training, the image feature extraction module extracts the image features of the training set and sends the image features of the training set to the confidence calculation module to prepare for the confidence calculation and obtaining the hyperparameters. When verifying the accuracy of the hyperparameters, the image feature extraction module extracts the image features of the verification set and sends the image features of the verification set to the main task module. When classifying the image to be classified input by the user, the image features to be classified input by the user are sent to the main task module. The image feature extraction module uses ResNet or ViT; The confidence calculation module is connected to the image feature extraction module, the text feature extraction module, and the soft weighting module. Its function is to calculate the confidence score of each text prompt. By using the mutual supervision relationship between text and image in the same feature space, the confidence score is calculated for the text features obtained from the text feature extraction module and the image features obtained from the image feature extraction module, and the quality of each text is measured as feature similarity. The confidence calculation module first screens images and texts of the same category n. Images of the same category n are grouped as express, Texts of the same category n are grouped together express, K is the number of small samples, K is a positive integer; Second, for category n, use Respectively Perform confidence calculation and sum to get the confidence score corresponding to the kth text prompt Similarly, the confidence calculation module performs the same operation on all categories in the small sample image classification scene dataset and sends the final confidence score to the soft weighting module; The soft weighting module is connected to the text feature extraction module, the confidence calculation module and the main task module. Its function is to further screen the text prompt features obtained from the text feature extraction module, and perform weighted aggregation on the text prompt features according to the confidence score to obtain the text classifier set W. C , the temperature coefficient t, the truncation factor l and the corresponding text classifier set W C Save as a set of hyperparameters and send the text classifier in the hyperparameters to the main task module; The main task module is connected to the image feature extraction module and the soft weighting module, receives the text classifier from the soft weighting module, receives the verification set image features from the image feature extraction module when verifying the accuracy of the hyperparameters, uses the verification set image features to test the text classifier, and obtains the optimal text classifier; when classifying the image to be classified input by the user, receives the features of the image to be classified input by the user from the image feature extraction module, and uses the optimal text classifier to classify the image to obtain the classification result; The second step is to construct the training set, validation set, and test set by: 2.1 Collect small sample scene images as small sample image classification scene datasets, the method is: use the general scene dataset ImageNet, remote sensing image dataset Eurosat, texture dataset DTD, flower dataset Flowers102, car dataset StanfordCars, action dataset UCF101, object recognition dataset Caltech101, scene classification dataset SUN397, aircraft classification dataset Aircraft, pet classification dataset OxfordPets, a total of 11 datasets as small sample image classification datasets, each image of these 11 datasets is manually annotated, that is, each image is annotated with the category of the object and its corresponding true label; 2.2 According to the dataset division file commonly used by researchers, the small sample image classification scene dataset is divided into training set D train , validation set D val , test set D test ; The total number of images in the training set is S, the total number of images in the validation set is V, and the total number of images in the test set is T, where S, V, and T are all positive integers; 2.3 According to the number of samples K of each category set in the small sample image classification, from the training set D train Randomly sample K images from each category in to construct a list, and add this list to the new training set D′ train , D′ train contains N lists, D′ train ={dataset1,…,dataset n ,…,dataset N }, dataset n To store the list of filtered n-th category images, N is D′ train The number of categories, each list has K images; the details are as follows: 2.3.1 Let category n = 1 and create an empty new training set D′ train Used to store sampled images; 2.3.2 Create a list dataset to store the filtered n-th category images n =[]; 2.3.3 Find the training set D train The image belonging to the nth category in is: 2.3.3.1 If the number of images num of the nth category ≥ K, randomly select K images from the images of the nth category, and at this time, no images in the K images are repeated, go to 2.3.3.3; 2.3.3.2 If the number of images num of the nth category < K, randomly select K images from the images of the nth category repeatedly, and at this time, some images in the K images are repeated, go to 2.3.3.3; 2.3.3.3 Add the selected K images to dataset n ; 2.3.3.4 Add dataset n to D′ train ; 2.3.3.5 If n < N, let n = n + 1, go to 2.3.2; if n ≥ N, obtain the final training set D′ train , D′ train ={dataset1,…,dataset n ,…,dataset N}; Thirdly, construct diverse text prompts, the method is: 3.1 Obtain 6 question templates: Obtain 5 question templates from CUPL and 1 question template from the text prompt template related to the features of CBD; the serial numbers of the 6 question templates are 1 to 6; in the templates, "{}" is used to represent the replaceable category name; 3.2 Let category n = 1, initialize the text prompt dictionary P = {}; 3.3 Let template number m = 1, initialize the text prompt list L corresponding to the nth category n =[]; 3.4 According to the category name class corresponding to the label of the nth category n , change the category name to class n Replace the "{}" of the mth template in step 3.1 to get the mth question template Q m ; 3.5 The text prompt generation module will ask the question template Q m Input to the large language model, get the corresponding text prompts from the large language model, and add these text prompts to the text prompt list L corresponding to the nth category n ; 3.6 If m < 6, let m = m + 1, and go to 3.4; if m ≥ 6, go to 3.7; 3.7 Set the class name of the label corresponding to the nth class n List of text prompts corresponding to this category L n Constitute the key-value pair "class n :L n ”,class n is the key, L n As value, set "class n :L n " is added to the dictionary P; 3.8 If n < N, then let n = n + 1, and go to 3.3; if n ≥ N, go to 3.9; 3.9 At this time, text prompts are generated for all N categories, and the final text prompt dictionary P is obtained, P = {class1:L1,…,class n :L n ,…,class N :L N }; The fourth step is to use the training set to train the small sample image classification system based on text prompt weighted aggregation to obtain N m Group hyperparameters, N m is a positive integer, the method is: 4.1 Initialize the model parameters of each module in the few-shot image classification system; use the pre-trained model CLIP to initialize the parameters of the Transformer in the text feature extraction module and the parameters of ResNet or ViT in the image feature extraction module; 4.2 Initialize the text classifier set W C = [], initialize the hyperparameter truncation factor l = 0.3; 4.3 Let batch number b = 1, indicating the bth image batch, each batch has B images, and the total batch number is N B , B is a positive integer; 4.4 Image feature extraction module from training set D′ train Read the B images of the bth batch, recorded as matrix form I train , I train It contains B H×W×3 images, where H represents the height of the input image, W represents the width of the input image, "3" represents the RGB channels of the image, and B represents the number of images in a batch. 4.5 Image feature extraction module uses image feature extraction method to filter out K image samples I of the category according to the category label n K , I K is a list of K images, extract I K The image feature f v , f v Sent to the confidence calculation module, f v is a tensor with dimension (B, D), where D is the feature dimension; 4.6 Text feature extraction module According to the category name class corresponding to the category label n n , extract the words belonging to class from the text prompt dictionary P n Text prompt list L n , Ln is a list of M text prompts, extract L n The text prompt feature f t , f t Sent to the confidence calculation module and the soft weighting module, f t is a tensor with dimension (M, D), where D is the feature dimension; 4.7 The confidence calculation module receives the image feature f from the image feature extraction module v and the text hint feature f from the text feature extraction module t , calculate the confidence score and get the confidence score S: S= <f v ·f t T > Formula (1) where <·> represents calculating the inner product between two vectors, and send the confidence score S to the soft weighting module, and the dimension of S is (K, M); 4.8 The soft weighting module sums the first dimension of the confidence score S to obtain the summed confidence score S1, and then sorts S1 from high to low to obtain the sorted confidence score S2. The hyperparameter cutoff factor l is used to filter the top confidence scores from S2. The confidence score S′ with higher confidence is S1 and S2 with dimensions M and S′ with dimensions The soft weighting module receives the text prompt features from the text feature extraction module and indexes the text prompt features f corresponding to S′ t ′, initialize the hyperparameter temperature coefficient t=1; 4.9 The soft weighting module multiplies the confidence score S' by the hyperparameter temperature coefficient t to sharpen the confidence score, and obtains the sharpened confidence score S'': S'' = S'·t Formula (2) 4.10 The soft weighting module uses the softmax function to weight the text prompt feature f according to the sharpened confidence score S″ t ′ is weighted aggregation to obtain the text prompt feature W of the bth batch b : W b = <f t ′·softmax(S″)> Formula (3) 4.11 The text prompt feature W at this time b Add to the text classifier set W C ; 4.12 If b <N B , let b=b+1, go to 4.4; if b≥N B , indicating that the text classifier set has been built, W C is a tensor with dimension (N, D), where D is the feature dimension, go to 4.13; 4.13 The temperature coefficient t, the truncation factor l and the corresponding text classifier set W at this time C Save as a set of hyperparameters; 4.14 If t<10, let t=t+1 and go to 4.9; if t≥10, go to 4.15; 4.15 If l<1, let l=l+0.1 and go to 4.8; if l≥1, go to 4.16; 4.16 Get N m The soft weighting module sets N m The text classifier in the group hyperparameters is sent to the main task module; In the fifth step, the main task module uses the validation set to verify the accuracy of the hyperparameters, retains the best performing hyperparameters as the hyperparameters of the small sample image classification system based on text prompt weighted aggregation, and obtains the best text classifier. and the trained few-shot image classification system by: 5.1 Let variable n m =1, let the total number of correct classifications total_correct = 0; 5.2 Main task module from N m Take the nth m The group hyperparameters l, t and corresponding W C , and read the verification set D val ; 5.3 Let batch number c = 1, indicating the cth batch. Each batch contains B′ = 64 validation set images, and the total number of batches is N. C , Let the total number of correct classifications total_correct = 0; 5.4 Take out the B′ validation set images of the cth batch and record these B′ images in matrix form I val , I val contains B′ H×W×3 images, B′=64; 5.5 The image feature extraction module receives B′ validation set D val Image I val , use the ResNet or ViT network initialized in step 4.1 to extract I val The image feature f val , f val is a tensor with dimension (B′, D), where D is the feature dimension. val Send to the main task module; 5.6 Main Task Module Using Text Classifier W C With f val Perform similarity calculation to obtain the predicted probability logits of N categories. Logits is a tensor with dimension (B′, N): logits= <f val ·W CT > Formula (4) The category corresponding to the maximum value of the second dimension in logits is the final prediction result; 5.7 Determine whether the predicted result is the same as the true label when the data set was obtained in step 2.

1. If they are the same, it is a correct classification. The number of correct classifications is recorded as correct and go to 5.

8. If they are not the same, go directly to 5.

8. 5.8 Add the correct number to the total number of correct classifications in the validation set: total_correct: total_correct=total_correct+correct formula (5) 5.9 If c <N C , let c=c+1, go to 5.4; if c≥N C , indicating that the verification is complete, go to 5.10; 5.10 Calculate the classification accuracy acc. The specific process is shown in formula (6): in, V is the number of images in the validation set; 5.11 If n m <N m , let n m =n m +1, go to 5.2; if n m ≥N m , indicating that all hyperparameter combinations have been verified, go to 5.12; 5.12 to N m The accuracy of the hyperparameters is compared, and the hyperparameter with the highest accuracy is found. This hyperparameter is used as the hyperparameter selected by the small sample image classification system. This hyperparameter contains the best text classifier. The selected hyperparameters are loaded into the small sample image classification system based on weighted aggregation of text prompts. The small sample image classification system based on weighted aggregation of text prompts loaded with the selected hyperparameters becomes the trained small sample image classification system based on weighted aggregation of text prompts. At this time, the main task module loads the optimal text classifier. Sixth step, use the trained few-shot image classification system based on text prompt weighted aggregation to classify the image to be classified input by the user, and obtain the prediction result of the image to be classified. The method is: 6.1 The image feature extraction module receives the image set I to be classified as input by the user test , I test The number of images in is N test ; 6.2 Image Feature Extraction Module Extraction I test The image feature f test ; 6.3 Main task module loads the optimal text classifier With the test set image features f test Perform similarity calculation to obtain the predicted probability logits_test of N categories. logits_test is a tensor with dimension (N test ,N): The category corresponding to the maximum value of the second dimension in logits_test is the prediction result of the image to be classified, and the image classification is completed.

2. A small sample image classification method based on textual hint weighted aggregation as claimed in claim 1, characterized in that The large language model adopted by the text prompt generation module is GPT-3 or ChatGLM, and the 6 question templates adopted are: (1) "Describe what a(n) {} looks like.", (2) "How can you identify a(n) {}?", (3) "What does a(n) {} look like?", (4) "A caption of an image of a(n) {}.", (5) "Describe an image from the internet of a(n) {}.", (6) "What are useful visual features for distinguishing a(n) {} in a photo?".

3. A small sample image classification method based on textual hint weighted aggregation as claimed in claim 1, characterized in that The text feature extraction module adopts the Transformer architecture, and its parameters adopt the parameters pre-trained by CLIP in the Transformer architecture; the Transformer architecture consists of an encoder and a decoder; the encoder is used to understand the input sequence, and the decoder is used to generate the output sequence; both the encoder and the decoder are stacked by 6 identical layers; each layer contains two sub-layers: one is a multi-head self-attention module, which uses the self-attention mechanism to allow the large language model to simultaneously focus on other elements in the sequence when processing an element in a sequence, so as to capture the dependencies between them; the other is a fully connected layer, and these two sub-layers are connected by a residual connection; use Transformer to capture the dependencies between different positions in the input sequence and obtain global context information, making it particularly effective in semantic feature extraction; the self-attention module of Transformer allows the network to perform attention calculations between inputs at different positions.

4. A small sample image classification method based on text prompt weighted aggregation as claimed in claim 1, characterized in that Depending on the network depth, the image feature extraction module is any one of the networks ResNet50, ResNet101, ViT-B / 32, ViT-B / 16 and ViT-L / 14 trained by CLIP using 400 million image-text pairs.

5. A small sample image classification method based on text prompt weighted aggregation as claimed in claim 1, characterized in that The number of samples of each category in the small sample image classification is K∈{1,2,4,8,16}.

6. A small sample image classification method based on text prompt weighted aggregation as claimed in claim 1, characterized in that Step 4: B = 256, N m =80.

Citation Information

Patent Citations

  • Small sample picture classification model and method based on semantic auxiliary attention mechanism

    CN111985538A

  • Small sample image classification method and device based on sample generation and storage medium

    CN116168257A

  • Graph data classification method and device, electronic equipment and storage medium

    CN117648625A

  • Image classification method and related device thereof

    WO2023274052A1