The Annotated CLIP (Part-1)
This post is part-1 of the two series blog posts on CLIP. In this blog, we present an Introduction to CLIP in an easy to digest manner. We also compare CLIP to other research papers and look at the background and inspiration behind CLIP.
1 Personal Updates
Hello, and welcome back everybody to the blog! This is my first blog of the year 2023 and as publicly announced on Twitter, I am returning to blogging with a commitment of 1 blog a week, planned to be released every Monday at 9am AEST.
Starting 01 Mar, 2023 I’ll be going back to blogging 1 post a week every Monday at 9am AEST.
These blogs will be about AI research, new technologies, updates, frameworks, Kaggle competitions and more.
If you have a topic that you’d like me to cover, please let me know. 🙂
— Aman Arora ( (amaarora?) ) February 7, 2023
Also, in case you missed it, I was also recently interviewed by Radek Osmulski — “How to Blog to Advance Your Career and Learn Faster” (in AI). In the video, we discuss and talk about my motivation for writing blogs, blogging to advance your career and learn, how to get started with blogging & more!
I have also updated my personal blog to use Quarto. The idea is to release all future blog posts which are working Jupyter Notebooks themeselves.
Now, with personal updates out of the way, let’s get started with CLIP.
2 Introduction
As part of this blog post we will be uncovering the inner workings of CLIP — Learning Transferable Visual Models From Natural Language Supervision ( Radford et al. (2021) ), and we will be looking at it’s PyTorch implementation in part-2 of the blog that will be released next week.
CLIP in itself does not present a new idea, but implements an older idea of learning Image representations from text. CLIP applies this idea to a large scale dataset (400M images), and achieves zero shot transfer on ImageNet that matches ResNet-50. At the time of writing CLIP was the first model architecture to achieve such great zero shot results on ImageNet.
2.1 Key Contributions
If I am to summarise key contributions from the paper:
- New (image, text) pair dataset:We demonstrate that the simple pre-training task of predicting which caption goes with which image is an efficient and scalable way to learn SOTA image representations from scratch on a dataset of 400 million (image, text) pairs collected from the internet.
- Zero-shot performance that is competitive with supervised models:We study the performance of this approach by benchmarking on over 30 different existing computer vision datasets, spanning tasks such as OCR, action recognition in videos, geo-localization, and many types of fine-grained object classification. The model transfers non-trivially to most tasks and is often competitive with a fully supervised baseline without the need for any dataset specific training.
- High zero shot performance on ImageNet: We match the accuracy of the original ResNet-50 on ImageNet zero-shot without needing to use any of the 1.28 million training examples it was trained on.
- Open source model and weights:We release our code and pre-trained model weights at https://github.com/OpenAI/CLIP.
Before we start looking at the inner workings of CLIP, let’s look at some background that led to the development of CLIP.
3 Motivation for CLIP & Prior Work
CLIP was written in 2021, at a time where text transformer based models like GPT-3 (and others) were competitive across many tasks on various benchmark datasets, swhile requiring little to no dataset specific training data. This was made possible by pretraining on huge amounts of data found directly from the web. Pre-training on Wikipidea articles (WebText which contained the text subset of these 45 million links), became standard practice.
It was clear that models pre-trained on high web-scale collections of text surpassed that of high-quality crowd-labeled NLP datasets.
But, for vision based models, it was still standard practice to pre-train models on crowd-labeled datasets such as ImageNet. The question then is Could scalable pre-training methods which learn directly from web text result in a similar breakthrough in computer vision?
At the time it was still common practice to train on crowd labeled datasets for computer vision.
For example, Kolesnikov et al. (2019) and Dosovitskiy et al. (2020) had demonstrated large gains on a broader set of transfer benchmarks by pre-training models to predict the classes of the noisily labeled JFT-300M dataset. But both approaches used static softmax classifiers to perform prediction, which severely curtails their flexibility and limits their “zero-shot” capabilities.
But also, before CLIP some attempts had been made to learn image representations directly from text — VirTex (Desai & Johnson, 2020), ICMLM (Bulent Sariyildiz et al., 2020), and ConVIRT (Zhang et al., 2020).
In my humble opinion, ConVirt — “Contrastive Learning of Medical Visual Representations from Paired Images and Text” (Zhang et al., 2020) is of most interest of all prior work.
Figure 1: Two example chest X-ray images with different abnormality categories
ConVirt introduced a new method of pretraining medical image encoders with the paired text data (as in Figure 1) via a bidirectional contrastive objective between the two modalities. This method was domain-agnostic, and required no additional expert input.
However, ConVirt had been applied in the medical context. CLIP expanded this idea to general visual recognition. Thus, ConVirt directly inspired CLIP.

