landcover_train module¶
Landcover Classification Training Module
This module extends the base geoai training functionality with specialized components for discrete landcover classification, including: - Enhanced loss functions with boundary weighting - Per-class frequency weighting for imbalanced datasets - Configurable ignore_index handling - Additional validation metrics
Key Features: - Maintains full compatibility with base geoai workflow - Adds optional advanced loss computation modes - Provides flexible ignore_index configuration - Optimized for multi-class landcover segmentation
Author: ValHab Project Date: November 2025
FocalLoss
¶
Bases: Module
Focal Loss for addressing class imbalance in segmentation.
Reference: Lin, T. Y., Goyal, P., Girshick, R., He, K., & Dollár, P. (2017). Focal loss for dense object detection. ICCV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
Weighting factor in range (0,1) to balance positive/negative examples |
1.0
|
|
gamma
|
Exponent of the modulating factor (1 - p_t)^gamma |
2.0
|
|
ignore_index
|
Specifies a target value that is ignored |
-100
|
|
reduction
|
Specifies the reduction to apply to the output |
'mean'
|
|
weight
|
Manual rescaling weight given to each class |
None
|
Source code in geoai/landcover_train.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 | |
forward(inputs, targets)
¶
Forward pass of focal loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Predictions (N, C, H, W) where C = number of classes |
required | |
targets
|
Ground truth (N, H, W) with class indices |
required |
Returns:
| Type | Description |
|---|---|
|
Loss value |
Source code in geoai/landcover_train.py
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 | |
LandcoverCrossEntropyLoss
¶
Bases: Module
Enhanced CrossEntropyLoss with optional ignore_index and class weights.
This extends the standard CrossEntropyLoss with more flexible ignore_index handling, specifically designed for landcover classification tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
Optional[Tensor]
|
Manual rescaling weight given to each class |
None
|
ignore_index
|
Union[int, bool]
|
Specifies a target value that is ignored. - False: No values ignored (standard behavior) - int: Specific class index to ignore (e.g., 0 for background) |
False
|
reduction
|
str
|
Specifies the reduction to apply ('mean', 'sum', 'none') |
'mean'
|
Source code in geoai/landcover_train.py
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 | |
forward(input, target)
¶
Compute cross entropy loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
Tensor
|
Predictions (N, C, H, W) where C = number of classes |
required |
target
|
Tensor
|
Ground truth (N, H, W) with class indices |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Loss value |
Source code in geoai/landcover_train.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
compute_class_weights(labels_dir, num_classes, ignore_index=-100, custom_multipliers=None, max_weight=50.0, use_inverse_frequency=True)
¶
Compute class weights for imbalanced datasets with optional custom multipliers and maximum weight cap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels_dir
|
str
|
Directory containing label files |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
Union[int, bool]
|
Class index to ignore when computing weights. - If int: specific class to ignore (pixels will be excluded from weight calc) - If False: no class ignored (all classes contribute to weights) |
-100
|
custom_multipliers
|
Optional[Dict[int, float]]
|
Custom multipliers for specific classes after inverse frequency calculation. Format: {class_id: multiplier} Example: {1: 0.5, 7: 2.0} - reduce class 1 weight by half, double class 7 weight |
None
|
max_weight
|
float
|
Maximum allowed weight value to prevent extreme values (default: 50.0) |
50.0
|
use_inverse_frequency
|
bool
|
Whether to compute inverse frequency weights. - True (default): Compute inverse frequency weights, then apply custom multipliers - False: Use uniform weights (1.0) for all classes, then apply custom multipliers |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of class weights (num_classes,) with custom adjustments and maximum weight cap applied |
Source code in geoai/landcover_train.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | |
evaluate_sparse_iou(model, images_dir, labels_dir, num_classes, num_channels=3, batch_size=8, background_class=0, ignore_index=False, device=None, verbose=True)
¶
Evaluate a trained model using sparse labels IoU.
This function is designed for incomplete/sparse ground truth where background (0) means "unlabeled" rather than "definitely not this class". Predictions in background areas are NOT penalized as false positives.
Use this for post-training evaluation when your training masks are incomplete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Trained segmentation model |
required |
images_dir
|
str
|
Directory containing validation images |
required |
labels_dir
|
str
|
Directory containing validation labels |
required |
num_classes
|
int
|
Number of classes |
required |
num_channels
|
int
|
Number of input channels (default: 3) |
3
|
batch_size
|
int
|
Batch size for evaluation (default: 8) |
8
|
background_class
|
int
|
Class ID for background/unlabeled pixels (default: 0) |
0
|
ignore_index
|
Union[int, bool]
|
Class to ignore during evaluation. - If int: specific class index to ignore - If False: no class ignored (default) |
False
|
device
|
Optional[device]
|
Torch device (auto-detected if None) |
None
|
verbose
|
bool
|
Print detailed results (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Example
model = torch.load("best_model.pth") results = evaluate_sparse_iou( ... model=model, ... images_dir="tiles/images", ... labels_dir="tiles/labels", ... num_classes=18, ... background_class=0, ... ) print(f"Sparse IoU: {results['mean_sparse_iou']:.4f}")
Source code in geoai/landcover_train.py
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 | |
get_landcover_loss_function(loss_name='crossentropy', num_classes=2, ignore_index=-100, class_weights=None, use_class_weights=False, focal_alpha=1.0, focal_gamma=2.0, device=None)
¶
Get loss function configured for landcover classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_name
|
str
|
Name of loss function ("crossentropy", "focal", "dice", "combo") |
'crossentropy'
|
num_classes
|
int
|
Number of classes |
2
|
ignore_index
|
Union[int, bool]
|
Class index to ignore, or False to not ignore any class. - If int: pixels with this label value will be ignored during training - If False: no pixels will be ignored (all pixels contribute to loss) |
-100
|
class_weights
|
Optional[Tensor]
|
Manual class weights tensor |
None
|
use_class_weights
|
bool
|
Whether to use class weights |
False
|
focal_alpha
|
float
|
Alpha parameter for focal loss |
1.0
|
focal_gamma
|
float
|
Gamma parameter for focal loss |
2.0
|
device
|
Optional[device]
|
Device to place loss function on |
None
|
Returns:
| Type | Description |
|---|---|
Module
|
Configured loss function |
Source code in geoai/landcover_train.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
landcover_iou(pred, target, num_classes, ignore_index=False, smooth=1e-06, mode='mean', boundary_weight_map=None, background_class=None)
¶
Calculate IoU for landcover classification with multiple weighting options.
Supports four IoU calculation modes: 1. "mean": Simple mean IoU across all classes 2. "perclass_frequency": Weight by per-class pixel frequency 3. "boundary_weighted": Weight by distance to class boundaries 4. "sparse_labels": For incomplete ground truth - only penalize FP where GT is positive (does NOT penalize predictions in unlabeled/background areas)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred
|
Tensor
|
Predicted classes (N, H, W) or logits (N, C, H, W) |
required |
target
|
Tensor
|
Ground truth (N, H, W) |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
Union[int, bool]
|
Class index to ignore (default: None) |
False
|
smooth
|
float
|
Smoothing factor to avoid division by zero |
1e-06
|
mode
|
str
|
IoU calculation mode ("mean", "perclass_frequency", "boundary_weighted", "sparse_labels") |
'mean'
|
boundary_weight_map
|
Optional[Tensor]
|
Optional boundary weights (N, H, W) |
None
|
background_class
|
Optional[int]
|
Background/unlabeled class for sparse_labels mode (default: 0) |
None
|
Returns:
| Type | Description |
|---|---|
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "mean": float (mean IoU) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "perclass_frequency": tuple (weighted IoU, per-class IoUs, class counts) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "boundary_weighted": float (boundary-weighted IoU) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "sparse_labels": tuple (sparse IoU, per-class IoUs, per-class recall, per-class precision) |
Source code in geoai/landcover_train.py
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 | |
train_segmentation_landcover(images_dir, labels_dir, output_dir, input_format='directory', architecture='unet', encoder_name='resnet34', encoder_weights='imagenet', num_channels=3, num_classes=2, batch_size=8, num_epochs=50, learning_rate=0.001, weight_decay=0.0001, seed=42, val_split=0.2, print_freq=10, verbose=True, save_best_only=True, plot_curves=False, device=None, checkpoint_path=None, resume_training=False, target_size=None, resize_mode='resize', num_workers=None, loss_function='crossentropy', ignore_index=0, use_class_weights=False, focal_alpha=1.0, focal_gamma=2.0, custom_multipliers=None, max_class_weight=50.0, use_inverse_frequency=True, validation_iou_mode='standard', boundary_alpha=1.0, background_class=0, training_callback=None, **kwargs)
¶
Train a semantic segmentation model with landcover-specific enhancements.
This is a standalone version that wraps geoai.train.train_segmentation_model with landcover-specific loss functions, class weights, and metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images_dir
|
str
|
Directory containing training images |
required |
labels_dir
|
str
|
Directory containing training labels |
required |
output_dir
|
str
|
Directory to save model checkpoints and training history |
required |
input_format
|
str
|
Data format ("directory", "COCO", "YOLO") |
'directory'
|
architecture
|
str
|
Model architecture (default: "unet") |
'unet'
|
encoder_name
|
str
|
Encoder backbone (default: "resnet34") |
'resnet34'
|
encoder_weights
|
Optional[str]
|
Pretrained weights ("imagenet" or None) |
'imagenet'
|
num_channels
|
int
|
Number of input channels (default: 3) |
3
|
num_classes
|
int
|
Number of output classes (default: 2) |
2
|
batch_size
|
int
|
Training batch size (default: 8) |
8
|
num_epochs
|
int
|
Number of training epochs (default: 50) |
50
|
learning_rate
|
float
|
Initial learning rate (default: 0.001) |
0.001
|
weight_decay
|
float
|
Weight decay for optimizer (default: 1e-4) |
0.0001
|
seed
|
int
|
Random seed for reproducibility (default: 42) |
42
|
val_split
|
float
|
Validation split ratio (default: 0.2) |
0.2
|
print_freq
|
int
|
Frequency of training progress prints (default: 10) |
10
|
verbose
|
bool
|
Enable verbose output (default: True) |
True
|
save_best_only
|
bool
|
Only save best model checkpoint (default: True) |
True
|
plot_curves
|
bool
|
Plot training curves at end (default: False) |
False
|
device
|
Optional[device]
|
Torch device (auto-detected if None) |
None
|
checkpoint_path
|
Optional[str]
|
Path to checkpoint for resuming training |
None
|
resume_training
|
bool
|
Whether to resume from checkpoint (default: False) |
False
|
target_size
|
Optional[Tuple[int, int]]
|
Target size for resizing images (H, W) or None |
None
|
resize_mode
|
str
|
How to resize ("resize", "crop", or "pad") |
'resize'
|
num_workers
|
Optional[int]
|
Number of dataloader workers (default: auto) |
None
|
loss_function
|
str
|
Loss function name ("crossentropy", "focal") |
'crossentropy'
|
ignore_index
|
Union[int, bool]
|
Class index to ignore during training. (default: 0) - If int: pixels with this label value will be ignored during training - If False: no pixels will be ignored (all pixels contribute to loss) |
0
|
use_class_weights
|
bool
|
Whether to compute and use class weights (default: False) |
False
|
focal_alpha
|
float
|
Focal loss alpha parameter (default: 1.0) |
1.0
|
focal_gamma
|
float
|
Focal loss gamma parameter (default: 2.0) |
2.0
|
custom_multipliers
|
Optional[Dict[int, float]]
|
Custom class weight multipliers {class_id: multiplier} |
None
|
max_class_weight
|
float
|
Maximum allowed class weight (default: 50.0) |
50.0
|
use_inverse_frequency
|
bool
|
Use inverse frequency for weights (default: True) |
True
|
validation_iou_mode
|
str
|
IoU calculation mode for validation (default: "standard") - "standard": Unweighted mean IoU (all classes equal importance) - "perclass_frequency": Frequency-weighted IoU (classes weighted by pixel count) - "boundary_weighted": Boundary-distance weighted IoU (wIoU, focus on edges) - "sparse_labels": For incomplete ground truth - predictions in background areas are NOT penalized. Uses custom training loop with sparse IoU for model selection. BEST FOR INCOMPLETE/SPARSE HABITAT MASKS. |
'standard'
|
boundary_alpha
|
float
|
Boundary importance factor for wIoU mode (default: 1.0) Higher values = more focus on boundaries (0.01-100 range) |
1.0
|
background_class
|
int
|
Class ID for background/unlabeled pixels in sparse_labels mode (default: 0). Predictions in this class area are NOT counted as false positives. |
0
|
training_callback
|
Optional[callable]
|
Optional callback function for automatic metric tracking |
None
|
**kwargs
|
Any
|
Additional arguments passed to base training function |
{}
|
Returns:
| Type | Description |
|---|---|
Module
|
Trained model |
Example
from landcover_train import train_segmentation_landcover
model = train_segmentation_landcover( ... images_dir="tiles/images", ... labels_dir="tiles/labels", ... output_dir="models/landcover_001", ... num_classes=5, ... loss_function="focal", ... ignore_index=0, # Ignore background ... use_class_weights=True, ... custom_multipliers={1: 1.5, 4: 0.8}, # Boost class 1, reduce class 4 ... max_class_weight=50.0, ... use_inverse_frequency=True, # Use inverse frequency weighting ... validation_iou_mode="boundary_weighted", # Focus on boundaries ... boundary_alpha=2.0, # Moderate boundary emphasis ... )
Source code in geoai/landcover_train.py
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 | |