recognize module¶
Module for image recognition (classification) on ImageFolder-style datasets.
This module provides a high-level API for training and evaluating image
classification models on datasets organized as class-named subdirectories.
It supports both standard image formats (JPEG, PNG) and multi-band GeoTIFFs,
and reuses :class:~geoai.timm_train.TimmClassifier for training.
ImageDataset
¶
Bases: Dataset
Dataset for image classification supporting both standard images and GeoTIFFs.
Automatically detects the file format and uses the appropriate loader: PIL for standard images (JPEG, PNG, BMP) and rasterio for GeoTIFFs (supporting multi-band imagery with more than 3 channels).
Source code in geoai/recognize.py
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 | |
__init__(image_paths, labels, transform=None, image_size=64, in_channels=None)
¶
Initialize ImageDataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_paths
|
List[str]
|
List of paths to image files (JPEG, PNG, or GeoTIFF). |
required |
labels
|
List[int]
|
List of integer labels corresponding to images. |
required |
transform
|
Optional[Callable]
|
Optional transform to apply to images. If |
None
|
image_size
|
int
|
Target size to resize images to (height and width). |
64
|
in_channels
|
Optional[int]
|
Expected number of channels. When |
None
|
Source code in geoai/recognize.py
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 | |
evaluate_classifier(model, dataset, class_names, batch_size=32, num_workers=4, device=None)
¶
Evaluate a trained classifier on a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[TimmClassifier, Module]
|
Trained model. |
required |
dataset
|
Dataset
|
An :class: |
required |
class_names
|
List[str]
|
List of class name strings. |
required |
batch_size
|
int
|
Evaluation batch size. |
32
|
num_workers
|
int
|
Data-loading workers. |
4
|
device
|
Optional[str]
|
Device string. Auto-detected when |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with keys:
- |
Source code in geoai/recognize.py
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 | |
load_image_dataset(data_dir, extensions=None)
¶
Scan an ImageFolder-style directory to discover classes and images.
The directory should have one subdirectory per class, each containing images of that class::
1 2 3 4 5 6 | |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
str
|
Root directory of the dataset. |
required |
extensions
|
Optional[List[str]]
|
List of file extensions to include (without dot).
Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with keys:
- |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ValueError
|
If no classes or no images are found. |
Source code in geoai/recognize.py
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 | |
plot_confusion_matrix(cm, class_names, figsize=None, cmap='Blues', normalize=False)
¶
Plot a confusion matrix as a heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cm
|
ndarray
|
Confusion matrix array from :func: |
required |
class_names
|
List[str]
|
List of class name strings. |
required |
figsize
|
Optional[Tuple[int, int]]
|
Figure size. Auto-scaled from class count when |
None
|
cmap
|
str
|
Matplotlib colormap name. |
'Blues'
|
normalize
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Matplotlib |
Figure
|
|
Source code in geoai/recognize.py
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 830 | |
plot_predictions(image_paths, predictions, true_labels, class_names, num_images=20, ncols=5, figsize=None, probabilities=None)
¶
Visualize model predictions on a grid of images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_paths
|
List[str]
|
Paths to the images. |
required |
predictions
|
ndarray
|
Predicted class indices. |
required |
true_labels
|
List[int]
|
Ground-truth class indices. |
required |
class_names
|
List[str]
|
List of class name strings. |
required |
num_images
|
int
|
Maximum number of images to display. |
20
|
ncols
|
int
|
Number of columns in the grid. |
5
|
figsize
|
Optional[Tuple[int, int]]
|
Figure size. Auto-scaled when |
None
|
probabilities
|
Optional[ndarray]
|
Optional array of class probabilities for showing confidence values. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Matplotlib |
Figure
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If PIL (Pillow) is not installed. |
Source code in geoai/recognize.py
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 | |
plot_training_history(log_dir, figsize=(14, 5))
¶
Plot training and validation loss/accuracy from Lightning CSV logs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_dir
|
str
|
Path to the Lightning CSV logger output directory. The
function searches for |
required |
figsize
|
Tuple[int, int]
|
Figure size as |
(14, 5)
|
Returns:
| Name | Type | Description |
|---|---|---|
Matplotlib |
Figure
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no |
Source code in geoai/recognize.py
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 | |
predict_images(model, image_paths, class_names=None, image_size=64, in_channels=None, batch_size=32, num_workers=4, device=None)
¶
Run inference on a list of images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[TimmClassifier, Module]
|
Trained model (typically a :class: |
required |
image_paths
|
List[str]
|
Paths to images to classify. |
required |
class_names
|
Optional[List[str]]
|
Optional list of class names for labelling predictions. |
None
|
image_size
|
int
|
Image size that the model was trained with. |
64
|
in_channels
|
Optional[int]
|
Number of channels the model expects. |
None
|
batch_size
|
int
|
Inference batch size. |
32
|
num_workers
|
int
|
Data-loading workers. |
4
|
device
|
Optional[str]
|
Device string ( |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with keys:
- |
Source code in geoai/recognize.py
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 582 583 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 | |
train_image_classifier(data_dir, model_name='resnet50', num_epochs=20, batch_size=32, learning_rate=0.001, weight_decay=0.0001, image_size=64, in_channels=3, test_size=0.2, val_size=0.2, pretrained=True, freeze_backbone=False, output_dir='output', num_workers=4, seed=42, accelerator='auto', devices='auto', patience=10, extensions=None, **kwargs)
¶
Train an image classifier on an ImageFolder-style dataset.
This is a single-function API: point it at a directory of images organized by class and get back a trained model with evaluation results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dir
|
str
|
Root directory with one subdirectory per class. |
required |
model_name
|
str
|
Name of the timm model (e.g., |
'resnet50'
|
num_epochs
|
int
|
Maximum number of training epochs. |
20
|
batch_size
|
int
|
Batch size for training and evaluation. |
32
|
learning_rate
|
float
|
Learning rate for the AdamW optimizer. |
0.001
|
weight_decay
|
float
|
Weight decay for the optimizer. |
0.0001
|
image_size
|
int
|
Target image size (height and width). |
64
|
in_channels
|
int
|
Number of input channels (3 for RGB, 4+ for multispectral). |
3
|
test_size
|
float
|
Fraction of data reserved for testing. |
0.2
|
val_size
|
float
|
Fraction of remaining data reserved for validation. |
0.2
|
pretrained
|
bool
|
Whether to use pretrained weights. |
True
|
freeze_backbone
|
bool
|
If |
False
|
output_dir
|
str
|
Directory to save model checkpoints and logs. |
'output'
|
num_workers
|
int
|
Number of data-loading workers. |
4
|
seed
|
int
|
Random seed for reproducibility. |
42
|
accelerator
|
str
|
PyTorch Lightning accelerator ( |
'auto'
|
devices
|
str
|
Devices to use ( |
'auto'
|
patience
|
int
|
Early-stopping patience (epochs without improvement). |
10
|
extensions
|
Optional[List[str]]
|
Image file extensions to include. |
None
|
**kwargs
|
Any
|
Extra arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with keys:
- |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
ImportError
|
If PyTorch Lightning is not installed. |
Source code in geoai/recognize.py
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 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 449 450 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 | |