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

tasks.py 6.5 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
  1. from typing import Dict
  2. import numpy as np
  3. from sklearn import linear_model as sk_lm
  4. from sklearn import metrics as sk_mtr
  5. from sklearn import model_selection as sk_ms
  6. from sklearn import multiclass as sk_mc
  7. from sklearn import preprocessing as sk_prep
  8. import torch
  9. from torch import nn
  10. from torch_geometric.data import Data
  11. from tqdm import tqdm
  12. def evaluate_node_classification_acc(
  13. z: torch.Tensor,
  14. data: Data,
  15. masks: Dict[str, torch.Tensor],
  16. use_pytorch: bool = False,
  17. ) -> Dict[str, float]:
  18. # Normalize input
  19. z = sk_prep.normalize(X=z, norm="l2")
  20. train_mask = masks["train"]
  21. y = data.y.cpu().numpy()
  22. if use_pytorch:
  23. num_cls = y.max() + 1
  24. clf = train_pytorch_model(
  25. emb_dim=z.shape[1],
  26. num_cls=num_cls,
  27. X=z,
  28. y=y,
  29. masks=masks,
  30. )
  31. else:
  32. clf = train_sklearn_model(X=z[train_mask], y=y[train_mask])
  33. accs = {}
  34. # Compute accuracy on train, val and test sets
  35. for split in ("train", "val", "test"):
  36. mask = masks[split]
  37. y_true = y[mask]
  38. y_pred = clf.predict(X=z[mask])
  39. acc = sk_mtr.classification_report(
  40. y_true=y_true,
  41. y_pred=y_pred,
  42. output_dict=True,
  43. zero_division=0,
  44. )["accuracy"]
  45. accs[split] = acc
  46. return accs
  47. def train_sklearn_model(
  48. X: np.ndarray,
  49. y: np.ndarray,
  50. ) -> sk_lm.LogisticRegression:
  51. # Define parameter space
  52. C = 2.0 ** np.arange(-10, 10, 1)
  53. # Use grid search with cross validation to find best estimator
  54. lr_model = sk_lm.LogisticRegression(
  55. solver="liblinear",
  56. max_iter=100,
  57. )
  58. clf = sk_ms.GridSearchCV(
  59. estimator=sk_mc.OneVsRestClassifier(lr_model),
  60. param_grid={"estimator__C": C},
  61. n_jobs=len(C),
  62. cv=5,
  63. scoring="accuracy",
  64. )
  65. clf.fit(X=X, y=y)
  66. return clf.best_estimator_
  67. def train_pytorch_model(
  68. emb_dim: int,
  69. num_cls: int,
  70. X: np.ndarray,
  71. y: np.ndarray,
  72. masks: Dict[str, torch.Tensor],
  73. ) -> "LogisticRegression":
  74. # Define parameter space
  75. wd = 2.0 ** np.arange(-10, 10, 2)
  76. best_clf = None
  77. best_acc = -1
  78. pbar = tqdm(wd, desc="Train best classifier")
  79. for weight_decay in pbar:
  80. lr_model = LogisticRegression(
  81. in_dim=emb_dim,
  82. out_dim=num_cls,
  83. weight_decay=weight_decay,
  84. is_multilabel=False,
  85. )
  86. lr_model.fit(X[masks["train"]], y[masks["train"]])
  87. acc = sk_mtr.classification_report(
  88. y_true=y[masks["val"]],
  89. y_pred=lr_model.predict(X[masks["val"]]),
  90. output_dict=True,
  91. zero_division=0,
  92. )["accuracy"]
  93. if acc > best_acc:
  94. best_acc = acc
  95. best_clf = lr_model
  96. pbar.set_description(f"Best acc: {best_acc * 100.0:.2f}")
  97. pbar.close()
  98. return best_clf
  99. def evaluate_node_classification_multilabel_f1(
  100. z_train: torch.Tensor,
  101. y_train: torch.Tensor,
  102. z_val: torch.Tensor,
  103. y_val: torch.Tensor,
  104. z_test: torch.Tensor,
  105. y_test: torch.Tensor,
  106. ) -> Dict[str, float]:
  107. # Normalize input
  108. z_train = sk_prep.StandardScaler().fit_transform(X=z_train)
  109. z_val = sk_prep.StandardScaler().fit_transform(X=z_val)
  110. z_test = sk_prep.StandardScaler().fit_transform(X=z_test)
  111. # Shapes
  112. emb_dim = z_train.shape[1]
  113. num_cls = y_train.size(1)
  114. # Find best classifier for given `weight_decay` space
  115. weight_decays = 2.0 ** np.arange(-10, 10, 2)
  116. best_clf = None
  117. best_f1 = -1
  118. pbar = tqdm(weight_decays, desc="Train best classifier")
  119. for wd in pbar:
  120. lr_model = LogisticRegression(
  121. in_dim=emb_dim,
  122. out_dim=num_cls,
  123. weight_decay=wd,
  124. is_multilabel=True,
  125. )
  126. lr_model.fit(z_train, y_train.numpy())
  127. f1 = sk_mtr.f1_score(
  128. y_true=y_val,
  129. y_pred=lr_model.predict(z_val),
  130. average="micro",
  131. zero_division=0,
  132. )
  133. if f1 > best_f1:
  134. best_f1 = f1
  135. best_clf = lr_model
  136. pbar.set_description(f"Best F1: {best_f1 * 100.0:.2f}")
  137. pbar.close()
  138. # Compute metrics over all splits
  139. all_f1 = {
  140. "train": sk_mtr.f1_score(
  141. y_true=y_train,
  142. y_pred=best_clf.predict(z_train),
  143. average="micro",
  144. zero_division=0,
  145. ),
  146. "val": sk_mtr.f1_score(
  147. y_true=y_val,
  148. y_pred=best_clf.predict(z_val),
  149. average="micro",
  150. zero_division=0,
  151. ),
  152. "test": sk_mtr.f1_score(
  153. y_true=y_test,
  154. y_pred=best_clf.predict(z_test),
  155. average="micro",
  156. zero_division=0,
  157. ),
  158. }
  159. return all_f1
  160. class LogisticRegression(nn.Module):
  161. def __init__(
  162. self,
  163. in_dim: int,
  164. out_dim: int,
  165. weight_decay: float,
  166. is_multilabel: bool,
  167. ):
  168. super().__init__()
  169. self.fc = nn.Linear(in_dim, out_dim)
  170. self._optimizer = torch.optim.AdamW(
  171. params=self.parameters(),
  172. lr=0.01,
  173. weight_decay=weight_decay,
  174. )
  175. self._is_multilabel = is_multilabel
  176. self._loss_fn = (
  177. nn.BCEWithLogitsLoss()
  178. if self._is_multilabel
  179. else nn.CrossEntropyLoss()
  180. )
  181. self._num_epochs = 1000
  182. self._device = torch.device(
  183. "cuda" if torch.cuda.is_available() else "cpu"
  184. )
  185. for m in self.modules():
  186. self.weights_init(m)
  187. self.to(self._device)
  188. def weights_init(self, m):
  189. if isinstance(m, nn.Linear):
  190. torch.nn.init.xavier_uniform_(m.weight.data)
  191. if m.bias is not None:
  192. m.bias.data.fill_(0.0)
  193. def forward(self, x):
  194. return self.fc(x)
  195. def fit(self, X: np.ndarray, y: np.ndarray):
  196. self.train()
  197. X = torch.from_numpy(X).float().to(self._device)
  198. y = torch.from_numpy(y).to(self._device)
  199. for _ in tqdm(range(self._num_epochs), desc="Epochs", leave=False):
  200. self._optimizer.zero_grad()
  201. pred = self(X)
  202. loss = self._loss_fn(input=pred, target=y)
  203. loss.backward()
  204. self._optimizer.step()
  205. def predict(self, X: np.ndarray):
  206. self.eval()
  207. with torch.no_grad():
  208. pred = self(torch.from_numpy(X).float().to(self._device))
  209. if self._is_multilabel:
  210. return (pred > 0).float().cpu()
  211. else:
  212. return pred.argmax(dim=1).cpu()
Tip!

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

Comments

Loading...