Repository navigation
Expand file tree
/
Copy pathclip_util.py
More file actions
61 lines (52 loc) · 2.24 KB
/
Copy pathclip_util.py
File metadata and controls
61 lines (52 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import torch
import clip
# @torch.no_grad()
# def build_normalized_text_features(model, classnames, templates, device):
# """
# Build a zero-shot classifier weight matrix from class names and text templates.
# Each class is represented by the mean of its template embeddings (L2-normalized).
# **!! THIS FUNCTION IS NOT MEANT TO GENERATE TRAINABLE SAMPLES**
# Returns:
# zeroshot_weights: [embed_dim, num_classes] tensor
# """
# zeroshot_weights = []
# for classname in classnames:
# if callable(templates):
# # Single template function
# texts = [templates(classname)]
# elif isinstance(templates, list) and callable(templates[0]):
# # List of template functions
# texts = [t(classname) for t in templates]
# else:
# texts = [templates(classname)]
# texts = clip.tokenize(texts).to(device)
# class_embeddings = model(None, texts)
# # average all templates
# class_embeddings = class_embeddings / class_embeddings.norm(dim=-1, keepdim=True)
# class_embedding = class_embeddings.mean(dim=0)
# # normalize
# class_embedding = class_embedding / class_embedding.norm()
# zeroshot_weights.append(class_embedding)
# zeroshot_weights = torch.stack(zeroshot_weights, dim=1) # [embed_dim, num_classes]
# # 直接就是列向量
# return zeroshot_weights
def build_normalized_text_features_from_text_embedding(model, texts: torch.Tensor):
"""
Build a zero-shot classifier weight matrix from class text clip embeddings.
Returns:
class_features: [embed_dim, num_classes] tensor
"""
class_features = model(None, texts)
# normalize
class_features = class_features / class_features.norm(dim=-1, keepdim=True)
return class_features
def build_normalized_image_features_from_image_embedding(model, images: torch.Tensor):
"""
Build a zero-shot classifier weight matrix from class image clip embeddings.
Returns:
image_features: [embed_dim, num_classes] tensor
"""
image_features = model(images, None)
# normalize
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
return image_features