Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

duqmodel.py 1.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from src.model.backbone import Backbone
  5. class DUQ(nn.Module):
  6. def __init__(self,sigma,gamma,num_classes,emb_size):
  7. super(DUQ,self).__init__()
  8. self.backbone = Backbone(emb_size)
  9. self.num_classes = num_classes
  10. self.sigma = sigma
  11. self.gamma = gamma
  12. self.emb_size = emb_size
  13. self.register_buffer("n",torch.ones(num_classes) * 12)
  14. self.register_buffer(
  15. "m",torch.normal(torch.zeros(num_classes,emb_size),1)
  16. )
  17. self.W = nn.Parameter(
  18. torch.normal(torch.zeros(num_classes,emb_size,256),0.05)
  19. )
  20. def kernel(self,Wx):
  21. # Wx: [B,C,D]
  22. # cntrds: [C,D]
  23. cntrds = self.m/self.n[:,None]
  24. K = (-(Wx - cntrds)**2).mean(-1).div(2 * self.sigma**2).exp()
  25. return K
  26. def update_centroids(self,Wx,targets):
  27. # Wx: [B,C,D]
  28. # targets: [B,C]
  29. cls_embeddings = torch.einsum('bc,bcd -> cd',targets,Wx)
  30. nt = targets.sum(0)
  31. self.n = self.gamma*self.n + (1-self.gamma)*nt
  32. self.m = self.gamma*self.m + (1-self.gamma)*cls_embeddings
  33. def loss(self,K,targets):
  34. return F.binary_cross_entropy(K,targets)
  35. def forward(self,x):
  36. x = self.backbone(x)
  37. # x: [B,D]
  38. # self.W: [C,D,E]
  39. Wx = torch.einsum('bd,cde -> bce',x,self.W)
  40. return Wx
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...