Views
No views yet
pip install -U sentence-transformers1from sentence_transformers import SentenceTransformer, util
2from PIL import Image, ImageFile
3import requests
4import torch
5
6# We use the original clip-ViT-B-32 for encoding images
7img_model = SentenceTransformer('clip-ViT-B-32')
8
9# Our text embedding model is aligned to the img_model and maps 50+
10# languages to the same vector space
11text_model = SentenceTransformer('sentence-transformers/clip-ViT-B-32-multilingual-v1')
12
13
14# Now we load and encode the images
15def load_image(url_or_path):
16 if url_or_path.startswith("http://") or url_or_path.startswith("https://"):
17 return Image.open(requests.get(url_or_path, stream=True).raw)
18 else:
19 return Image.open(url_or_path)
20
21# We load 3 images. You can either pass URLs or
22# a path on your disc
23img_paths = [
24 # Dog image
25 "https://unsplash.com/photos/QtxgNsmJQSs/download?ixid=MnwxMjA3fDB8MXxhbGx8fHx8fHx8fHwxNjM1ODQ0MjY3&w=640",
26
27 # Cat image
28 "https://unsplash.com/photos/9UUoGaaHtNE/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8Mnx8Y2F0fHwwfHx8fDE2MzU4NDI1ODQ&w=640",
29
30 # Beach image
31 "https://unsplash.com/photos/Siuwr3uCir0/download?ixid=MnwxMjA3fDB8MXxzZWFyY2h8NHx8YmVhY2h8fDB8fHx8MTYzNTg0MjYzMg&w=640"
32]
33
34images = [load_image(img) for img in img_paths]
35
36# Map images to the vector space
37img_embeddings = img_model.encode(images)
38
39# Now we encode our text:
40texts = [
41 "A dog in the snow",
42 "Eine Katze", # German: A cat
43 "Una playa con palmeras." # Spanish: a beach with palm trees
44]
45
46text_embeddings = text_model.encode(texts)
47
48# Compute cosine similarities:
49cos_sim = util.cos_sim(text_embeddings, img_embeddings)
50
51for text, scores in zip(texts, cos_sim):
52 max_img_idx = torch.argmax(scores)
53 print("Text:", text)
54 print("Score:", scores[max_img_idx] )
55 print("Path:", img_paths[max_img_idx], "\n")
56clip-ViT-B-32 and then trained a multilingual DistilBERT model as student model. Using parallel data, the multilingual student model learns to align the teachers vector space across many languages. As a result, you get an text embedding model that works for 50+ languages.SentenceTransformer(
(0): Transformer({'max_seq_length': 128, 'do_lower_case': False}) with Transformer model: DistilBertModel
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False})
(2): Dense({'in_features': 768, 'out_features': 512, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})
)1@inproceedings{reimers-2019-sentence-bert,
2 title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
3 author = "Reimers, Nils and Gurevych, Iryna",
4 booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
5 month = "11",
6 year = "2019",
7 publisher = "Association for Computational Linguistics",
8 url = "http://arxiv.org/abs/1908.10084",
9}