|
| 1 | +import torch as th |
| 2 | +import torch.nn as nn |
| 3 | + |
| 4 | +from torchmetrics import Accuracy, Precision, Recall, AUROC |
| 5 | +from typing import Callable, Union |
| 6 | + |
| 7 | +from tint.models import Net |
| 8 | + |
| 9 | + |
| 10 | +class StateClassifier(nn.Module): |
| 11 | + def __init__( |
| 12 | + self, |
| 13 | + feature_size: int, |
| 14 | + n_state: int, |
| 15 | + hidden_size: int, |
| 16 | + rnn: str = "GRU", |
| 17 | + dropout: float = 0.5, |
| 18 | + regres: bool = True, |
| 19 | + bidirectional: bool = False, |
| 20 | + ): |
| 21 | + super().__init__() |
| 22 | + self.hidden_size = hidden_size |
| 23 | + self.n_state = n_state |
| 24 | + self.rnn_type = rnn |
| 25 | + self.regres = regres |
| 26 | + # Input to torch LSTM should be of size (batch, seq_len, input_size) |
| 27 | + if self.rnn_type == "GRU": |
| 28 | + self.rnn = nn.GRU( |
| 29 | + feature_size, |
| 30 | + self.hidden_size, |
| 31 | + bidirectional=bidirectional, |
| 32 | + batch_first=True, |
| 33 | + ) |
| 34 | + else: |
| 35 | + self.rnn = nn.LSTM( |
| 36 | + feature_size, |
| 37 | + self.hidden_size, |
| 38 | + bidirectional=bidirectional, |
| 39 | + batch_first=True, |
| 40 | + ) |
| 41 | + |
| 42 | + self.regressor = nn.Sequential( |
| 43 | + nn.BatchNorm1d(num_features=self.hidden_size), |
| 44 | + nn.ReLU(), |
| 45 | + nn.Dropout(dropout), |
| 46 | + nn.Linear(self.hidden_size, self.n_state), |
| 47 | + ) |
| 48 | + |
| 49 | + def forward(self, x, return_all: bool = False): |
| 50 | + if self.rnn_type == "GRU": |
| 51 | + all_encodings, encoding = self.rnn(x) |
| 52 | + else: |
| 53 | + all_encodings, (encoding, state) = self.rnn(x) |
| 54 | + |
| 55 | + if self.regres: |
| 56 | + if return_all: |
| 57 | + reshaped_encodings = all_encodings.reshape( |
| 58 | + all_encodings.shape[0] * all_encodings.shape[1], -1 |
| 59 | + ) |
| 60 | + return self.regressor(reshaped_encodings).reshape( |
| 61 | + all_encodings.shape[0], all_encodings.shape[1], -1 |
| 62 | + ) |
| 63 | + return self.regressor(encoding.reshape(encoding.shape[1], -1)) |
| 64 | + return encoding.reshape(encoding.shape[1], -1) |
| 65 | + |
| 66 | + |
| 67 | +class StateClassifierNet(Net): |
| 68 | + def __init__( |
| 69 | + self, |
| 70 | + feature_size: int, |
| 71 | + n_state: int, |
| 72 | + hidden_size: int, |
| 73 | + rnn: str = "GRU", |
| 74 | + dropout: float = 0.5, |
| 75 | + regres: bool = True, |
| 76 | + bidirectional: bool = False, |
| 77 | + loss: Union[str, Callable] = "mse", |
| 78 | + optim: str = "adam", |
| 79 | + lr: float = 0.001, |
| 80 | + lr_scheduler: Union[dict, str] = None, |
| 81 | + lr_scheduler_args: dict = None, |
| 82 | + l2: float = 0.0, |
| 83 | + ): |
| 84 | + classifier = StateClassifier( |
| 85 | + feature_size=feature_size, |
| 86 | + n_state=n_state, |
| 87 | + hidden_size=hidden_size, |
| 88 | + rnn=rnn, |
| 89 | + dropout=dropout, |
| 90 | + regres=regres, |
| 91 | + bidirectional=bidirectional, |
| 92 | + ) |
| 93 | + |
| 94 | + super().__init__( |
| 95 | + layers=classifier, |
| 96 | + loss=loss, |
| 97 | + optim=optim, |
| 98 | + lr=lr, |
| 99 | + lr_scheduler=lr_scheduler, |
| 100 | + lr_scheduler_args=lr_scheduler_args, |
| 101 | + l2=l2, |
| 102 | + ) |
| 103 | + self.save_hyperparameters() |
| 104 | + |
| 105 | + for stage in ["train", "val", "test"]: |
| 106 | + setattr(self, stage + "_acc", Accuracy(task="binary")) |
| 107 | + setattr(self, stage + "_pre", Precision(task="binary")) |
| 108 | + setattr(self, stage + "_rec", Recall(task="binary")) |
| 109 | + setattr(self, stage + "_auroc", AUROC(task="binary")) |
| 110 | + |
| 111 | + def forward(self, *args, **kwargs) -> th.Tensor: |
| 112 | + return self.net(*args, **kwargs) |
| 113 | + |
| 114 | + def step(self, batch, batch_idx, stage): |
| 115 | + t = th.randint(batch[1].shape[-1], (1,)).item() |
| 116 | + x, y = batch |
| 117 | + x = x[:, : t + 1] |
| 118 | + y = y[:, t] |
| 119 | + y_hat = self(x) |
| 120 | + loss = self.loss(y_hat, y) |
| 121 | + |
| 122 | + for metric in ["acc", "pre", "rec", "auroc"]: |
| 123 | + getattr(self, stage + "_" + metric)(y_hat[:, 1], y.long()) |
| 124 | + self.log(stage + "_" + metric, getattr(self, stage + "_" + metric)) |
| 125 | + |
| 126 | + return loss |
| 127 | + |
| 128 | + def predict_step(self, batch, batch_idx, dataloader_idx=0): |
| 129 | + x, y = batch |
| 130 | + return self(x) |
0 commit comments