3

I am using CLIP to determine the similarity between words and images.

For now I am using this repo and the following code and for classification it gives great results. I would need it for multi label classification in which I would need to use sigmoid instead of softmax.

import torch
from PIL import Image
import open_clip

model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32-quickgelu', pretrained='laion400m_e32')
tokenizer = open_clip.get_tokenizer('ViT-B-32-quickgelu')

image = preprocess(Image.open("CLIP.png")).unsqueeze(0)
text = tokenizer(["a diagram", "a dog", "a cat"])

with torch.no_grad(), torch.cuda.amp.autocast():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    image_features /= image_features.norm(dim=-1, keepdim=True)
    text_features /= text_features.norm(dim=-1, keepdim=True)

    text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)

print("Label probs:", text_probs)  # prints: [[1., 0., 0.]]

Now I would like to use it for multi-class. For example if we have on the image dog and cat I would like to have high probabilities for both, so I would need to run it with sigmoid. But this gives me results all around 0.55 with the correct classes being 0.56 and the wrong 0.54, so something like this [0.54, 0.555, 0.56]. I would like to have something like [0.01, 0.98, 0.99] after using the sigmoid.

What am I doing wrong there? How can I get the results I want?

craaaft
  • 211
  • 1
  • 8

0 Answers0