API Reference
The architecture of the package can be seen on the UML diagram:
HyperSpectral Image
HSI
A dataclass for hyperspectral image data, including the image, wavelengths, and binary mask.
Attributes:
Name | Type | Description |
---|---|---|
image |
Tensor
|
The hyperspectral image data as a PyTorch tensor. |
wavelengths |
Tensor
|
The wavelengths present in the image. |
orientation |
tuple[str, str, str]
|
The orientation of the image data. |
device |
device
|
The device to be used for inference. |
binary_mask |
Tensor
|
A binary mask used to cover unimportant parts of the image. |
Source code in src/meteors/hsi.py
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 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 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 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 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 |
|
spatial_binary_mask: torch.Tensor
property
Returns a 2D spatial representation of the binary mask.
This property extracts a single 2D slice from the 3D binary mask, assuming that the mask is identical across all spectral bands. It handles different data orientations by first ensuring the spectral dimension is the last dimension before extracting the 2D spatial mask.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A 2D tensor representing the spatial binary mask. The shape will be (H, W) where H is height and W is width of the image. |
Note
- This assumes that the binary mask is consistent across all spectral bands.
- The returned mask is always 2D, regardless of the original data orientation.
Examples:
>>> # If self.binary_mask has shape (100, 100, 5) with spectral_axis=2:
>>> hsi_image = HSI(binary_mask=torch.rand(100, 100, 5), orientation=("H", "W", "C"))
>>> hsi_image.spatial_binary_mask.shape
torch.Size([100, 100])
>>> If self.binary_mask has shape (5, 100, 100) with spectral_axis=0:
>>> hsi_image = HSI(binary_mask=torch.rand(5, 100, 100), orientation=("C", "H", "W"))
>>> hsi_image.spatial_binary_mask.shape
torch.Size([100, 100])
spectral_axis: int
property
Returns the index of the spectral (wavelength) axis based on the current data orientation.
In hyperspectral imaging, the spectral axis represents the dimension along which different spectral bands or wavelengths are arranged. This property dynamically determines the index of this axis based on the current orientation of the data.
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The index of the spectral axis in the current data structure. - 0 for 'CHW' or 'CWH' orientations (Channel/Wavelength first) - 2 for 'HWC' or 'WHC' orientations (Channel/Wavelength last) - 1 for 'HCW' or 'WCH' orientations (Channel/Wavelength in the middle) |
Note
The orientation is typically represented as a string where: - 'C' represents the spectral/wavelength dimension - 'H' represents the height (rows) of the image - 'W' represents the width (columns) of the image
Examples:
>>> hsi_image = HSI()
>>> hsi_image.orientation = "CHW"
>>> hsi_image.spectral_axis
0
>>> hsi_image.orientation = "HWC"
>>> hsi_image.spectral_axis
2
change_orientation(target_orientation, inplace=False)
Changes the orientation of the hsi data to the target orientation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_orientation
|
(tuple[str, str, str], list[str], str)
|
The target orientation for the hsi data. This should be a tuple of three one-letter strings in any order: "C", "H", "W". |
required |
inplace
|
bool
|
Whether to modify the hsi data in place or return a new object. |
False
|
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The updated HSI object with the new orientation. |
Raises:
Type | Description |
---|---|
ValueError
|
If the target orientation is not a valid tuple of three one-letter strings. |
Source code in src/meteors/hsi.py
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 |
|
extract_band_by_name(band_name, selection_method='center', apply_mask=True, apply_min_cutoff=False, normalize=True)
Extracts a single spectral band from the hyperspectral image based on a standardized band name.
This method uses the spyndex library to map standardized band names to wavelength ranges, then extracts the corresponding band from the hyperspectral data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
band_name
|
str
|
The standardized name of the band to extract (e.g., "Red", "NIR", "SWIR1"). |
required |
selection_method
|
str
|
The method to use for selecting the band within the wavelength range. Currently, only "center" is supported, which selects the central wavelength. Defaults to "center". |
'center'
|
apply_mask
|
bool
|
Whether to apply the binary mask to the extracted band. Defaults to True. |
True
|
apply_min_cutoff
|
bool
|
Whether to apply a minimum intensity cutoff after normalization. If True, sets the minimum non-zero value to zero. Defaults to False. |
False
|
normalize
|
bool
|
Whether to normalize the band values to the [0, 1] range. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A 2D tensor representing the extracted and processed spectral band. Shape will be (H, W), where H is height and W is width of the image. |
Raises:
Type | Description |
---|---|
BandSelectionError
|
If the specified band name is not found in the spyndex library. |
NotImplementedError
|
If a selection method other than "center" is specified. |
Notes
- The spyndex library is used to map band names to wavelength ranges.
- Currently, only the "center" selection method is implemented, which chooses the central wavelength within the specified range.
- Processing steps are applied in the order: normalization, cutoff, masking.
Examples:
>>> hsi_image = HSI(image=torch.rand(200, 100, 100), wavelengths=np.linspace(400, 2500, 200))
>>> red_band = hsi_image.extract_band_by_name("Red")
>>> red_band.shape
torch.Size([100, 100])
>>> # Extract NIR band without normalization or masking
>>> nir_band = hsi_image.extract_band_by_name("NIR", apply_mask=False, normalize=False)
Source code in src/meteors/hsi.py
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 616 617 618 619 620 621 622 623 624 625 626 627 |
|
get_image(apply_mask=True)
Returns the hyperspectral image data with optional masking applied.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
apply_mask
|
bool
|
Whether to apply the binary mask to the image. Defaults to True. |
True
|
Returns: torch.Tensor: The hyperspectral image data.
Notes
- If apply_mask is True, the binary mask will be applied to the image based on the
binary_mask
attribute.
Examples:
>>> hsi_image = HSI(image=torch.rand(10, 100, 100), wavelengths=np.linspace(400, 1000, 10))
>>> image = hsi_image.get_image()
>>> image.shape
torch.Size([10, 100, 100])
>>> image = hsi_image.get_image(apply_mask=False)
>>> image.shape
torch.Size([10, 100, 100])
Source code in src/meteors/hsi.py
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
|
get_rgb_image(apply_mask=True, apply_min_cutoff=False, output_channel_axis=None, normalize=True)
Extracts an RGB representation from the hyperspectral image data.
This method creates a 3-channel RGB image by selecting appropriate bands corresponding to red, green, and blue wavelengths from the hyperspectral data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
apply_mask
|
bool
|
Whether to apply the binary mask to the image. Defaults to True. |
True
|
apply_min_cutoff
|
bool
|
Whether to apply a minimum intensity cutoff to the image. Defaults to False. |
False
|
output_channel_axis
|
int | None
|
The axis where the RGB channels should be placed in the output tensor. If None, uses the current spectral axis of the hyperspectral data. Defaults to None. |
None
|
normalize
|
bool
|
Whether to normalize the band values to the [0, 1] range. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The RGB representation of the hyperspectral image. Shape will be either (H, W, 3), (3, H, W), or (H, 3, W) depending on the specified output_channel_axis, where H is height and W is width. |
Notes
- The RGB bands are extracted using predefined wavelength ranges for R, G, and B.
- Each band is normalized independently before combining into the RGB image.
- If apply_mask is True, masked areas will be set to zero in the output.
- If apply_min_cutoff is True, a minimum intensity threshold is applied to each band.
Examples:
>>> hsi_image = HSI(image=torch.rand(10, 100, 100), wavelengths=np.linspace(400, 1000, 10))
>>> rgb_image = hsi_image.get_rgb_image()
>>> rgb_image.shape
torch.Size([100, 100, 3])
>>> rgb_image = hsi_image.get_rgb_image(output_channel_axis=0)
>>> rgb_image.shape
torch.Size([3, 100, 100])
>>> rgb_image = hsi_image.get_rgb_image(apply_mask=False, apply_min_cutoff=True)
>>> rgb_image.shape
torch.Size([100, 100, 3])
Source code in src/meteors/hsi.py
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 |
|
to(device)
Moves the image and binary mask (if available) to the specified device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
str or device
|
The device to move the image and binary mask to. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The updated HSI object. |
Examples:
>>> # Create an HSI object
>>> hsi_image = HSI(image=torch.rand(10, 10, 10), wavelengths=np.arange(10))
>>> # Move the image to cpu
>>> hsi_image = hsi_image.to("cpu")
>>> hsi_image.device
device(type='cpu')
>>> # Move the image to cuda
>>> hsi_image = hsi_image.to("cuda")
>>> hsi_image.device
device(type='cuda', index=0)
Source code in src/meteors/hsi.py
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 |
|
Visualizations
Visualizes a Hyperspectral image object on the given axes. It uses either the object from HSI class or a field from the HSIAttributes class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi_or_attributes
|
HSI | HSIAttributes
|
The hyperspectral image, or the attributes to be visualized. |
required |
ax
|
Axes | None
|
The axes on which the image will be plotted. If None, the current axes will be used. |
None
|
use_mask
|
bool
|
Whether to use the image mask if provided for the visualization. |
True
|
Returns:
Type | Description |
---|---|
Axes
|
matplotlib.figure.Figure | None: If use_pyplot is False, returns the figure and axes objects. If use_pyplot is True, returns None. |
Raises:
Type | Description |
---|---|
TypeError
|
If hsi_or_attributes is not an instance of HSI or HSIAttributes. |
Source code in src/meteors/visualize/hsi_visualize.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
visualize_attributes(image_attributes, ax=None, use_pyplot=False)
Visualizes the attributes of an image on the given axes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image_attributes
|
HSIAttributes
|
The image attributes to be visualized. |
required |
ax
|
Axes | None
|
The axes to visualize the image on. If None, creates a new figure and axes. |
None
|
use_pyplot
|
bool
|
If True, uses pyplot to display the image. If False, returns the figure and axes objects. if ax is not None, use_pyplot is ignored. |
False
|
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
matplotlib.figure.Figure | matplotlib.axes.Axes | None: The figure and axes objects. If use_pyplot is False and ax is None, returns the figure and axes objects. If use_pyplot is True and ax is None, returns None, and displays the image using pyplot. if ax is not None, returns the axes object. If all the attributions are zero, returns None. |
Raises:
Type | Description |
---|---|
ValueError
|
If the axes have less than 2 rows and 2 columns |
ValueError
|
If the axes object is not a list of axes objects |
Source code in src/meteors/visualize/attr_visualize.py
22 23 24 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 |
|
visualize_spatial_aggregated_attributes(attributes, aggregated_mask, ax=None, use_pyplot=False, aggregate_func=torch.mean)
Visualizes the spatial attributes of an hsi object aggregated by a custom mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attributes
|
HSIAttributes
|
The spatial attributes of the hsi object to visualize. |
required |
aggregated_mask
|
Tensor | ndarray
|
The mask used to aggregate the spatial attributes. |
required |
ax
|
Axes | None
|
The axes object to plot the visualization on. If None, a new axes will be created. |
None
|
use_pyplot
|
bool
|
If True, displays the visualization using pyplot. If ax is not None, use_pyplot is ignored. If False, returns the figure and axes objects. Defaults to False. |
False
|
aggregate_func
|
Callable[[Tensor], Tensor]
|
The aggregation function to be applied. The function should take a tensor as input and return a tensor as output. We recommend using torch functions. Defaults to torch.mean. |
mean
|
Raises:
Type | Description |
---|---|
ShapeMismatchError
|
If the shape of the aggregated mask does not match the shape of the spatial attributes. |
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
tuple[Figure, Axes] | Axes | None: If ax is not None, returns the axes object. If use_pyplot is True, returns None. If use_pyplot is False, returns the figure and axes objects. |
Source code in src/meteors/visualize/attr_visualize.py
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 616 617 618 619 620 |
|
visualize_spectral_aggregated_attributes(attributes, band_names, band_mask, ax=None, use_pyplot=False, color_palette=None, show_not_included=True, aggregate_func=torch.mean)
Visualizes the spectral attributes of an hsi object aggregated by a custom band mask.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attributes
|
HSIAttributes | list[HSIAttributes]
|
The spectral attributes of the hsi object to visualize. |
required |
band_names
|
dict[str | tuple[str, ...], int]
|
A dictionary mapping band names to their indices. |
required |
band_mask
|
Tensor | ndarray
|
The mask used to aggregate the spectral attributes. |
required |
ax
|
Axes | None
|
The axes object to plot the visualization on. If None, a new axes will be created. |
None
|
use_pyplot
|
bool
|
If True, displays the visualization using pyplot. If ax is not None, use_pyplot is ignored. If False, returns the figure and axes objects. Defaults to False. |
False
|
color_palette
|
list[str] | None
|
The color palette to use for visualizing different spectral bands. If None, a default color palette is used. Defaults to None. |
None
|
show_not_included
|
bool
|
If True, includes the spectral bands that are not included in the visualization. If False, only includes the spectral bands that are included in the visualization. Defaults to True. |
True
|
aggregate_func
|
Callable[[Tensor], Tensor]
|
The aggregation function to be applied. The function should take a tensor as input and return a tensor as output. We recommend using torch functions. Defaults to torch.mean. |
mean
|
Raises:
Type | Description |
---|---|
ShapeMismatchError
|
If the shape of the band mask does not match the shape of the spectral attributes. |
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
tuple[Figure, Axes] | Axes | None: If ax is not None, returns the axes object. If use_pyplot is True, returns None. If use_pyplot is False, returns the figure and axes objects |
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
visualize_aggregated_attributes(attributes, mask, band_names=None, ax=None, use_pyplot=False, color_palette=None, show_not_included=True, aggregate_func=torch.mean)
Visualizes the aggregated attributes of an hsi object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attributes
|
HSIAttributes | list[HSIAttributes]
|
The attributes of the hsi object to visualize. |
required |
mask
|
Tensor | ndarray
|
The mask used to aggregate the attributes. |
required |
band_names
|
dict[str | tuple[str, ...], int] | None
|
A dictionary mapping band names to their indices. If None, the visualization will be spatially aggregated. Defaults to None. |
None
|
ax
|
Axes | None
|
The axes object to plot the visualization on. If None, a new axes will be created. |
None
|
use_pyplot
|
bool
|
If True, displays the visualization using pyplot. If ax is not None, use_pyplot is ignored. If False, returns the figure and axes objects. Defaults to False. |
False
|
color_palette
|
list[str] | None
|
The color palette to use for visualizing different spectral bands. If None, a default color palette is used. Defaults to None. |
None
|
show_not_included
|
bool
|
If True, includes the spectral bands that are not included in the visualization. If False, only includes the spectral bands that are included in the visualization. Defaults to True. |
True
|
aggregate_func
|
Callable[[Tensor], Tensor]
|
The aggregation function to be applied. The function should take a tensor as input and return a tensor as output. We recommend using torch functions. Defaults to torch.mean. |
mean
|
Raises:
Type | Description |
---|---|
ValueError
|
If the shape of the mask does not match the shape of the attributes. |
AssertionError
|
If band_names is None and attributes is a list of HSIAttributes objects. |
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
tuple[Figure, Axes] | Axes | None: If ax is not None, returns the axes object. If use_pyplot is True, returns None. If use_pyplot is False, returns the figure and axes objects. |
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
visualize_spectral_attributes_by_waveband(spectral_attributes, ax, color_palette=None, show_not_included=True, show_legend=True)
Visualizes spectral attributes by waveband.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spectral_attributes
|
HSISpectralAttributes | list[HSISpectralAttributes]
|
The spectral attributes to visualize. |
required |
ax
|
Axes | None
|
The matplotlib axes to plot the visualization on. If None, a new axes will be created. |
required |
color_palette
|
list[str] | None
|
The color palette to use for plotting. If None, a default color palette will be used. |
None
|
show_not_included
|
bool
|
Whether to show the "not_included" band in the visualization. Default is True. |
True
|
show_legend
|
bool
|
Whether to show the legend in the visualization. |
True
|
Returns:
Name | Type | Description |
---|---|---|
Axes |
Axes
|
The matplotlib axes object containing the visualization. |
Raises: TypeError: If the spectral attributes are not an HSISpectralAttributes object or a list of HSISpectralAttributes objects.
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
visualize_spectral_attributes_by_magnitude(spectral_attributes, ax, color_palette=None, annotate_bars=True, show_not_included=True)
Visualizes the spectral attributes by magnitude.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spectral_attributes
|
HSISpectralAttributes | list[HSISpectralAttributes]
|
The spectral attributes to visualize. |
required |
ax
|
Axes | None
|
The matplotlib Axes object to plot the visualization on. If None, a new Axes object will be created. |
required |
color_palette
|
list[str] | None
|
The color palette to use for the visualization. If None, a default color palette will be used. |
None
|
annotate_bars
|
bool
|
Whether to annotate the bars with their magnitudes. Defaults to True. |
True
|
show_not_included
|
bool
|
Whether to show the 'not_included' band in the visualization. Defaults to True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
Axes |
Axes
|
The matplotlib Axes object containing the visualization. |
Raises: TypeError: If the spectral attributes are not an HSISpectralAttributes object or a list of HSISpectralAttributes objects.
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
visualize_spectral_attributes(spectral_attributes, ax=None, use_pyplot=False, color_palette=None, show_not_included=True)
Visualizes the spectral attributes of an hsi object or a list of hsi objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spectral_attributes
|
HSISpectralAttributes | list[HSISpectralAttributes]
|
The spectral attributes of the image object to visualize. |
required |
ax
|
Axes | None
|
The axes object to plot the visualization on. If None, a new axes will be created. |
None
|
use_pyplot
|
bool
|
If ax is not None, use_pyplot is ignored. If True, displays the visualization using pyplot. If False, returns the figure and axes objects. Defaults to False. |
False
|
color_palette
|
list[str] | None
|
The color palette to use for visualizing different spectral bands. If None, a default color palette is used. Defaults to None. |
None
|
show_not_included
|
bool
|
If True, includes the spectral bands that are not included in the visualization. If False, only includes the spectral bands that are included in the visualization. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes] | matplotlib.axes.Axes | None: If ax is not None, returns the axes object. If use_pyplot is True, returns None. If use_pyplot is False, returns the figure and axes objects. |
Raises:
Type | Description |
---|---|
ValueError
|
If ax is provided as a single axes object and not a list of axes objects. |
ValueError
|
If agg is True and the axes have less than 3 rows or 3 columns. |
ValueError
|
If agg is False and the axes have less than 2 rows or 2 columns. |
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
visualize_spatial_attributes(spatial_attributes, ax=None, use_pyplot=False)
Visualizes the spatial attributes of an hsi using Lime attribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spatial_attributes
|
HSISpatialAttributes
|
The spatial attributes of the image object to visualize. |
required |
ax
|
Axes | None
|
The axes object to plot the visualization on. If None, a new axes will be created. |
None
|
use_pyplot
|
bool
|
Whether to use pyplot for visualization. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
tuple[Figure, Axes] | Axes | None
|
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes] | matplotlib.axes.Axes | None: If ax is not None, returns the axes object. If use_pyplot is True, returns None. If use_pyplot is False, returns the figure and axes objects. |
Raises:
Type | Description |
---|---|
ValueError
|
If the axes have less 3 rows or 3 columns |
ValueError
|
If the axes object is not a list of axes objects |
Source code in src/meteors/visualize/attr_visualize.py
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 |
|
Attribution Methods
HSIAttributes
Bases: BaseModel
Represents an object that contains Hyperspectral image attributes and explanations.
Attributes:
Name | Type | Description |
---|---|---|
hsi |
HSI
|
Hyperspectral image object for which the explanations were created. |
attributes |
Tensor
|
Attributions (explanations) for the hsi. |
score |
float
|
The score provided by the interpretable model. Can be None if method don't provide one. |
device |
device
|
Device to be used for inference. If None, the device of the input hsi will be used. Defaults to None. |
attribution_method |
str | None
|
The method used to generate the explanation. Defaults to None. |
Source code in src/meteors/attr/attributes.py
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 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 |
|
flattened_attributes: torch.Tensor
property
Returns a flattened tensor of attributes.
This method should be implemented in the subclass.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A flattened tensor of attributes. |
orientation: tuple[str, str, str]
property
Returns the orientation of the hsi.
Returns:
Type | Description |
---|---|
tuple[str, str, str]
|
tuple[str, str, str]: The orientation of the hsi corresponding to the attributes. |
change_orientation(target_orientation, inplace=False)
Changes the orientation of the image data along with the attributions to the target orientation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_orientation
|
tuple[str, str, str] | list[str] | str
|
The target orientation for the attribution data. This should be a tuple of three one-letter strings in any order: "C", "H", "W". |
required |
inplace
|
bool
|
Whether to modify the data in place or return a new object. |
False
|
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The updated Image object with the new orientation. |
Raises:
Type | Description |
---|---|
OrientationError
|
If the target orientation is not a valid tuple of three one-letter strings. |
Source code in src/meteors/attr/attributes.py
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 |
|
to(device)
Move the hsi and attributes tensors to the specified device.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
str or device
|
The device to move the tensors to. |
required |
Returns:
Name | Type | Description |
---|---|---|
Self |
Self
|
The modified object with tensors moved to the specified device. |
Examples:
>>> attrs = HSIAttributes(hsi, attributes, score=0.5)
>>> attrs.to("cpu")
>>> attrs.hsi.device
device(type='cpu')
>>> attrs.attributes.device
device(type='cpu')
>>> attrs.to("cuda")
>>> attrs.hsi.device
device(type='cuda')
>>> attrs.attributes.device
device(type='cuda')
Source code in src/meteors/attr/attributes.py
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 |
|
HSISpatialAttributes
Bases: HSIAttributes
Represents spatial attributes of an hsi used for explanation.
Attributes:
Name | Type | Description |
---|---|---|
hsi |
HSI
|
Hyperspectral image object for which the explanations were created. |
attributes |
Tensor
|
Attributions (explanations) for the hsi. |
score |
float
|
The score provided by the interpretable model. Can be None if method don't provide one. |
device |
device
|
Device to be used for inference. If None, the device of the input hsi will be used. Defaults to None. |
attribution_method |
str | None
|
The method used to generate the explanation. Defaults to None. |
segmentation_mask |
Tensor
|
Spatial (Segmentation) mask used for the explanation. |
flattened_attributes |
Tensor
|
Spatial 2D attribution map. |
Source code in src/meteors/attr/attributes.py
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 |
|
flattened_attributes: torch.Tensor
property
Returns a flattened tensor of attributes, with removed repeated dimensions.
In the case of spatial attributes, the flattened attributes are 2D spatial attributes of shape (rows, columns) and the spectral dimension is removed.
Examples:
>>> segmentation_mask = torch.zeros((3, 2, 2))
>>> attrs = HSISpatialAttributes(hsi, attributes, score=0.5, segmentation_mask=segmentation_mask)
>>> attrs.flattened_attributes
tensor([[0., 0.],
[0., 0.]])
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A flattened tensor of attributes. |
segmentation_mask: torch.Tensor
property
Returns the 2D spatial segmentation mask that has the same size as the hsi image.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The segmentation mask tensor. |
Raises:
Type | Description |
---|---|
HSIAttributesError
|
If the segmentation mask is not provided in the attributes object. |
HSISpectralAttributes
Bases: HSIAttributes
Represents an hsi with spectral attributes used for explanation.
Attributes:
Name | Type | Description |
---|---|---|
hsi |
HSI
|
Hyperspectral hsi object for which the explanations were created. |
attributes |
Tensor
|
Attributions (explanations) for the hsi. |
score |
float
|
R^2 score of interpretable model used for the explanation. |
device |
device
|
Device to be used for inference. If None, the device of the input hsi will be used. Defaults to None. |
attribution_method |
str | None
|
The method used to generate the explanation. Defaults to None. |
band_mask |
Tensor
|
Band mask used for the explanation. |
band_names |
dict[str | tuple[str, ...], int]
|
Dictionary that translates the band names into the band segment ids. |
flattened_attributes |
Tensor
|
Spectral 1D attribution map. |
Source code in src/meteors/attr/attributes.py
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 |
|
band_mask: torch.Tensor
property
Returns a 1D band mask - a band mask with removed repeated dimensions (num_bands, ), where num_bands is the number of bands in the hsi image.
The method selects the appropriate dimensions from the band_mask
tensor
based on the axis_to_select
and returns a flattened version of the selected
tensor.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The flattened band mask tensor. |
Examples:
>>> band_names = {"R": 0, "G": 1, "B": 2}
>>> attrs = HSISpectralAttributes(hsi, attributes, score=0.5, mask=band_mask)
>>> attrs.flattened_band_mask
torch.tensor([0, 1, 2])
flattened_attributes: torch.Tensor
property
Returns a flattened tensor of attributes with removed repeated dimensions.
In the case of spectral attributes, the flattened attributes are 1D tensor of shape (num_bands, ), where num_bands is the number of bands in the hsi image.
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A flattened tensor of attributes. |
Lime
Bases: Explainer
Lime class is a subclass of Explainer and represents the Lime explainer. Lime is an interpretable model-agnostic
explanation method that explains the predictions of a black-box model by approximating it with a simpler
interpretable model. The Lime method is based on the captum
implementation
and is an implementation of an idea coming from the original paper on Lime,
where more details about this method can be found.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
explainable_model
|
ExplainableModel
|
The explainable model to be explained. |
required |
interpretable_model
|
InterpretableModel
|
The interpretable model used to approximate the black-box model.
Defaults to |
SkLearnLasso(alpha=0.08)
|
similarity_func
|
Callable[[Tensor], Tensor] | None
|
The similarity function used by Lime. Defaults to None. |
None
|
perturb_func
|
Callable[[Tensor], Tensor] | None
|
The perturbation function used by Lime. Defaults to None. |
None
|
Source code in src/meteors/attr/lime.py
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 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 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 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 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 830 831 832 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 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 |
|
attribute(hsi, target=None, attribution_type=None, additional_forward_args=None, **kwargs)
A wrapper function to attribute the image using the LIME method. It executes either the
get_spatial_attributes
or get_spectral_attributes
method based on the provided attribution_type
. For more
detailed description of the methods, please refer to the respective method documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSISpatialAttributes or HSISpectralAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
attribution_type
|
Literal['spatial', 'spectral'] | None
|
The type of attribution to be computed. User can compute spatial or spectral attributions with the LIME method. If None, the method will throw an error. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
kwargs
|
Any
|
Additional keyword arguments for the LIME method. |
{}
|
Returns:
Type | Description |
---|---|
HSISpatialAttributes | HSISpectralAttributes | list[HSISpatialAttributes] | list[HSISpectralAttributes]
|
HSISpectralAttributes | HSISpatialAttributes | list[HSISpectralAttributes | HSISpatialAttributes]: The computed attributions Spectral or Spatial for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the Lime object is not initialized or is not an instance of LimeBase. |
ValueError
|
If number of HSI images is not equal to the number of masks provided. |
Examples:
>>> simple_model = lambda x: torch.rand((x.shape[0], 2))
>>> hsi = mt.HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> segmentation_mask = torch.randint(1, 4, (1, 240, 240))
>>> lime = meteors.attr.Lime(
explainable_model=ExplainableModel(simple_model, "regression"), interpretable_model=SkLearnLasso(alpha=0.1)
)
>>> spatial_attribution = lime.attribute(hsi, segmentation_mask=segmentation_mask, target=0, attribution_type="spatial")
>>> spatial_attribution.hsi
HSI(shape=(4, 240, 240), dtype=torch.float32)
>>> band_mask = torch.randint(1, 4, (4, 1, 1)).repeat(1, 240, 240)
>>> band_names = ["R", "G", "B"]
>>> spectral_attribution = lime.attribute(
... hsi, band_mask=band_mask, band_names=band_names, target=0, attribution_type="spectral"
... )
>>> spectral_attribution.hsi
HSI(shape=(4, 240, 240), dtype=torch.float32)
Source code in src/meteors/attr/lime.py
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 |
|
get_band_mask(hsi, band_names=None, band_indices=None, band_wavelengths=None, device=None, repeat_dimensions=False)
staticmethod
Generates a band mask based on the provided hsi and band information.
Remember you need to provide either band_names, band_indices, or band_wavelengths to create the band mask. If you provide more than one, the band mask will be created using only one using the following priority: band_names > band_wavelengths > band_indices.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
HSI
|
The input hyperspectral image. |
required |
band_names
|
None | list[str | list[str]] | dict[tuple[str, ...] | str, int]
|
The names of the spectral bands to include in the mask. Defaults to None. |
None
|
band_indices
|
None | dict[str | tuple[str, ...], list[tuple[int, int]] | tuple[int, int] | list[int]]
|
The indices or ranges of indices of the spectral bands to include in the mask. Defaults to None. |
None
|
band_wavelengths
|
None | dict[str | tuple[str, ...], list[tuple[float, float]] | tuple[float, float], list[float], float]
|
The wavelengths or ranges of wavelengths of the spectral bands to include in the mask. Defaults to None. |
None
|
device
|
str | device | None
|
The device to use for computation. Defaults to None. |
None
|
repeat_dimensions
|
bool
|
Whether to repeat the dimensions of the mask to match the input hsi shape. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
tuple[torch.Tensor, dict[tuple[str, ...] | str, int]]: A tuple containing the band mask tensor and a dictionary |
dict[tuple[str, ...] | str, int]
|
mapping band names to segment IDs. |
Raises:
Type | Description |
---|---|
TypeError
|
If the input hsi is not an instance of the HSI class. |
ValueError
|
If no band names, indices, or wavelengths are provided. |
Examples:
>>> hsi = mt.HSI(image=torch.ones((len(wavelengths), 10, 10)), wavelengths=wavelengths)
>>> band_names = ["R", "G"]
>>> band_mask, dict_labels_to_segment_ids = mt_lime.Lime.get_band_mask(hsi, band_names=band_names)
>>> dict_labels_to_segment_ids
{"R": 1, "G": 2}
>>> band_indices = {"RGB": [0, 1, 2]}
>>> band_mask, dict_labels_to_segment_ids = mt_lime.Lime.get_band_mask(hsi, band_indices=band_indices)
>>> dict_labels_to_segment_ids
{"RGB": 1}
>>> band_wavelengths = {"RGB": [(462.08, 465.27), (465.27, 468.47), (468.47, 471.68)]}
>>> band_mask, dict_labels_to_segment_ids = mt_lime.Lime.get_band_mask(hsi, band_wavelengths=band_wavelengths)
>>> dict_labels_to_segment_ids
{"RGB": 1}
Source code in src/meteors/attr/lime.py
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 |
|
get_segmentation_mask(hsi, segmentation_method='slic', **segmentation_method_params)
staticmethod
Generates a segmentation mask for the given hsi using the specified segmentation method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
HSI
|
The input hyperspectral image for which the segmentation mask needs to be generated. |
required |
segmentation_method
|
Literal['patch', 'slic']
|
The segmentation method to be used. Defaults to "slic". |
'slic'
|
**segmentation_method_params
|
Any
|
Additional parameters specific to the chosen segmentation method. |
{}
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: The segmentation mask as a tensor. |
Raises:
Type | Description |
---|---|
TypeError
|
If the input hsi is not an instance of the HSI class. |
ValueError
|
If an unsupported segmentation method is specified. |
Examples:
>>> hsi = meteors.HSI(image=torch.ones((3, 240, 240)), wavelengths=[462.08, 465.27, 468.47])
>>> segmentation_mask = mt_lime.Lime.get_segmentation_mask(hsi, segmentation_method="slic")
>>> segmentation_mask.shape
torch.Size([1, 240, 240])
>>> segmentation_mask = meteors.attr.Lime.get_segmentation_mask(hsi, segmentation_method="patch", patch_size=2)
>>> segmentation_mask.shape
torch.Size([1, 240, 240])
>>> segmentation_mask[0, :2, :2]
torch.tensor([[1, 1],
[1, 1]])
>>> segmentation_mask[0, 2:4, :2]
torch.tensor([[2, 2],
[2, 2]])
Source code in src/meteors/attr/lime.py
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 |
|
get_spatial_attributes(hsi, segmentation_mask=None, target=None, n_samples=10, perturbations_per_eval=4, verbose=False, segmentation_method='slic', additional_forward_args=None, **segmentation_method_params)
Get spatial attributes of an hsi image using the LIME method. Based on the provided hsi and segmentation mask
LIME method attributes the superpixels
provided by the segmentation mask. Please refer to the original paper
https://arxiv.org/abs/1602.04938
for more details or to Christoph Molnar's book
https://christophm.github.io/interpretable-ml-book/lime.html
.
This function attributes the hyperspectral image using the LIME (Local Interpretable Model-Agnostic Explanations)
method for spatial data. It returns an HSISpatialAttributes
object that contains the hyperspectral image,,
the attributions, the segmentation mask, and the score of the interpretable model used for the explanation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSISpatialAttributes objects. |
required |
segmentation_mask
|
ndarray | Tensor | list[ndarray | Tensor] | None
|
A segmentation mask according to which the attribution should be performed.
The segmentation mask should have a 2D or 3D shape, which can be broadcastable to the shape of the
input image. The only dimension on which the image and the mask shapes can differ is the spectral
dimension, marked with letter |
None
|
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
n_samples
|
int
|
The number of samples to generate/analyze in LIME. The more the better but slower. Defaults to 10. |
10
|
perturbations_per_eval
|
int
|
The number of perturbations to evaluate at once (Simply the inner batch size). Defaults to 4. |
4
|
verbose
|
bool
|
Whether to show the progress bar. Defaults to False. |
False
|
segmentation_method
|
Literal['slic', 'patch']
|
Segmentation method used only if |
'slic'
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
**segmentation_method_params
|
Any
|
Additional parameters for the segmentation method. |
{}
|
Returns:
Type | Description |
---|---|
list[HSISpatialAttributes] | HSISpatialAttributes
|
HSISpatialAttributes | list[HSISpatialAttributes]: An object containing the image, the attributions, the segmentation mask, and the score of the interpretable model used for the explanation. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the Lime object is not initialized or is not an instance of LimeBase. |
MaskCreationError
|
If there is an error creating the segmentation mask. |
ValueError
|
If the number of segmentation masks is not equal to the number of HSI images provided. |
HSIAttributesError
|
If there is an error during creating spatial attribution. |
Examples:
>>> simple_model = lambda x: torch.rand((x.shape[0], 2))
>>> hsi = mt.HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> segmentation_mask = torch.randint(1, 4, (1, 240, 240))
>>> lime = meteors.attr.Lime(
explainable_model=ExplainableModel(simple_model, "regression"), interpretable_model=SkLearnLasso(alpha=0.1)
)
>>> spatial_attribution = lime.get_spatial_attributes(hsi, segmentation_mask=segmentation_mask, target=0)
>>> spatial_attribution.hsi
HSI(shape=(4, 240, 240), dtype=torch.float32)
>>> spatial_attribution.attributes.shape
torch.Size([4, 240, 240])
>>> spatial_attribution.segmentation_mask.shape
torch.Size([1, 240, 240])
>>> spatial_attribution.score
1.0
Source code in src/meteors/attr/lime.py
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 |
|
get_spectral_attributes(hsi, band_mask=None, target=None, n_samples=10, perturbations_per_eval=4, verbose=False, additional_forward_args=None, band_names=None)
Attributes the hsi image using LIME method for spectral data. Based on the provided hsi and band mask, the LIME
method attributes the hsi based on superbands
(clustered bands) provided by the band mask.
Please refer to the original paper https://arxiv.org/abs/1602.04938
for more details or to
Christoph Molnar's book https://christophm.github.io/interpretable-ml-book/lime.html
.
The function returns a HSISpectralAttributes object that contains the image, the attributions, the band mask, the band names, and the score of the interpretable model used for the explanation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSISpatialAttributes objects. |
required |
band_mask
|
ndarray | Tensor | list[ndarray | Tensor] | None
|
Band mask that
is used for the spectral attribution. The band mask should have a 1D or 3D shape, which can be
broadcastable to the shape of the input image. The only dimensions on which the image and the mask shapes
can differ is the height and width dimensions, marked with letters |
None
|
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
n_samples
|
int
|
The number of samples to generate/analyze in LIME. The more the better but slower. Defaults to 10. |
10
|
perturbations_per_eval
|
int
|
The number of perturbations to evaluate at once (Simply the inner batch size). Defaults to 4. |
4
|
verbose
|
bool
|
Whether to show the progress bar. Defaults to False. |
False
|
segmentation_method
|
Literal['slic', 'patch']
|
Segmentation method used only if |
required |
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
band_names
|
list[str] | dict[str | tuple[str, ...], int] | None
|
Band names. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
HSISpectralAttributes | list[HSISpectralAttributes]
|
HSISpectralAttributes | list[HSISpectralAttributes]: An object containing the image, the attributions, the band mask, the band names, and the score of the interpretable model used for the explanation. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the Lime object is not initialized or is not an instance of LimeBase. |
MaskCreationError
|
If there is an error creating the band mask. |
ValueError
|
If the number of band masks is not equal to the number of HSI images provided. |
HSIAttributesError
|
If there is an error during creating spectral attribution. |
Examples:
>>> simple_model = lambda x: torch.rand((x.shape[0], 2))
>>> hsi = mt.HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> band_mask = torch.randint(1, 4, (4, 1, 1)).repeat(1, 240, 240)
>>> band_names = ["R", "G", "B"]
>>> lime = meteors.attr.Lime(
explainable_model=ExplainableModel(simple_model, "regression"), interpretable_model=SkLearnLasso(alpha=0.1)
)
>>> spectral_attribution = lime.get_spectral_attributes(hsi, band_mask=band_mask, band_names=band_names, target=0)
>>> spectral_attribution.hsi
HSI(shape=(4, 240, 240), dtype=torch.float32)
>>> spectral_attribution.attributes.shape
torch.Size([4, 240, 240])
>>> spectral_attribution.band_mask.shape
torch.Size([4, 240, 240])
>>> spectral_attribution.band_names
["R", "G", "B"]
>>> spectral_attribution.score
1.0
Source code in src/meteors/attr/lime.py
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 |
|
Lime Base
The Lime Base class was adapted from the Captum Lime implementation. This adaptation builds upon the original work, extending and customizing it for specific use cases within this project. To see the original implementation, please refer to the Captum repository.
IntegratedGradients
Bases: Explainer
IntegratedGradients explainer class for generating attributions using the Integrated Gradients method.
The Integrated Gradients method is based on the captum
implementation
and is an implementation of an idea coming from the original paper on Integrated Gradients,
where more details about this method can be found.
Attributes:
Name | Type | Description |
---|---|---|
_attribution_method |
IntegratedGradients
|
The Integrated Gradients method from the |
multiply_by_inputs |
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in, then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found in this paper. In case of integrated gradients, if multiply_by_inputs is set to True, final sensitivity scores are being multiplied by (inputs - baselines). |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
explainable_model
|
ExplainableModel | Explainer
|
The explainable model to be explained. |
required |
Source code in src/meteors/attr/integrated_gradients.py
17 18 19 20 21 22 23 24 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 |
|
attribute(hsi, baseline=None, target=None, additional_forward_args=None, n_steps=50, method='gausslegendre', return_convergence_delta=False)
Method for generating attributions using the Integrated Gradients method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
baseline
|
int | float | torch.Tensor | list[int | float | torch.Tensor
|
Baselines define the starting point from which integral is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object. - list of integers, floats or tensors with the same shape as the input tensor, providing a baseline for each input pixel. If the input is a list of HSI objects, the baseline can be a list of tensors with the same shape as the input tensor for each HSI object. Defaults to None. |
None
|
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
n_steps
|
int
|
The number of steps to approximate the integral. Default: 50. |
50
|
return_convergence_delta
|
bool
|
Indicates whether to return convergence delta or not. If return_convergence_delta is set to True convergence delta will be returned in a tuple following attributions. Default: False |
False
|
Returns:
Type | Description |
---|---|
HSIAttributes | list[HSIAttributes]
|
HSIAttributes | list[HSIAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
HSIAttributesError
|
If an error occurs during the generation of the attributions. |
Examples:
>>> integrated_gradients = IntegratedGradients(explainable_model)
>>> hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> attributions = integrated_gradients.attribute(hsi, method="riemann_right", baseline=0.0)
>>> attributions, approximation_error = integrated_gradients.attribute(hsi, return_convergence_delta=True)
>>> approximation_error
0.5
>>> attributions = integrated_gradients.attribute([hsi, hsi])
>>> len(attributions)
2
Source code in src/meteors/attr/integrated_gradients.py
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 |
|
InputXGradient
Bases: Explainer
Initializes the InputXGradient explainer. The InputXGradients method is a straightforward approach to
computing attribution. It simply multiplies the input image with the gradient with respect to the input.
This method is based on the captum
implementation
Attributes:
Name | Type | Description |
---|---|---|
_attribution_method |
CaptumIntegratedGradients
|
The InputXGradient method from the |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
explainable_model
|
ExplainableModel | Explainer
|
The explainable model to be explained. |
required |
Source code in src/meteors/attr/input_x_gradients.py
14 15 16 17 18 19 20 21 22 23 24 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 |
|
attribute(hsi, target=None, additional_forward_args=None)
Method for generating attributions using the InputXGradient method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
Returns:
Type | Description |
---|---|
HSIAttributes | list[HSIAttributes]
|
HSIAttributes | list[HSIAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
HSIAttributesError
|
If an error occurs during the generation of the attributions. |
Examples:
>>> input_x_gradient = InputXGradient(explainable_model)
>>> hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> attributions = input_x_gradient.attribute(hsi)
>>> attributions = input_x_gradient.attribute([hsi, hsi])
>>> len(attributions)
2
Source code in src/meteors/attr/input_x_gradients.py
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 |
|
Occlusion
Bases: Explainer
Occlusion explainer class for generating attributions using the Occlusion method.
This attribution method perturbs the input by replacing the contiguous rectangular region
with a given baseline and computing the difference in output.
In our case, features are located in multiple regions, and attribution from different hyper-rectangles is averaged.
The implementation of this method is also based on the captum
repository.
More details about this approach can be found in the original paper
Attributes:
Name | Type | Description |
---|---|---|
_attribution_method |
Occlusion
|
The Occlusion method from the |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
explainable_model
|
ExplainableModel | Explainer
|
The explainable model to be explained. |
required |
postprocessing_segmentation_output
|
Callable[[Tensor], Tensor] | None
|
A segmentation postprocessing function for segmentation problem type. This is required for segmentation problem type as attribution methods needs to have 1d output. Defaults to None, which means that the attribution method is not used. |
required |
Source code in src/meteors/attr/occlusion.py
19 20 21 22 23 24 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 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 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 |
|
attribute(hsi, target=None, sliding_window_shapes=(1, 1, 1), strides=(1, 1, 1), baseline=None, additional_forward_args=None, perturbations_per_eval=1, show_progress=False)
Method for generating attributions using the Occlusion method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
sliding_window_shapes
|
int | tuple[int, int, int]
|
The shape of the sliding window. If an integer is provided, it will be used for all dimensions. Defaults to (1, 1, 1). |
(1, 1, 1)
|
strides
|
int | tuple[int, int, int]
|
The stride of the sliding window. Defaults to (1, 1, 1). Simply put, the stride is the number of pixels by which the sliding window is moved in each dimension. |
(1, 1, 1)
|
baseline
|
int | float | Tensor | list[int | float | Tensor]
|
Baselines define reference value which replaces each feature when occluded is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object. - list of integers, floats or tensors with the same shape as the input tensor, providing a baseline for each input pixel. If the input is a list of HSI objects, the baseline can be a list of tensors with the same shape as the input tensor for each HSI object. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
perturbations_per_eval
|
int
|
Allows multiple occlusions to be included in one batch (one call to forward_fn). By default, perturbations_per_eval is 1, so each occlusion is processed individually. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. When working with multiple examples, the number of perturbations per evaluation should be set to at least the number of examples. Defaults to 1. |
1
|
show_progress
|
bool
|
If True, displays a progress bar. Defaults to False. |
False
|
Returns:
Name | Type | Description |
---|---|---|
HSIAttributes |
HSIAttributes | list[HSIAttributes]
|
The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
ValueError
|
If the sliding window shapes or strides are not a tuple of three integers. |
HSIAttributesError
|
If an error occurs during the generation of the attributions. |
Example
occlusion = Occlusion(explainable_model) hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68]) attributions = occlusion.attribute(hsi, baseline=0, sliding_window_shapes=(4, 3, 3), strides=(1, 1, 1)) attributions = occlusion.attribute([hsi, hsi], baseline=0, sliding_window_shapes=(4, 3, 3), strides=(1, 2, 2)) len(attributions) 2
Source code in src/meteors/attr/occlusion.py
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 |
|
get_spatial_attributes(hsi, target=None, sliding_window_shapes=(1, 1), strides=1, baseline=None, additional_forward_args=None, perturbations_per_eval=1, show_progress=False)
Compute spatial attributions for the input HSI using the Occlusion method. In this case, the sliding window is applied to the spatial dimensions only.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
sliding_window_shapes
|
int | tuple[int, int]
|
The shape of the sliding window for spatial dimensions. If an integer is provided, it will be used for both spatial dimensions. Defaults to (1, 1). |
(1, 1)
|
strides
|
int | tuple[int, int]
|
The stride of the sliding window for spatial dimensions. Defaults to 1. Simply put, the stride is the number of pixels by which the sliding window is moved in each spatial dimension. |
1
|
baseline
|
int | float | Tensor | list[int | float | Tensor]
|
Baselines define reference value which replaces each feature when occluded is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object. - list of integers, floats or tensors with the same shape as the input tensor, providing a baseline for each input pixel. If the input is a list of HSI objects, the baseline can be a list of tensors with the same shape as the input tensor for each HSI object. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
perturbations_per_eval
|
int
|
Allows multiple occlusions to be included in one batch (one call to forward_fn). By default, perturbations_per_eval is 1, so each occlusion is processed individually. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. When working with multiple examples, the number of perturbations per evaluation should be set to at least the number of examples. Defaults to 1. |
1
|
show_progress
|
bool
|
If True, displays a progress bar. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
HSISpatialAttributes | list[HSISpatialAttributes]
|
HSISpatialAttributes | list[HSISpatialAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
ValueError
|
If the sliding window shapes or strides are not a tuple of two integers. |
HSIAttributesError
|
If an error occurs during the generation of the attributions |
Example
occlusion = Occlusion(explainable_model) hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68]) attributions = occlusion.get_spatial_attributes(hsi, baseline=0, sliding_window_shapes=(3, 3), strides=(1, 1)) attributions = occlusion.get_spatial_attributes([hsi, hsi], baseline=0, sliding_window_shapes=(3, 3), strides=(2, 2)) len(attributions) 2
Source code in src/meteors/attr/occlusion.py
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 |
|
get_spectral_attributes(hsi, target=None, sliding_window_shapes=1, strides=1, baseline=None, additional_forward_args=None, perturbations_per_eval=1, show_progress=False)
Compute spectral attributions for the input HSI using the Occlusion method. In this case, the sliding window is applied to the spectral dimension only.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
sliding_window_shapes
|
int | tuple[int]
|
The size of the sliding window for the spectral dimension. Defaults to 1. |
1
|
strides
|
int | tuple[int]
|
The stride of the sliding window for the spectral dimension. Defaults to 1. Simply put, the stride is the number of pixels by which the sliding window is moved in spectral dimension. |
1
|
baseline
|
int | float | Tensor | list[int | float | Tensor]
|
Baselines define reference value which replaces each feature when occluded is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object. - list of integers, floats or tensors with the same shape as the input tensor, providing a baseline for each input pixel. If the input is a list of HSI objects, the baseline can be a list of tensors with the same shape as the input tensor for each HSI object. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
perturbations_per_eval
|
int
|
Allows multiple occlusions to be included in one batch (one call to forward_fn). By default, perturbations_per_eval is 1, so each occlusion is processed individually. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. When working with multiple examples, the number of perturbations per evaluation should be set to at least the number of examples. Defaults to 1. |
1
|
show_progress
|
bool
|
If True, displays a progress bar. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
HSISpectralAttributes | list[HSISpectralAttributes]
|
HSISpectralAttributes | list[HSISpectralAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
ValueError
|
If the sliding window shapes or strides are not a tuple of a single integer. |
TypeError
|
If the sliding window shapes or strides are not a single integer. |
HSIAttributesError
|
If an error occurs during the generation of the attributions |
Example
occlusion = Occlusion(explainable_model) hsi = HSI(image=torch.ones((10, 240, 240)), wavelengths=torch.arange(10)) attributions = occlusion.get_spectral_attributes(hsi, baseline=0, sliding_window_shapes=3, strides=1) attributions = occlusion.get_spectral_attributes([hsi, hsi], baseline=0, sliding_window_shapes=3, strides=2) len(attributions) 2
Source code in src/meteors/attr/occlusion.py
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 |
|
Saliency
Bases: Explainer
Saliency explainer class for generating attributions using the Saliency method.
This baseline method for computing input attribution calculates gradients with respect to inputs.
It also has an option to return the absolute value of the gradients, which is the default behaviour.
Implementation of this method is based on the captum
repository
Attributes:
Name | Type | Description |
---|---|---|
_attribution_method |
Saliency
|
The Saliency method from the |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
explainable_model
|
ExplainableModel | Explainer
|
The explainable model to be explained. |
required |
Source code in src/meteors/attr/saliency.py
17 18 19 20 21 22 23 24 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 |
|
attribute(hsi, target=None, abs=True, additional_forward_args=None)
Method for generating attributions using the Saliency method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
abs
|
bool
|
Returns absolute value of gradients if set to True, otherwise returns the (signed) gradients if False. Default: True |
True
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
Returns:
Type | Description |
---|---|
HSIAttributes | list[HSIAttributes]
|
HSIAttributes | list[HSIAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the explainer is not initialized. |
HSIAttributesError
|
If an error occurs during the generation of the attributions |
Examples:
>>> saliency = Saliency(explainable_model)
>>> hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> attributions = saliency.attribute(hsi)
>>> attributions = saliency.attribute([hsi, hsi])
>>> len(attributions)
2
Source code in src/meteors/attr/saliency.py
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 |
|
NoiseTunnel
Bases: BaseNoiseTunnel
Noise Tunnel is a method that is used to explain the model's predictions by adding noise to the input tensor.
The noise is added to the input tensor, and the model's output is computed. The process is repeated multiple times
to obtain a distribution of the model's output. The final attribution is computed as the mean of the outputs.
For more information about the method, see captum
documentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chained_explainer
|
The explainable method that will be used to compute the attributions. |
required |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the callable object is not an instance of the Explainer class |
Source code in src/meteors/attr/noise_tunnel.py
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 |
|
attribute(hsi, target=None, additional_forward_args=None, n_samples=5, steps_per_batch=1, perturbation_axis=None, stdevs=1.0, method='smoothgrad')
Method for generating attributions using the Noise Tunnel method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
baseline
|
int | float | Tensor
|
Baselines define reference value which replaces each feature when occluded is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object. |
required |
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
n_samples
|
int
|
The number of randomly generated examples per sample in the input batch. Random examples are generated by adding gaussian random noise to each sample. Default: 5 if nt_samples is not provided. |
5
|
steps_per_batch
|
int
|
The number of the n_samples that will be processed together. With the help of this parameter we can avoid out of memory situation and reduce the number of randomly generated examples per sample in each batch. Default: None if steps_per_batch is not provided. In this case all nt_samples will be processed together. |
1
|
perturbation_axis
|
None | tuple[int | slice]
|
The indices of the input image to be perturbed. If set to None, all bands are perturbed, which corresponds to a traditional noise tunnel method. Defaults to None. |
None
|
stdevs
|
float | tuple[float, ...]
|
The standard deviation of gaussian noise with zero mean that is added to each input in the batch. If stdevs is a single float value then that same value is used for all inputs. If stdevs is a tuple, then the length of the tuple must match the number of inputs as each value in the tuple is used for the corresponding input. Default: 1.0 |
1.0
|
method
|
Literal['smoothgrad', 'smoothgrad_sq', 'vargrad']
|
Smoothing type of the attributions. smoothgrad, smoothgrad_sq or vargrad Default: smoothgrad if type is not provided. |
'smoothgrad'
|
Returns:
Type | Description |
---|---|
HSIAttributes | list[HSIAttributes]
|
HSIAttributes | list[HSIAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
HSIAttributesError
|
If an error occurs during the generation of the attributions. |
Examples:
>>> noise_tunnel = NoiseTunnel(explainable_model)
>>> hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> attributions = noise_tunnel.attribute(hsi)
>>> attributions = noise_tunnel.attribute([hsi, hsi])
>>> len(attributions)
2
Source code in src/meteors/attr/noise_tunnel.py
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 |
|
perturb_input(input, n_samples=1, perturbation_axis=None, stdevs=1, **kwargs)
staticmethod
The default perturbation function used in the noise tunnel with small enhancement for hyperspectral images.
It randomly adds noise to the input tensor from a normal distribution with a given standard deviation.
The noise is added to the selected bands (channels) of the input tensor.
The bands to be perturbed are selected based on the perturbation_axis
parameter.
By default all bands are perturbed, which is equivalent to the standard noise tunnel method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
Tensor
|
An input tensor to be perturbed. It should have the shape (C, H, W). |
required |
n_samples
|
int
|
A number of samples to be drawn - number of perturbed inputs to be generated. |
1
|
perturbation_axis
|
None | tuple[int | slice]
|
The indices of the bands to be perturbed. If set to None, all bands are perturbed. Defaults to None. |
None
|
stdevs
|
float
|
The standard deviation of gaussian noise with zero mean that is added to each input in the batch. Defaults to 1.0. |
1
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A perturbed tensor, which contains |
Source code in src/meteors/attr/noise_tunnel.py
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 |
|
HyperNoiseTunnel
Bases: BaseNoiseTunnel
Hyper Noise Tunnel is our novel method, designed specifically to explain hyperspectral satellite images. It is inspired by the behaviour of the classical Noise Tunnel (Smooth Grad) method, but instead of sampling noise into the original image, it randomly masks some of the bands with the baseline. In the process, the created noised samples are close to the distribution of the original image yet differ enough to smoothen the produced attribution map.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chained_explainer
|
The explainable method that will be used to compute the attributions. |
required |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the callable object is not an instance of the Explainer class |
Source code in src/meteors/attr/noise_tunnel.py
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 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 |
|
attribute(hsi, baseline=None, target=None, additional_forward_args=None, n_samples=5, steps_per_batch=1, perturbation_prob=0.5, num_perturbed_bands=None, method='smoothgrad')
Method for generating attributions using the Hyper Noise Tunnel method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hsi
|
list[HSI] | HSI
|
Input hyperspectral image(s) for which the attributions are to be computed. If a list of HSI objects is provided, the attributions are computed for each HSI object in the list. The output will be a list of HSIAttributes objects. |
required |
baseline
|
int | float | Tensor | list[int | float | Tensor]
|
Baselines define reference value which replaces each feature when occluded is computed and can be provided as: - integer or float representing a constant value used as the baseline for all input pixels. - tensor with the same shape as the input tensor, providing a baseline for each input pixel. if the input is a list of HSI objects, the baseline can be a tensor with the same shape as the input tensor for each HSI object or a list of tensors with the same length as the input list. |
None
|
target
|
list[int] | int | None
|
target class index for computing the attributions. If None, methods assume that the output has only one class. If the output has multiple classes, the target index must be provided. For multiple input images, a list of target indices can be provided, one for each image or single target value will be used for all images. Defaults to None. |
None
|
additional_forward_args
|
Any
|
If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None |
None
|
n_samples
|
int
|
The number of randomly generated examples per sample in the input batch. Random examples are generated by adding gaussian random noise to each sample. Default: 5 if nt_samples is not provided. |
5
|
steps_per_batch
|
int
|
The number of the n_samples that will be processed together. With the help of this parameter we can avoid out of memory situation and reduce the number of randomly generated examples per sample in each batch. Default: None if steps_per_batch is not provided. In this case all nt_samples will be processed together. |
1
|
perturbation_prob
|
float
|
The probability that each band will be perturbed independently. Defaults to 0.5. |
0.5
|
num_perturbed_bands
|
int | None
|
The number of perturbed bands in the whole image.
The bands to be perturbed are selected randomly with no replacement.
If set to None, the bands are perturbed with probability |
None
|
method
|
Literal['smoothgrad', 'smoothgrad_sq', 'vargrad']
|
Smoothing type of the attributions. smoothgrad, smoothgrad_sq or vargrad Default: smoothgrad if type is not provided. |
'smoothgrad'
|
Returns:
Type | Description |
---|---|
HSIAttributes | list[HSIAttributes]
|
HSIAttributes | list[HSIAttributes]: The computed attributions for the input hyperspectral image(s). if a list of HSI objects is provided, the attributions are computed for each HSI object in the list. |
Raises:
Type | Description |
---|---|
HSIAttributesError
|
If an error occurs during the generation of the attributions. |
Examples:
>>> hyper_noise_tunnel = HyperNoiseTunnel(explainable_model)
>>> hsi = HSI(image=torch.ones((4, 240, 240)), wavelengths=[462.08, 465.27, 468.47, 471.68])
>>> attributions = hyper_noise_tunnel.attribute(hsi)
>>> attributions = hyper_noise_tunnel.attribute([hsi, hsi])
>>> len(attributions)
2
Source code in src/meteors/attr/noise_tunnel.py
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 |
|
perturb_input(input, baseline=None, n_samples=1, perturbation_prob=0.5, num_perturbed_bands=None, **kwargs)
staticmethod
The perturbation function used in the hyper noise tunnel. It randomly selects a subset of the input bands
that will be masked out and replaced with the baseline. The parameters num_perturbed_bands
and
perturbation_prob
control the number of bands that will be perturbed (masked). If num_perturbed_bands
is
set, it will be used as the number of bands to perturb, which will be randomly selected. Otherwise, the number
of bands will be drawn from a binomial distribution with perturbation_prob
as the probability of success.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
Tensor
|
An input tensor to be perturbed. It should have the shape (C, H, W). |
required |
baseline
|
Tensor | None
|
A tensor that will be used to replace the perturbed bands. |
None
|
n_samples
|
int
|
A number of samples to be drawn - number of perturbed inputs to be generated. |
1
|
perturbation_prob
|
float
|
A probability that each band will be perturbed intependently. Defaults to 0.5. |
0.5
|
num_perturbed_bands
|
int | None
|
A number of perturbed bands in the whole image.
If set to None, the bands are perturbed with probability |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
torch.Tensor: A perturbed tensor, which contains |
Source code in src/meteors/attr/noise_tunnel.py
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 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 |
|