Figure 2: Overview of ConVirt
The figure above shows the overview of ConVirt, and as you’ll notice, CLIP is quite similar.
From the ConVirt paper:
ConVIRT has directly inspired subsequent studies such as the CLIP framework (Radford et al., 2021) and the ALIGN model (Jia et al., 2021), which showed that direct adaptations of ConVIRT-style pretraining at much larger scales lead to state-of-the-art general visual recognition capabilities.
4 Approach
At the core of our approach is the idea of learning perception from supervision contained in natural language. As discussed before, this is not at all a new idea.
Learning from natural language has several potential strengths over other training methods. Can you think of some?
- It’s much easier to scale natural language supervision compared to standard crowd-sourced labeling for image classification.
- Learning from natural language also has an important advantage over most unsupervised or self-supervised learning approaches in that it doesn’t “just” learn a representation but also connects that representation to language which enables flexible zero-shot transfer.
4.1 Summary with Pseudo-Code
In this section I will present the summary of CLIP architecture from the paper.
The overall approach has been presented in Figure 3 below. Can you notice the similarities to ConVirt in Figure 2?

Figure 3: Summary of CLIP approach
CLIP Is architecture agnostic. You can use any models as visual and text encoders in Figure 3.
A team led by Ross Wightman, Cade Gordon, and Vaishaal Shankar have a repository OpenCLIP that is an open source implementation of CLIP and enables training for any vision models with contrastive image-text supervision.
Also, recently, Ross Wightman also announced a 847M param ConvNext model trained via CLIP training that achieves 79.43% ImageNet zero-shot eval. Astonishing, right?
The approach presented in Figure 3 has been summarised in pseudo code from paper:
Let’s look at what it all means with the help of Microsoft Excel.

Figure 4: Illustration of contrastive loss
Let’s say we have 8 images with corresponding text descriptions as in Figure 4. CLIP presents a training framework to maximise the cosine similarity of text and image embeddings.
As from the pseudo-code, first we pass the images through image encoder and texts through text encoder respective to get image and text features.
Therefore in the above case, referencing to pseuo-code, \(n=8\) and \(d_i = 2048\) .
Similarly, referencing to pseudo-code, \(n=8\) and \(d_t=768\) .
Let’s just assume the embedding dimension \(d_e = 1024\) , now, as per psuedo-code, we can have two projection layers- \(W_i[d_i, d_e]\) and \(W_t[d_t, d_e]\) both for text and image features respectively.
Now that we have our projection layers, as per pseudo-code, we get our joint multimodal embeddings through dot product.
Now that we both our Image and Text embeddings, we can find cosine-similarity.

