Path: blob/main/transformers_doc/en/image_feature_extraction.ipynb
4522 views
Image Feature Extraction
Image feature extraction is the task of extracting semantically meaningful features given an image. This has many use cases, including image similarity and image retrieval. Moreover, most computer vision models can be used for image feature extraction, where one can remove the task-specific head (image classification, object detection etc) and get the features. These features are very useful on a higher level: edge detection, corner detection and so on. They may also contain information about the real world (e.g. what a cat looks like) depending on how deep the model is. Therefore, these outputs can be used to train new classifiers on a specific dataset.
In this guide, you will:
Learn to build a simple image similarity system on top of the
image-feature-extraction
pipeline.Accomplish the same task with bare model inference.
Image Similarity using image-feature-extraction
Pipeline
We have two images of cats sitting on top of fish nets, one of them is generated.
Let's see the pipeline in action. First, initialize the pipeline. If you don't pass any model to it, the pipeline will be automatically initialized with google/vit-base-patch16-224. If you'd like to calculate similarity, set pool
to True.
To infer with pipe
pass both images to it.
The output contains pooled embeddings of those two images.
To get the similarity score, we need to pass them to a similarity function.
If you want to get the last hidden states before pooling, avoid passing any value for the pool
parameter, as it is set to False
by default. These hidden states are useful for training new classifiers or models based on the features from the model.
Since the outputs are unpooled, we get the last hidden states where the first dimension is the batch size, and the last two are the embedding shape.
Getting Features and Similarities using AutoModel
We can also use AutoModel
class of transformers to get the features. AutoModel
loads any transformers model with no task-specific head, and we can use this to get the features.
Let's write a simple function for inference. We will pass the inputs to the processor
first and pass its outputs to the model
.
We can pass the images directly to this function and get the embeddings.
We can get the similarity again over the embeddings.