hidehisa-arai
commited on
Commit
•
82f1345
1
Parent(s):
3a3be99
add usage
Browse files
README.md
CHANGED
@@ -1,3 +1,59 @@
|
|
1 |
---
|
2 |
license: mit
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
license: mit
|
3 |
---
|
4 |
+
|
5 |
+
# recruit-jp/japanese-clip-vit-b-32-roberta-base
|
6 |
+
|
7 |
+
## 使い方
|
8 |
+
|
9 |
+
```python
|
10 |
+
import io
|
11 |
+
import requests
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
import torch
|
15 |
+
import torchvision
|
16 |
+
from transformers import AutoTokenizer, AutoModel
|
17 |
+
|
18 |
+
model_name = "recruit-jp/japanese-clip-vit-b-32-roberta-base"
|
19 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
20 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
21 |
+
model = AutoModel.from_pretrained(model_name, trust_remote_code=True).to(device)
|
22 |
+
|
23 |
+
def _convert_to_rgb(image):
|
24 |
+
return image.convert('RGB')
|
25 |
+
|
26 |
+
|
27 |
+
preprocess = torchvision.transforms.Compose([
|
28 |
+
torchvision.transforms.Resize(size=224, interpolation=torchvision.transforms.InterpolationMode.BICUBIC, max_size=None),
|
29 |
+
torchvision.transforms.CenterCrop(size=(224, 224)),
|
30 |
+
_convert_to_rgb,
|
31 |
+
torchvision.transforms.ToTensor(),
|
32 |
+
torchvision.transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])
|
33 |
+
])
|
34 |
+
|
35 |
+
|
36 |
+
def tokenize(tokenizer, texts):
|
37 |
+
texts = ["[CLS]" + text for text in texts]
|
38 |
+
encodings = [
|
39 |
+
tokenizer(text, max_length=77, padding="max_length", truncation=True, add_special_tokens=False)["input_ids"]
|
40 |
+
for text in texts
|
41 |
+
]
|
42 |
+
return torch.LongTensor(encodings)
|
43 |
+
|
44 |
+
# Run!
|
45 |
+
image = Image.open(io.BytesIO(requests.get('https://images.pexels.com/photos/2253275/pexels-photo-2253275.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260').content))
|
46 |
+
image = preprocess(image).unsqueeze(0).to(device)
|
47 |
+
text = tokenize(tokenizer, texts=["犬", "猫", "象"]).to(device)
|
48 |
+
|
49 |
+
with torch.inference_mode():
|
50 |
+
image_features = model.get_image_features(image)
|
51 |
+
image_features /= image_features.norm(dim=-1, keepdim=True)
|
52 |
+
|
53 |
+
text_features = model.get_text_features(input_ids=text)
|
54 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
55 |
+
|
56 |
+
probs = image_features @ text_features.T
|
57 |
+
|
58 |
+
print("Label probs:", probs.cpu().numpy()[0])
|
59 |
+
```
|