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

nn_tools.py 6.9 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
  1. from typing import Optional
  2. from pytorch_lightning.metrics.functional import f1
  3. import torch
  4. from torch import Tensor
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from .tools import mask
  8. class FocalLoss(nn.Module):
  9. """ Focal Loss, as described in https://arxiv.org/abs/1708.02002.
  10. It is essentially an enhancement to cross entropy loss and is
  11. useful for classification tasks when there is a large class imbalance.
  12. x is expected to contain raw, unnormalized scores for each class.
  13. y is expected to contain class labels.
  14. Shape:
  15. - x: (batch_size, C) or (batch_size, C, d1, d2, ..., dK), K > 0.
  16. - y: (batch_size,) or (batch_size, d1, d2, ..., dK), K > 0.
  17. """
  18. def __init__(self, alpha: Optional[Tensor] = None, gamma: float = 0., reduction: str = "mean", ignore_index: int = -100):
  19. """Constructor.
  20. Args:
  21. alpha (Tensor, optional): Weights for each class. Defaults to None.
  22. gamma (float, optional): A constant, as described in the paper.
  23. Defaults to 0.
  24. reduction (str, optional): 'mean', 'sum' or 'none'.
  25. Defaults to 'mean'.
  26. ignore_index (int, optional): class label to ignore.
  27. Defaults to -100.
  28. """
  29. if reduction not in ("mean", "sum", "none"):
  30. raise ValueError("Reduction must be one of: 'mean', 'sum', 'none'.")
  31. super().__init__()
  32. self.alpha = alpha
  33. self.gamma = gamma
  34. self.ignore_index = ignore_index
  35. self.reduction = reduction
  36. self.nll_loss = nn.NLLLoss(weight=alpha, reduction="none", ignore_index=ignore_index)
  37. def __repr__(self):
  38. arg_keys = ["alpha", "gamma", "ignore_index", "reduction"]
  39. arg_vals = [self.__dict__[k] for k in arg_keys]
  40. arg_strs = [f"{k}={v}" for k, v in zip(arg_keys, arg_vals)]
  41. arg_str = ", ".join(arg_strs)
  42. return f"{type(self).__name__}({arg_str})"
  43. def forward(self, x: Tensor, y: Tensor) -> Tensor:
  44. if x.ndim > 2:
  45. # (N, C, d1, d2, ..., dK) --> (N * d1 * ... * dK, C)
  46. c = x.shape[1]
  47. x = x.permute(0, *range(2, x.ndim), 1).reshape(-1, c)
  48. # (N, d1, d2, ..., dK) --> (N * d1 * ... * dK,)
  49. y = y.view(-1)
  50. unignored_mask = y != self.ignore_index
  51. y = y[unignored_mask]
  52. if len(y) == 0:
  53. return 0.0
  54. x = x[unignored_mask]
  55. # compute weighted cross entropy term: -alpha * log(pt)
  56. # (alpha is already part of self.nll_loss)
  57. log_p = F.log_softmax(x, dim=-1)
  58. ce = self.nll_loss(log_p, y)
  59. # get true class column from each row
  60. all_rows = torch.arange(len(x))
  61. log_pt = log_p[all_rows, y]
  62. # compute focal term: (1 - pt)^gamma
  63. pt = log_pt.exp()
  64. focal_term = (1 - pt)**self.gamma
  65. # the full loss: -alpha * ((1 - pt)^gamma) * log(pt)
  66. loss = focal_term * ce
  67. if self.reduction == "mean":
  68. loss = loss.mean()
  69. elif self.reduction == "sum":
  70. loss = loss.sum()
  71. return loss
  72. def to_device(data, device):
  73. if isinstance(data, tuple) or isinstance(data, list):
  74. result = []
  75. for d in data:
  76. result.append(d.to(device))
  77. return result
  78. return data.to(device)
  79. def train(model, device, dataloader, epoch, criterion, optimizer):
  80. model.train()
  81. batch_count = len(dataloader)
  82. data_count = len(dataloader.dataset)
  83. loss_sum = 0
  84. correct_predictions = 0
  85. f1_sum = 0
  86. for batch_id, data in enumerate(dataloader):
  87. input_data, labels = data
  88. input_data, labels = to_device(input_data, device), to_device(labels, device)
  89. output = model(input_data)
  90. loss = criterion(output, labels)
  91. optimizer.zero_grad()
  92. loss.backward()
  93. optimizer.step()
  94. loss_sum += loss.item()
  95. preds = output.argmax(dim=1)
  96. f1_sum += f1(preds, labels, output.size(1), average="weighted").item()
  97. correct_predictions += torch.sum((preds == labels).double()).item()
  98. if (batch_id + 1) % 10 == 0 or batch_id + 1 == batch_count:
  99. acc_score = torch.mean((preds == labels).double())
  100. print("train epoch {} [{}/{}] - accuracy {:.6f} - loss {:.6f}".format(
  101. epoch, batch_id + 1, batch_count, acc_score.item(), loss.item()
  102. ))
  103. mean_loss = loss_sum / batch_count
  104. mean_f1 = f1_sum / batch_count
  105. accuracy = correct_predictions / data_count
  106. return mean_loss, accuracy, mean_f1
  107. def train_with_augment(model, device, dataloader, epoch, criterion, optimizer, code_column, masking_rate):
  108. model.train()
  109. batch_count = len(dataloader)
  110. data_count = len(dataloader.dataset)
  111. loss_sum = 0
  112. correct_predictions = 0
  113. f1_sum = 0
  114. for batch_id, data in enumerate(dataloader):
  115. input_data, labels = data
  116. input_data, labels = to_device(input_data, device), to_device(labels, device)
  117. output = model(input_data)
  118. loss = criterion(output, labels)
  119. optimizer.zero_grad()
  120. loss.backward()
  121. optimizer.step()
  122. loss_sum += loss.item()
  123. preds = output.argmax(dim=1)
  124. f1_sum += f1(preds, labels, output.size(1), average="weighted").item()
  125. correct_predictions += torch.sum((preds == labels).double()).item()
  126. if (batch_id + 1) % 10 == 0 or batch_id + 1 == batch_count:
  127. acc_score = torch.mean((preds == labels).double())
  128. print("train epoch {} [{}/{}] - accuracy {:.6f} - loss {:.6f}".format(
  129. epoch, batch_id + 1, batch_count, acc_score.item(), loss.item()
  130. ))
  131. mean_loss = loss_sum / batch_count
  132. mean_f1 = f1_sum / batch_count
  133. accuracy = correct_predictions / data_count
  134. return mean_loss, accuracy, mean_f1
  135. def test(model, device, dataloader, epoch, criterion):
  136. model.eval()
  137. batch_count = len(dataloader)
  138. data_count = len(dataloader.dataset)
  139. loss_sum = 0
  140. correct_predictions = 0
  141. f1_sum = 0
  142. with torch.no_grad():
  143. for data in dataloader:
  144. input_data, labels = data
  145. input_data, labels = to_device(input_data, device), to_device(labels, device)
  146. output = model(input_data)
  147. loss = criterion(output, labels)
  148. loss_sum += loss.item()
  149. preds = output.argmax(dim=1)
  150. f1_sum += f1(preds, labels, output.size(1), average="weighted").item()
  151. correct_predictions += torch.sum((preds == labels).double()).item()
  152. mean_loss = loss_sum / batch_count
  153. mean_f1 = f1_sum / batch_count
  154. accuracy = correct_predictions / data_count
  155. print("test epoch {} - accuracy {:.6f} - f-score {:.6f} - loss {:.6f}".format(
  156. epoch, accuracy, mean_f1, mean_loss
  157. ))
  158. return mean_loss, accuracy, mean_f1
  159. def augment_mask_list(batch, masking_rate):
  160. augmented = []
  161. for obj in batch:
  162. augmented.append(mask(obj, "code", masking_rate, True))
  163. return augmented
Tip!

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

Comments

Loading...