|
| 1 | +from typing import Dict |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | + |
| 6 | +from pyhealth.datasets import SampleDataset |
| 7 | +from pyhealth.models import BaseModel |
| 8 | + |
| 9 | +from .embedding import EmbeddingModel |
| 10 | + |
| 11 | + |
| 12 | +class LogisticRegression(BaseModel): |
| 13 | + """Logistic/Linear regression baseline model. |
| 14 | +
|
| 15 | + This model uses embeddings from different input features and applies a single |
| 16 | + linear transformation (no hidden layers or non-linearity) to produce predictions. |
| 17 | + |
| 18 | + - For classification tasks: acts as logistic regression |
| 19 | + - For regression tasks: acts as linear regression |
| 20 | + |
| 21 | + The model automatically handles different input types through the EmbeddingModel, |
| 22 | + pools sequence dimensions, concatenates all feature embeddings, and applies a |
| 23 | + final linear layer. |
| 24 | +
|
| 25 | + Args: |
| 26 | + dataset: the dataset to train the model. It is used to query certain |
| 27 | + information such as the set of all tokens. |
| 28 | + embedding_dim: the embedding dimension. Default is 128. |
| 29 | + **kwargs: other parameters (for compatibility). |
| 30 | +
|
| 31 | + Examples: |
| 32 | + >>> from pyhealth.datasets import SampleDataset |
| 33 | + >>> samples = [ |
| 34 | + ... { |
| 35 | + ... "patient_id": "patient-0", |
| 36 | + ... "visit_id": "visit-0", |
| 37 | + ... "conditions": ["cond-33", "cond-86", "cond-80"], |
| 38 | + ... "procedures": [1.0, 2.0, 3.5, 4], |
| 39 | + ... "label": 0, |
| 40 | + ... }, |
| 41 | + ... { |
| 42 | + ... "patient_id": "patient-1", |
| 43 | + ... "visit_id": "visit-1", |
| 44 | + ... "conditions": ["cond-33", "cond-86", "cond-80"], |
| 45 | + ... "procedures": [5.0, 2.0, 3.5, 4], |
| 46 | + ... "label": 1, |
| 47 | + ... }, |
| 48 | + ... ] |
| 49 | + >>> input_schema = {"conditions": "sequence", |
| 50 | + ... "procedures": "tensor"} |
| 51 | + >>> output_schema = {"label": "binary"} |
| 52 | + >>> dataset = SampleDataset(samples=samples, |
| 53 | + ... input_schema=input_schema, |
| 54 | + ... output_schema=output_schema, |
| 55 | + ... dataset_name="test") |
| 56 | + >>> |
| 57 | + >>> from pyhealth.models import LogisticRegression |
| 58 | + >>> model = LogisticRegression(dataset=dataset) |
| 59 | + >>> |
| 60 | + >>> from pyhealth.datasets import get_dataloader |
| 61 | + >>> train_loader = get_dataloader(dataset, batch_size=2, shuffle=True) |
| 62 | + >>> data_batch = next(iter(train_loader)) |
| 63 | + >>> |
| 64 | + >>> ret = model(**data_batch) |
| 65 | + >>> print(ret) |
| 66 | + { |
| 67 | + 'loss': tensor(0.6931, grad_fn=<BinaryCrossEntropyWithLogitsBackward0>), |
| 68 | + 'y_prob': tensor([[0.5123], |
| 69 | + [0.4987]], grad_fn=<SigmoidBackward0>), |
| 70 | + 'y_true': tensor([[1.], |
| 71 | + [0.]]), |
| 72 | + 'logit': tensor([[0.0492], |
| 73 | + [-0.0052]], grad_fn=<AddmmBackward0>) |
| 74 | + } |
| 75 | + >>> |
| 76 | +
|
| 77 | + """ |
| 78 | + |
| 79 | + def __init__( |
| 80 | + self, |
| 81 | + dataset: SampleDataset, |
| 82 | + embedding_dim: int = 128, |
| 83 | + **kwargs, |
| 84 | + ): |
| 85 | + super(LogisticRegression, self).__init__(dataset) |
| 86 | + self.embedding_dim = embedding_dim |
| 87 | + |
| 88 | + assert len(self.label_keys) == 1, "Only one label key is supported" |
| 89 | + self.label_key = self.label_keys[0] |
| 90 | + |
| 91 | + # Use the EmbeddingModel to handle embedding logic |
| 92 | + self.embedding_model = EmbeddingModel(dataset, embedding_dim) |
| 93 | + |
| 94 | + # Single linear layer (no hidden layers, no activation) |
| 95 | + output_size = self.get_output_size() |
| 96 | + self.fc = nn.Linear(len(self.feature_keys) * self.embedding_dim, output_size) |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def mean_pooling(x, mask): |
| 100 | + """Mean pooling over the middle dimension of the tensor. |
| 101 | +
|
| 102 | + Args: |
| 103 | + x: tensor of shape (batch_size, seq_len, embedding_dim) |
| 104 | + mask: tensor of shape (batch_size, seq_len) |
| 105 | +
|
| 106 | + Returns: |
| 107 | + x: tensor of shape (batch_size, embedding_dim) |
| 108 | +
|
| 109 | + Examples: |
| 110 | + >>> x.shape |
| 111 | + [128, 5, 32] |
| 112 | + >>> mean_pooling(x, mask).shape |
| 113 | + [128, 32] |
| 114 | + """ |
| 115 | + return x.sum(dim=1) / mask.sum(dim=1, keepdim=True) |
| 116 | + |
| 117 | + def forward(self, **kwargs) -> Dict[str, torch.Tensor]: |
| 118 | + """Forward propagation. |
| 119 | +
|
| 120 | + Args: |
| 121 | + **kwargs: keyword arguments for the model. The keys must contain |
| 122 | + all the feature keys and the label key. |
| 123 | +
|
| 124 | + Returns: |
| 125 | + Dict[str, torch.Tensor]: A dictionary with the following keys: |
| 126 | + - loss: a scalar tensor representing the loss. |
| 127 | + - y_prob: a tensor representing the predicted probabilities. |
| 128 | + - y_true: a tensor representing the true labels. |
| 129 | + - logit: a tensor representing the logits. |
| 130 | + - embed (optional): a tensor representing the patient |
| 131 | + embeddings if requested. |
| 132 | + """ |
| 133 | + patient_emb = [] |
| 134 | + |
| 135 | + # Preprocess inputs for EmbeddingModel |
| 136 | + processed_inputs = {} |
| 137 | + reshape_info = {} # Track which inputs were reshaped |
| 138 | + |
| 139 | + for feature_key in self.feature_keys: |
| 140 | + x = kwargs[feature_key] |
| 141 | + |
| 142 | + # Convert to tensor if not already |
| 143 | + if not isinstance(x, torch.Tensor): |
| 144 | + x = torch.tensor(x, device=self.device) |
| 145 | + else: |
| 146 | + x = x.to(self.device) |
| 147 | + |
| 148 | + # Handle 3D input: (patient, event, # of codes) -> flatten to 2D |
| 149 | + if x.dim() == 3: |
| 150 | + batch_size, seq_len, inner_len = x.shape |
| 151 | + x = x.view(batch_size, seq_len * inner_len) |
| 152 | + reshape_info[feature_key] = { |
| 153 | + "original_shape": (batch_size, seq_len, inner_len), |
| 154 | + "was_3d": True, |
| 155 | + "expanded": False, |
| 156 | + } |
| 157 | + elif x.dim() == 1: |
| 158 | + x = x.unsqueeze(0) |
| 159 | + reshape_info[feature_key] = {"was_3d": False, "expanded": True} |
| 160 | + else: |
| 161 | + reshape_info[feature_key] = {"was_3d": False, "expanded": False} |
| 162 | + |
| 163 | + processed_inputs[feature_key] = x |
| 164 | + |
| 165 | + # Pass through EmbeddingModel |
| 166 | + embedded = self.embedding_model(processed_inputs) |
| 167 | + |
| 168 | + for feature_key in self.feature_keys: |
| 169 | + x = embedded[feature_key] |
| 170 | + |
| 171 | + info = reshape_info[feature_key] |
| 172 | + if info.get("expanded") and x.dim() > 1: |
| 173 | + x = x.squeeze(0) |
| 174 | + |
| 175 | + # Handle different tensor dimensions for pooling |
| 176 | + if x.dim() == 3: |
| 177 | + # Case: (batch, seq_len, embedding_dim) - apply mean pooling |
| 178 | + mask = (x.sum(dim=-1) != 0).float() |
| 179 | + if mask.sum(dim=-1, keepdim=True).any(): |
| 180 | + x = self.mean_pooling(x, mask) |
| 181 | + else: |
| 182 | + x = x.mean(dim=1) |
| 183 | + elif x.dim() == 2: |
| 184 | + # Case: (batch, embedding_dim) - already pooled, use as is |
| 185 | + pass |
| 186 | + else: |
| 187 | + raise ValueError(f"Unsupported tensor dimension: {x.dim()}") |
| 188 | + |
| 189 | + patient_emb.append(x) |
| 190 | + |
| 191 | + # Concatenate all feature embeddings |
| 192 | + patient_emb = torch.cat(patient_emb, dim=1) |
| 193 | + |
| 194 | + # Apply single linear layer (no activation) |
| 195 | + logits = self.fc(patient_emb) |
| 196 | + |
| 197 | + # Obtain y_true, loss, y_prob |
| 198 | + y_true = kwargs[self.label_key].to(self.device) |
| 199 | + loss = self.get_loss_function()(logits, y_true) |
| 200 | + y_prob = self.prepare_y_prob(logits) |
| 201 | + |
| 202 | + results = { |
| 203 | + "loss": loss, |
| 204 | + "y_prob": y_prob, |
| 205 | + "y_true": y_true, |
| 206 | + "logit": logits, |
| 207 | + } |
| 208 | + if kwargs.get("embed", False): |
| 209 | + results["embed"] = patient_emb |
| 210 | + return results |
| 211 | + |
| 212 | + |
| 213 | +if __name__ == "__main__": |
| 214 | + from pyhealth.datasets import SampleDataset |
| 215 | + |
| 216 | + samples = [ |
| 217 | + { |
| 218 | + "patient_id": "patient-0", |
| 219 | + "visit_id": "visit-0", |
| 220 | + "conditions": ["cond-33", "cond-86", "cond-80"], |
| 221 | + "procedures": [1.0, 2.0, 3.5, 4], |
| 222 | + "label": 0, |
| 223 | + }, |
| 224 | + { |
| 225 | + "patient_id": "patient-1", |
| 226 | + "visit_id": "visit-1", |
| 227 | + "conditions": ["cond-33", "cond-86", "cond-80"], |
| 228 | + "procedures": [5.0, 2.0, 3.5, 4], |
| 229 | + "label": 1, |
| 230 | + }, |
| 231 | + ] |
| 232 | + |
| 233 | + # Define input and output schemas |
| 234 | + input_schema = { |
| 235 | + "conditions": "sequence", # sequence of condition codes |
| 236 | + "procedures": "tensor", # tensor of procedure values |
| 237 | + } |
| 238 | + output_schema = {"label": "binary"} # binary classification |
| 239 | + |
| 240 | + # dataset |
| 241 | + dataset = SampleDataset( |
| 242 | + samples=samples, |
| 243 | + input_schema=input_schema, |
| 244 | + output_schema=output_schema, |
| 245 | + dataset_name="test", |
| 246 | + ) |
| 247 | + |
| 248 | + # data loader |
| 249 | + from pyhealth.datasets import get_dataloader |
| 250 | + |
| 251 | + train_loader = get_dataloader(dataset, batch_size=2, shuffle=True) |
| 252 | + |
| 253 | + # model |
| 254 | + model = LogisticRegression(dataset=dataset) |
| 255 | + |
| 256 | + # data batch |
| 257 | + data_batch = next(iter(train_loader)) |
| 258 | + |
| 259 | + # try the model |
| 260 | + ret = model(**data_batch) |
| 261 | + print(ret) |
| 262 | + |
| 263 | + # try loss backward |
| 264 | + ret["loss"].backward() |
0 commit comments