Figure 5: Cosine similarity between text and image features
We want the cosine similarity of real (text, image) pairs to be high (right diagonal), and everywhere else to be low.
So what loss function could we use in this case? The answer is in the pseudo-code.
When we do cross entropy loss with both axis=1 and axis=0, we are pushing logits to be high for the diagonal and low everywhere else. This is also referred to as Contrastive Loss. Thus, by doing this the CLIP model is able to learn visual features directly from text.
By training on a dataset of 400 million (image, text) pairs, the CLIP model is able to attain zero shot performance on ImageNet that is comparable to ResNet-50!
And that’s really all the magic behind CLIP.
5 Conclusion
As part of this blog post, we introduced the CLIP architecture to the reader. We saw how the CLIP approach is very similar to ConVirt with some very minor differences which we will discuss further in part-2 of the blog to be released next week.
In part-2, we will also be looking at the PyTorch code of CLIP, and the training code from OpenClip.
If you enjoyed reading, please feel free to subscribe to receive regular updates regarding new blog posts.
CLIP: Connecting text and images

We’re introducing a neural network called CLIP which efficiently learns visual concepts from natural language supervision. CLIP can be applied to any visual classification benchmark by simply providing the names of the visual categories to be recognized, similar to the “zero-shot” capabilities of GPT-2 and GPT-3.
More resources
Although deep learning has revolutionized computer vision, current approaches have several major problems: typical vision datasets are labor intensive and costly to create while teaching only a narrow set of visual concepts; standard vision models are good at one task and one task only, and require significant effort to adapt to a new task; and models that perform well on benchmarks have disappointingly poor performance on stress tests, [^reference-1] [^reference-2] [^reference-3] [^reference-4] casting doubt on the entire deep learning approach to computer vision.
We present a neural network that aims to address these problems: it is trained on a wide variety of images with a wide variety of natural language supervision that’s abundantly available on the internet. By design, the network can be instructed in natural language to perform a great variety of classification benchmarks, without directly optimizing for the benchmark’s performance, similar to the “zero-shot” capabilities of GPT-2 [^reference-5] and GPT-3. [^reference-6] This is a key change: by not directly optimizing for the benchmark, we show that it becomes much more representative: our system closes this “robustness gap” by up to 75% while matching the performance of the original ResNet-50 [^reference-7] on ImageNet zero-shot without using any of the original 1.28M labeled examples.
Background and related work
CLIP (Contrastive Language–Image Pre-training) builds on a large body of work on zero-shot transfer, natural language supervision, and multimodal learning. The idea of zero-data learning dates back over a decade [^reference-8] but until recently was mostly studied in computer vision as a way of generalizing to unseen object categories. [^reference-9] [^reference-10] A critical insight was to leverage natural language as a flexible prediction space to enable generalization and transfer. In 2013, Richer Socher and co-authors at Stanford [^reference-11] developed a proof of concept by training a model on CIFAR-10 to make predictions in a word vector embedding space and showed this model could predict two unseen classes. The same year DeVISE [^reference-12] scaled this approach and demonstrated that it was possible to fine-tune an ImageNet model so that it could generalize to correctly predicting objects outside the original 1000 training set.
Most inspirational for CLIP is the work of Ang Li and his co-authors at FAIR [^reference-13] who in 2016 demonstrated using natural language supervision to enable zero-shot transfer to several existing computer vision classification datasets, such as the canonical ImageNet dataset. They achieved this by fine-tuning an ImageNet CNN to predict a much wider set of visual concepts (visual n-grams) from the text of titles, descriptions, and tags of 30 million Flickr photos and were able to reach 11.5% accuracy on ImageNet zero-shot.
Finally, CLIP is part of a group of papers revisiting learning visual representations from natural language supervision in the past year. This line of work uses more modern architectures like the Transformer [^reference-32] and includes VirTex, [^reference-33] which explored autoregressive language modeling, ICMLM, [^reference-34] which investigated masked language modeling, and ConVIRT, [^reference-35] which studied the same contrastive objective we use for CLIP but in the field of medical imaging.
Approach
We show that scaling a simple pre-training task is sufficient to achieve competitive zero-shot performance on a great variety of image classification datasets. Our method uses an abundantly available source of supervision: the text paired with images found across the internet. This data is used to create the following proxy training task for CLIP: given an image, predict which out of a set of 32,768 randomly sampled text snippets, was actually paired with it in our dataset.
In order to solve this task, our intuition is that CLIP models will need to learn to recognize a wide variety of visual concepts in images and associate them with their names. As a result, CLIP models can then be applied to nearly arbitrary visual classification tasks. For instance, if the task of a dataset is classifying photos of dogs vs cats we check for each image whether a CLIP model predicts the text description “a photo of a dog” or “a photo of a cat” is more likely to be paired with it.
CLIP was designed to mitigate a number of major problems in the standard deep learning approach to computer vision:
Costly datasets: Deep learning needs a lot of data, and vision models have traditionally been trained on manually labeled datasets that are expensive to construct and only provide supervision for a limited number of predetermined visual concepts. The ImageNet dataset, one of the largest efforts in this space, required over 25,000 workers to annotate 14 million images for 22,000 object categories. In contrast, CLIP learns from text–image pairs that are already publicly available on the internet. Reducing the need for expensive large labeled datasets has been extensively studied by prior work, notably self-supervised learning, [^reference-14] [^reference-15] [^reference-16] contrastive methods, [^reference-17] [^reference-18] [^reference-19] [^reference-20] [^reference-21] self-training approaches, [^reference-22] [^reference-23] and generative modeling. [^reference-24] [^reference-25] [^reference-26] [^reference-27]
Narrow: An ImageNet model is good at predicting the 1000 ImageNet categories, but that’s all it can do “out of the box.” If we wish to perform any other task, an ML practitioner needs to build a new dataset, add an output head, and fine-tune the model. In contrast, CLIP can be adapted to perform a wide variety of visual classification tasks without needing additional training examples. To apply CLIP to a new task, all we need to do is “tell” CLIP’s text-encoder the names of the task’s visual concepts, and it will output a linear classifier of CLIP’s visual representations. The accuracy of this classifier is often competitive with fully supervised models.
We show random, non-cherry picked, predictions of zero-shot CLIP classifiers on examples from various datasets below.
Poor real-world performance: Deep learning systems are often reported to achieve human or even superhuman performance [^reference-28] [^footnote-1] on vision benchmarks, yet when deployed in the wild, their performance can be far below the expectation set by the benchmark. In other words, there is a gap between “benchmark performance” and “real performance.” We conjecture that this gap occurs because the models “cheat” by only optimizing for performance on the benchmark, much like a student who passed an exam by studying only the questions on past years’ exams. In contrast, the CLIP model can be evaluated on benchmarks without having to train on their data, so it can’t “cheat” in this manner. This results in its benchmark performance being much more representative of its performance in the wild. To verify the “cheating hypothesis”, we also measure how CLIP’s performance changes when it is able to “study” for ImageNet. When a linear classifier is fitted on top of CLIP’s features, it improves CLIP’s accuracy on the ImageNet test set by almost 10%. However, this classifier does no better on average across an evaluation suite of 7 other datasets measuring “robust” performance. [^reference-30]
Key takeaways
1. CLIP is highly efficient
CLIP learns from unfiltered, highly varied, and highly noisy data, and is intended to be used in a zero-shot manner. We know from GPT-2 and 3 that models trained on such data can achieve compelling zero shot performance; however, such models require significant training compute. To reduce the needed compute, we focused on algorithmic ways to improve the training efficiency of our approach.
We report two algorithmic choices that led to significant compute savings. The first choice is the adoption of a contrastive objective for connecting text with images. [^reference-31] [^reference-17] [^reference-35] We originally explored an image-to-text approach, similar to VirTex, [^reference-33] but encountered difficulties scaling this to achieve state-of-the-art performance. In small to medium scale experiments, we found that the contrastive objective used by CLIP is 4x to 10x more efficient at zero-shot ImageNet classification. The second choice was the adoption of the Vision Transformer, [^reference-36] which gave us a further 3x gain in compute efficiency over a standard ResNet. In the end, our best performing CLIP model trains on 256 GPUs for 2 weeks which is similar to existing large scale image models. [^reference-37] [^reference-23] [^reference-38] [^reference-36]
2. CLIP is flexible and general
Because they learn a wide range of visual concepts directly from natural language, CLIP models are significantly more flexible and general than existing ImageNet models. We find they are able to zero-shot perform many different tasks. To validate this we have measured CLIP’s zero-shot performance on over 30 different datasets including tasks such as fine-grained object classification, geo-localization, action recognition in videos, and OCR. [^footnote-2] In particular, learning OCR is an example of an exciting behavior that does not occur in standard ImageNet models. Above, we visualize a random non-cherry picked prediction from each zero-shot classifier.
This finding is also reflected on a standard representation learning evaluation using linear probes. The best CLIP model outperforms the best publicly available ImageNet model, the Noisy Student EfficientNet-L2, [^reference-23] on 20 out of 26 different transfer datasets we tested.
CLIP from OpenAI: what is it and how you can try it out yourself
Neural networks (NN) and computer vision models in particular are known to perform well in specific tasks, but often fail to generalize to tasks they have not been trained on. A model that performs well on a food data may perform poorly on satellite images.
A new model from OpenAI named CLIP claims to close this gap by a large margin. The paper Open AI wrote presenting CLIP demonstrates how the model may be used on a various classification datasets in a zero-shot manner.
In this article, I will explain the key ideas of the model they proposed and show you the code to use it.
Intuition
In a typical classification scenario, one has a set of examples connected to a set of pre-defined categories. In such a set, the number of categories is fixed. If you train a model to distinguish between cats and dogs and then later decide to add a new class “bear”, then you will have to add example images with bears and train a new network!
However, if one were to train a network that connects an image to an arbitrary text, then you can utilize it with new classes simply by providing text description of that class. For this to work successfully, the network must learn good visual representations and good connections between visual cues and text.
How CLIP works
First, let us consider our problem scope. In order to connect images with text we need a dataset of image-text pairs. CLIP authors report that they assembled a dataset of 400 million (image, text) pairs from the Internet. The model will take an image as an input and predict text as an output.
There are different ways of representing text for prediction as shown on the figure below:
One can predict text with the correct word order, i.e. the classifier must output this is a photo of a cat . Or one can predict a label based on bag of words, i.e. the order of words is not important and if classifier predicts photo , cat , then it is correct. OpenAI suggests a further improvement upon the bag of words method and shows that CLIP is 4x more efficient in zero-shot ImageNet accuracy compared to previous methods.
CLIP achieves this by reframing the problem and using the contrastive pre-training. Instead of predicting label text, CLIP is training on predicting how likely this image is to correspond to that text.
Input images and texts are encoded, and their vector representations are used to build a similarity matrix (I*T is an inner product). Now, we know (during training) that the values on the diagonal represent correct classifications, so their similarity must be higher than those in the same row/column. This approach contrasts what we know go together (diagonal values) to what we know doesn’t go together (non-diagonal values). You can see that each row is a classification task: given an input image I, predict the text. Similarly, each column is a classification task: given an input text T, predict the image. During training, OpenAI used a very large size of mini-batches 32768 (N on the figure above).
During inference one takes a set of labels, creates texts based on labels and runs these texts through the text encoder. Text embeddings are later matched to image representation.
Classic classification training cares only about the predefined labels. If it is successful in findings dogs, then it doesn’t care if it is a photo or a sketch of a dog or a specific breed. Whereas CLIP training coupled with a large dataset makes the network learn various aspects of images and point attention to details.
One detail that is worth mentioning is that CLIP is sensitive to words used for image descriptions. Texts “a photo of a bird”, “a photo of a bird siting near bird feeder”, or “an image of a bird” all produce different probability paired with the same image:
CLIP in a real project scenario
To illustrate the potential of CLIP, I would like to show a real project use case, based on one of the projects I worked on for a customer, an image similarity search engine. In this project, a user submits an image to model and as a result get a list of images that are visually similar to the query image. In our case, images being searched corresponded to pages of PDF documents and may contain individually or a mix of text, tables, embedded photos, empty pages, schemas, diagrams, and technical drawings. For the customer, the search return images of interest were technical drawings. Additionally, we also knew that what user searches would only be based on technical drawings.
The key characteristics of these images are that they contain a lot of small details that may be highly relevant for interpretation and that they may contain irrelevant patterns. Here are a couple of examples of technical drawings:
As always, the devil is in the details, and in this case these are things like the fact that each image contains textual information block in the bottom-right corner. For example, if there are a lot of technical drawings from Pittsburgh Technical Institute, then they all will have a very similar text block. Thus, a neural network may very quickly begin to anchor to that block.
The ResNet-18 model used in production was trained using SimCLR approach. SimCLR is a self-supervised contrastive learning method that allows to learn good visual representations without image labels. The model was trained on 100k images, ca. 50 % of which were technical drawings and the rest were all the other types of images.
Following this, I benchmarked CLIP against SimCLR for visual similarity search. I found that image features from a released CLIP-based model taken as zero-shot perform on pair with SimCLR-based model trained specifically for that data. This is truly amazing given that technical drawings are not the typical candidates for publicly available datasets. I can’t explain why CLIP is able to perform so well on technical drawings, might it be that examples of such drawings were part of the training dataset.
Another result shown here is that CLIP was not training with image similarity in mind. Yet it learned useful representations that may be used in image similarity scenarios.
CLIP current limitations
CLIP authors are open about its limitations. CLIP struggles on more abstract or systematic tasks such as counting the number of objects and on a more complex tasks such as estimating relative distances between objects. On such datasets, CLIP is only slightly better than random guessing. CLIP also struggles with very fine-grained classification, such as telling the difference between car models, variants of aircraft, or flower species.
CLIP model itself is data hungry and expensive to train. If pre-trained model doesn’t work well for you, it may be not feasible to train your own version.
While zero-shot CLIP tries to reformulate classification task, the principles are still the same. And although CLIP generalizes well to many image distributions, it still generalizes poorly to data that is truly out-of-distribution. One example of this was CLIP’s performance on MNIST dataset where CLIP zero-shot accuracy was 88 %. Logistic regression on raw pixels outperforms CLIP.
Ability to adapt to new datasets and classes is related to text encoder. It is thus limited to choosing from only those concepts known to the encoder. CLIP model trained with English texts will be of little help if used with texts in other languages.
Finally, CLIP’s classifiers can be sensitive to wording in label descriptions and may require trial and error to perform well.
Conclusions
CLIP training pushes the boundaries of traditional classifier a bit further, and the released pre-trained model allows one to perform various computer vision tasks (classification, image feature utilization) with good performance and without a need of a training set. As one of the pain points when working on real projects in data science is data scarcity, where there may be a lack of ground truth data or the amount of data is limited. As I show with an example, pre-trained CLIP-based model allows to kick-start such projects — thus this development is a welcomed addition to the Data Science toolbox.
I hope you enjoyed a presentation the key aspects of how CLIP works, and a high-level demonstration of what it can be used on.
If you have found it interesting, I highly recommend reading the original paper where authors run a lot of different experiments and show how CLIP performs zero-shot classification on a broad range of datasets.
How to try out CLIP yourself?
I’ve prepared a Colab notebook that shows how to interact with CLIP. There you will find not only the basic procedure, but also some insights into how text descriptions affect the outcome. Be sure to check it out!
That notebook uses 16 portrait photos of 3 people. I wanted to see if CLIP can discriminate these people. It certainly can! However, as CLIP authors point out in their paper, at the current state of development CLIP may be not the best candidate to perform such tasks, but it is a good way to see how the model works. Its capabilities are anyway look very interesting.
Acknowledgments
Big thanks to Maximilian Warner and Alexander Vaagan who helped preparing this post.
Классификация изображений с помощью OpenAI Clip
CLIP расшифровывается как предварительное обучение с использованием контрастного языка и изображения. Его можно проинструктировать на естественном языке для прогнозирования наиболее релевантного фрагмента текста для данного изображения без прямой оптимизации под задачу, аналогично возможностям нулевого кадра в GPT-2 и 3.
Почему именно CLIP для классификации изображений?
Стандартным подходом к решению любой проблемы классификации изображений является использование предварительно обученной модели, такой как ResNet, а затем ее точная настройка с некоторыми дополнительными данными. Это очень трудоемкий и затратный по времени процесс. Модель CLIP OpenAI обеспечивает новое прагматическое решение проблем такого типа, поскольку она интуитивно понимает, что означает естественный язык в связи с изображениями. С OpenAI CLIP все, что вам нужно сделать, это создать семантические и описательные метки, а CLIP сделает все остальное!
Как мы видим, OpenAI CLIP очень точен среди наборов данных разных типов, что делает его отличным выбором с точки зрения производительности классификации изображений.
Использование OpenAI CLIP
В недавнем проекте я столкнулся с проблемой классификации изображений по времени суток. Например, изображение, сделанное ночью, будет классифицироваться как ночное, а изображение, сделанное днем, будет классифицировано как дневное. Проведя небольшое исследование в Интернете, я обнаружил, что не существует помеченных наборов данных, которые позволили бы мне обучить модель традиционным способом. Поэтому я предпочитаю использовать OpenAI CLIP для классификации своих изображений.
В этом примере мы классифицируем 25 000 изображений в наборе данных unsplash
Примечание: чтобы избежать проблем с настройкой среды машинного обучения, рекомендуется запускать код в градиенте пространства бумаги. Gradient также предоставляет бесплатный графический процессор, который рекомендуется для запуска кода.
Если вы хотите продолжить, раскройте мою записную книжку здесь, чтобы иметь набор данных в вашем каталоге.
Если вы хотите загрузить набор данных изображений без всплесков самостоятельно, следуйте инструкциям здесь
Установка
Предполагая, что pytorch установлен, запустите следующий код в командной строке, чтобы установить необходимые пакеты:
Теперь давайте импортируем необходимые библиотеки:
Настроить OpenAI CLIP
— ›« cuda »(« cpu », если ваше устройство использует процессор.)
Настроить набор данных Unsplash
Идентификаторы фотографий без всплеска хранятся во фрейме данных, который затем сохраняется в файле пера.
Запускать на всех изображениях
Чтобы запустить это на всех изображениях в наборе данных Unsplash, сначала мы настраиваем все метки и используем CLIP для токенизации меток.
Здесь мы используем пакетную обработку изображений, чтобы ускорить процесс прогнозирования, используя возможности графических процессоров.
В следующем коде мы запускаем модель OpenAI CLIP для каждого изображения в наборе данных unsplash, чтобы определить, к какой метке они относятся.
Теперь, когда у нас есть результаты для каждого пакета изображений, мы собираемся объединить их и получить индекс метки, которая имеет наибольшую вероятность для каждого изображения. К счастью, numpy имеет встроенные функции, которые позволяют нам делать это эффективно.
И теперь у нас есть результаты прогнозов! Теперь мы собираемся сохранить результаты прогнозов в формате данных пера, чтобы использовать их в будущем.
Это распределение изображений по нашим лейблам.
И теперь все готово! Посмотрим на результаты.
Прогноз ИИ: утро (похоже на обои Эль-Капитана, смеется)
Прогноз ИИ: полдень
Прогноз ИИ: полдень
Прогнозирование ИИ: восход или закат (поскольку восход и закат выглядят одинаково, они объединены в один класс.)