Tasks
Tasks provide a convenient abstraction over the training of a model for a specific downstream task.
They encapsulate the model, optimizer, metrics, loss as well as training, validation and testing steps.
The task expects to be passed a model factory, to which the model_args arguments are passed to instantiate the model that will be trained. The models produced by this model factory should output ModelOutput instances and conform to the Model ABC.
Tasks are best leveraged using config files. Check out some examples here.
Argument parsing in configs
Argument parsing of configs relies on argument names and type hints in the code.
To pass arguments that do not conform to this (e.g. for classes that make use of **kwargs)
put those arguments in dict_kwargs
instead of init_args
.
Multi Temporal Inputs
Multi temporal inputs are also supported! However, we leverage albumentations for augmentations, and it does not support multitemporal input. We currently get around this using the following strategy in the transform:
train_transform:
- class_path: FlattenTemporalIntoChannels
# your transforms here, wrapped by these other ones
# e.g. a random flip
- class_path: albumentations.Flip
# end of your transforms
- class_path: ToTensorV2
- class_path: UnflattenTemporalFromChannels
init_args:
n_timesteps: 3 # your number of timesteps here
# alternatively, n_channels can be specified
terratorch.tasks.regression_tasks.PixelwiseRegressionTask
Bases: BaseTask
Pixelwise Regression Task that accepts models from a range of sources.
This class is analog in functionality to [PixelwiseRegressionTask] (https://torchgeo.readthedocs.io/en/stable/api/trainers.html#torchgeo.trainers.PixelwiseRegressionTask) defined by torchgeo. However, it has some important differences: - Accepts the specification of a model factory - Logs metrics per class - Does not have any callbacks by default (TorchGeo tasks do early stopping by default) - Allows the setting of optimizers in the constructor
Source code in terratorch/tasks/regression_tasks.py
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|
__init__(model_args, model_factory, loss='mse', aux_heads=None, aux_loss=None, class_weights=None, ignore_index=None, lr=0.001, optimizer=None, optimizer_hparams=None, scheduler=None, scheduler_hparams=None, freeze_backbone=False, freeze_decoder=False, plot_on_val=10, tiled_inference_parameters=None)
Constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_args
|
Dict
|
Arguments passed to the model factory. |
required |
model_factory
|
str
|
Name of ModelFactory class to be used to instantiate the model. |
required |
loss
|
str
|
Loss to be used. Currently, supports 'mse', 'rmse', 'mae' or 'huber' loss. Defaults to "mse". |
'mse'
|
aux_loss
|
dict[str, float] | None
|
Auxiliary loss weights. Should be a dictionary where the key is the name given to the loss and the value is the weight to be applied to that loss. The name of the loss should match the key in the dictionary output by the model's forward method containing that output. Defaults to None. |
None
|
class_weights
|
list[float] | None
|
List of class weights to be applied to the loss. Defaults to None. |
None
|
ignore_index
|
int | None
|
Label to ignore in the loss computation. Defaults to None. |
None
|
lr
|
float
|
Learning rate to be used. Defaults to 0.001. |
0.001
|
optimizer
|
str | None
|
Name of optimizer class from torch.optim to be used. If None, will use Adam. Defaults to None. Overriden by config / cli specification through LightningCLI. |
None
|
optimizer_hparams
|
dict | None
|
Parameters to be passed for instantiation of the optimizer. Overriden by config / cli specification through LightningCLI. |
None
|
scheduler
|
str
|
Name of Torch scheduler class from torch.optim.lr_scheduler to be used (e.g. ReduceLROnPlateau). Defaults to None. Overriden by config / cli specification through LightningCLI. |
None
|
scheduler_hparams
|
dict | None
|
Parameters to be passed for instantiation of the scheduler. Overriden by config / cli specification through LightningCLI. |
None
|
freeze_backbone
|
bool
|
Whether to freeze the backbone. Defaults to False. |
False
|
freeze_decoder
|
bool
|
Whether to freeze the decoder and segmentation head. Defaults to False. |
False
|
plot_on_val
|
bool | int
|
Whether to plot visualizations on validation. If true, log every epoch. Defaults to 10. If int, will plot every plot_on_val epochs. |
10
|
tiled_inference_parameters
|
TiledInferenceParameters | None
|
Inference parameters used to determine if inference is done on the whole image or through tiling. |
None
|
Source code in terratorch/tasks/regression_tasks.py
configure_losses()
Initialize the loss criterion.
Raises:
Type | Description |
---|---|
ValueError
|
If loss is invalid. |
Source code in terratorch/tasks/regression_tasks.py
configure_metrics()
Initialize the performance metrics.
Source code in terratorch/tasks/regression_tasks.py
predict_step(batch, batch_idx, dataloader_idx=0)
Compute the predicted class probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Returns:
Type | Description |
---|---|
Tensor
|
Output predicted probabilities. |
Source code in terratorch/tasks/regression_tasks.py
test_step(batch, batch_idx, dataloader_idx=0)
Compute the test loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/regression_tasks.py
training_step(batch, batch_idx, dataloader_idx=0)
Compute the train loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/regression_tasks.py
validation_step(batch, batch_idx, dataloader_idx=0)
Compute the validation loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/regression_tasks.py
terratorch.tasks.segmentation_tasks.SemanticSegmentationTask
Bases: BaseTask
Semantic Segmentation Task that accepts models from a range of sources.
This class is analog in functionality to class:SemanticSegmentationTask defined by torchgeo. However, it has some important differences: - Accepts the specification of a model factory - Logs metrics per class - Does not have any callbacks by default (TorchGeo tasks do early stopping by default) - Allows the setting of optimizers in the constructor
Source code in terratorch/tasks/segmentation_tasks.py
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
|
__init__(model_args, model_factory, loss='ce', aux_heads=None, aux_loss=None, class_weights=None, ignore_index=None, lr=0.001, optimizer=None, optimizer_hparams=None, scheduler=None, scheduler_hparams=None, freeze_backbone=False, freeze_decoder=False, plot_on_val=10, class_names=None, tiled_inference_parameters=None)
Constructor
Args:
Defaults to None.
model_args (Dict): Arguments passed to the model factory.
model_factory (str): ModelFactory class to be used to instantiate the model.
loss (str, optional): Loss to be used. Currently, supports 'ce', 'jaccard' or 'focal' loss.
Defaults to "ce".
aux_loss (dict[str, float] | None, optional): Auxiliary loss weights.
Should be a dictionary where the key is the name given to the loss
and the value is the weight to be applied to that loss.
The name of the loss should match the key in the dictionary output by the model's forward
method containing that output. Defaults to None.
class_weights (Union[list[float], None], optional): List of class weights to be applied to the loss.
class_weights (list[float] | None, optional): List of class weights to be applied to the loss.
Defaults to None.
ignore_index (int | None, optional): Label to ignore in the loss computation. Defaults to None.
lr (float, optional): Learning rate to be used. Defaults to 0.001.
optimizer (str | None, optional): Name of optimizer class from torch.optim to be used.
If None, will use Adam. Defaults to None. Overriden by config / cli specification through LightningCLI.
optimizer_hparams (dict | None): Parameters to be passed for instantiation of the optimizer.
Overriden by config / cli specification through LightningCLI.
scheduler (str, optional): Name of Torch scheduler class from torch.optim.lr_scheduler
to be used (e.g. ReduceLROnPlateau). Defaults to None.
Overriden by config / cli specification through LightningCLI.
scheduler_hparams (dict | None): Parameters to be passed for instantiation of the scheduler.
Overriden by config / cli specification through LightningCLI.
freeze_backbone (bool, optional): Whether to freeze the backbone. Defaults to False.
freeze_decoder (bool, optional): Whether to freeze the decoder and segmentation head. Defaults to False.
plot_on_val (bool | int, optional): Whether to plot visualizations on validation.
If true, log every epoch. Defaults to 10. If int, will plot every plot_on_val epochs.
class_names (list[str] | None, optional): List of class names passed to metrics for better naming.
Defaults to numeric ordering.
tiled_inference_parameters (TiledInferenceParameters | None, optional): Inference parameters
used to determine if inference is done on the whole image or through tiling.
Source code in terratorch/tasks/segmentation_tasks.py
configure_losses()
Initialize the loss criterion.
Raises:
Type | Description |
---|---|
ValueError
|
If loss is invalid. |
Source code in terratorch/tasks/segmentation_tasks.py
configure_metrics()
Initialize the performance metrics.
Source code in terratorch/tasks/segmentation_tasks.py
predict_step(batch, batch_idx, dataloader_idx=0)
Compute the predicted class probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Returns:
Type | Description |
---|---|
Tensor
|
Output predicted probabilities. |
Source code in terratorch/tasks/segmentation_tasks.py
test_step(batch, batch_idx, dataloader_idx=0)
Compute the test loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/segmentation_tasks.py
training_step(batch, batch_idx, dataloader_idx=0)
Compute the train loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/segmentation_tasks.py
validation_step(batch, batch_idx, dataloader_idx=0)
Compute the validation loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/segmentation_tasks.py
terratorch.tasks.classification_tasks.ClassificationTask
Bases: BaseTask
Classification Task that accepts models from a range of sources.
This class is analog in functionality to class:ClassificationTask defined by torchgeo. However, it has some important differences: - Accepts the specification of a model factory - Logs metrics per class - Does not have any callbacks by default (TorchGeo tasks do early stopping by default) - Allows the setting of optimizers in the constructor - It provides mIoU with both Micro and Macro averaging
.. note:: * 'Micro' averaging suits overall performance evaluation but may not reflect minority class accuracy. * 'Macro' averaging gives equal weight to each class, useful for balanced performance assessment across imbalanced classes.
Source code in terratorch/tasks/classification_tasks.py
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 273 274 275 276 277 278 |
|
__init__(model_args, model_factory, loss='ce', aux_heads=None, aux_loss=None, class_weights=None, ignore_index=None, lr=0.001, optimizer=None, optimizer_hparams=None, scheduler=None, scheduler_hparams=None, freeze_backbone=False, freeze_decoder=False, class_names=None)
Constructor
Args:
Defaults to None.
model_args (Dict): Arguments passed to the model factory.
model_factory (str): ModelFactory class to be used to instantiate the model.
loss (str, optional): Loss to be used. Currently, supports 'ce', 'jaccard' or 'focal' loss.
Defaults to "ce".
aux_loss (dict[str, float] | None, optional): Auxiliary loss weights.
Should be a dictionary where the key is the name given to the loss
and the value is the weight to be applied to that loss.
The name of the loss should match the key in the dictionary output by the model's forward
method containing that output. Defaults to None.
class_weights (Union[list[float], None], optional): List of class weights to be applied to the loss.
class_weights (list[float] | None, optional): List of class weights to be applied to the loss.
Defaults to None.
ignore_index (int | None, optional): Label to ignore in the loss computation. Defaults to None.
lr (float, optional): Learning rate to be used. Defaults to 0.001.
optimizer (str | None, optional): Name of optimizer class from torch.optim to be used.
If None, will use Adam. Defaults to None. Overriden by config / cli specification through LightningCLI.
optimizer_hparams (dict | None): Parameters to be passed for instantiation of the optimizer.
Overriden by config / cli specification through LightningCLI.
scheduler (str, optional): Name of Torch scheduler class from torch.optim.lr_scheduler
to be used (e.g. ReduceLROnPlateau). Defaults to None.
Overriden by config / cli specification through LightningCLI.
scheduler_hparams (dict | None): Parameters to be passed for instantiation of the scheduler.
Overriden by config / cli specification through LightningCLI.
freeze_backbone (bool, optional): Whether to freeze the backbone. Defaults to False.
freeze_decoder (bool, optional): Whether to freeze the decoder and segmentation head. Defaults to False.
class_names (list[str] | None, optional): List of class names passed to metrics for better naming.
Defaults to numeric ordering.
Source code in terratorch/tasks/classification_tasks.py
configure_losses()
Initialize the loss criterion.
Raises:
Type | Description |
---|---|
ValueError
|
If loss is invalid. |
Source code in terratorch/tasks/classification_tasks.py
configure_metrics()
Initialize the performance metrics.
Source code in terratorch/tasks/classification_tasks.py
predict_step(batch, batch_idx, dataloader_idx=0)
Compute the predicted class probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Returns:
Type | Description |
---|---|
Tensor
|
Output predicted probabilities. |
Source code in terratorch/tasks/classification_tasks.py
test_step(batch, batch_idx, dataloader_idx=0)
Compute the test loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/classification_tasks.py
training_step(batch, batch_idx, dataloader_idx=0)
Compute the train loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|
Source code in terratorch/tasks/classification_tasks.py
validation_step(batch, batch_idx, dataloader_idx=0)
Compute the validation loss and additional metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
Any
|
The output of your DataLoader. |
required |
batch_idx
|
int
|
Integer displaying index of this batch. |
required |
dataloader_idx
|
int
|
Index of the current dataloader. |
0
|