slisemap.utils
Module that contains various useful functions.
softmax_row_kernel(D)
Kernel function that applies softmax on the rows.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
D |
Tensor
|
Distance matrix. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Weight matrix. |
Source code in slisemap/utils.py
23 24 25 26 27 28 29 30 31 32 |
|
softmax_column_kernel(D)
Kernel function that applies softmax on the columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
D |
Tensor
|
Distance matrix. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Weight matrix. |
Source code in slisemap/utils.py
35 36 37 38 39 40 41 42 43 44 |
|
squared_distance(A, B)
Distance function that returns the squared euclidean distances.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
A |
Tensor
|
The first matrix [n1, d]. |
required |
B |
Tensor
|
The second matrix [n2, d]. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Distance matrix [n1, n2]. |
Source code in slisemap/utils.py
47 48 49 50 51 52 53 54 55 56 57 |
|
SlisemapException
Bases: Exception
Custom Exception type (for filtering).
Source code in slisemap/utils.py
60 61 62 63 |
|
SlisemapWarning
Bases: Warning
Custom Warning type (for filtering).
Source code in slisemap/utils.py
66 67 68 69 |
|
CallableLike
Bases: Generic[_F]
Type annotation for functions matching the signature of a given function.
Source code in slisemap/utils.py
138 139 140 141 142 143 |
|
tonp(x)
Convert a torch.Tensor
to a numpy.ndarray
.
If x
is not a torch.Tensor
then np.asarray
is used instead.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Union[Tensor, object]
|
Input |
required |
Returns:
Type | Description |
---|---|
ndarray
|
Output |
Source code in slisemap/utils.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
CheckConvergence
An object that tries to estimate when an optimisation has converged.
Use it for, e.g., escape+optimisation cycles in Slisemap.
Source code in slisemap/utils.py
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 |
|
__init__(patience=3, max_iter=1 << 20, rel=0.0001)
Create a CheckConvergence
object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
patience |
float
|
How long should the optimisation continue without improvement. Defaults to 3. |
3
|
max_iter |
int
|
The maximum number of iterations. Defaults to |
1 << 20
|
rel |
float
|
Minimum relative error change that is considered an improvement. Defaults to |
0.0001
|
Source code in slisemap/utils.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
|
has_converged(loss, store=None, verbose=False)
Check if the optimisation has converged.
If more than one loss value is provided, then only the first one is checked when storing the optimal_state
.
The other losses are only used for checking convergence.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
loss |
Union[float, Sequence[float], ndarray]
|
The latest loss value(s). |
required |
store |
Optional[Callable[[], Any]]
|
Function that returns the current state for storing in |
None
|
verbose |
bool
|
Pring debug messages. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
bool
|
True if the optimisation has converged. |
Source code in slisemap/utils.py
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 |
|
LBFGS(loss_fn, variables, max_iter=500, max_eval=None, line_search_fn='strong_wolfe', time_limit=None, increase_tolerance=False, verbose=False, **kwargs)
Optimise a function using LBFGS.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
loss_fn |
Callable[[], Tensor]
|
Function that returns a value to be minimised. |
required |
variables |
List[Tensor]
|
List of variables to optimise (must have |
required |
max_iter |
int
|
Maximum number of LBFGS iterations. Defaults to 500. |
500
|
max_eval |
Optional[int]
|
Maximum number of function evaluations. Defaults to |
None
|
line_search_fn |
Optional[str]
|
Line search method (None or "strong_wolfe"). Defaults to "strong_wolfe". |
'strong_wolfe'
|
time_limit |
Optional[float]
|
Optional time limit for the optimisation (in seconds). Defaults to None. |
None
|
increase_tolerance |
bool
|
Increase the tolerances for convergence checking. Defaults to False. |
False
|
verbose |
bool
|
Print status messages. Defaults to False. |
False
|
Other Parameters:
Name | Type | Description |
---|---|---|
**kwargs |
Any
|
Arguments forwarded to |
Returns:
Type | Description |
---|---|
LBFGS
|
The LBFGS optimiser. |
Source code in slisemap/utils.py
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 |
|
PCA_rotation(X, components=-1, center=True, full=True, niter=10)
Calculate the rotation matrix from PCA.
If the PCA fails (e.g. if original matrix is not full rank) then this shows a warning instead of throwing an error (returns a dummy rotation).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
Tensor
|
The original matrix. |
required |
components |
int
|
The maximum number of components in the embedding. Defaults to |
-1
|
center |
bool
|
Center the matrix before calculating the PCA. |
True
|
full |
bool
|
Use a full SVD for the PCA (slower). Defaults to True. |
True
|
niter |
int
|
The number of iterations when a randomised approach is used. Defaults to 10. |
10
|
Returns:
Type | Description |
---|---|
Tensor
|
Rotation matrix that turns the original matrix into the embedded space. |
Source code in slisemap/utils.py
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 |
|
global_model(X, Y, local_model, local_loss, coefficients=None, lasso=0.0, ridge=0.0)
Find coefficients for a global model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
Tensor
|
Data matrix. |
required |
Y |
Tensor
|
Target matrix. |
required |
local_model |
Callable[[Tensor, Tensor], Tensor]
|
Prediction function for the model. |
required |
local_loss |
Callable[[Tensor, Tensor, Tensor], Tensor]
|
Loss function for the model. |
required |
coefficients |
Optional[int]
|
Number of coefficients. Defaults to X.shape[1]. |
None
|
lasso |
float
|
Lasso-regularisation coefficient for B ($\lambda_{lasso} * ||B||_1$). Defaults to 0.0. |
0.0
|
ridge |
float
|
Ridge-regularisation coefficient for B ($\lambda_{ridge} * ||B||_2$). Defaults to 0.0. |
0.0
|
Returns:
Type | Description |
---|---|
Tensor
|
Global model coefficients. |
Source code in slisemap/utils.py
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 |
|
dict_array(dict)
Turn a dictionary of various values to a dictionary of numpy arrays with equal length inplace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dict |
Dict[str, Any]
|
Dictionary. |
required |
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
The same dictionary where the values are numpy arrays with equal length. |
Source code in slisemap/utils.py
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
|
dict_append(df, d)
Append a dictionary of values to a dictionary of numpy arrays (see dict_array
) inplace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
Dict[str, ndarray]
|
Dictionary of numpy arrays. |
required |
d |
Dict[str, Any]
|
Dictionary to append. |
required |
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
The same dictionary as |
Source code in slisemap/utils.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
|
dict_concat(dicts)
Combine multiple dictionaries into one by concatenating the values.
Calls dict_array
to pre-process the dictionaries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dicts |
Union[Sequence[Dict[str, Any]], Iterator[Dict[str, Any]]]
|
Sequence or Generator with dictionaries (all must have the same keys). |
required |
Returns:
Type | Description |
---|---|
Dict[str, ndarray]
|
Combined dictionary. |
Source code in slisemap/utils.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
|
ToTensor = Union[float, np.ndarray, torch.Tensor, 'pandas.DataFrame', Dict[str, Sequence[float]], Sequence[float]]
module-attribute
Type annotations for objects that can be turned into a torch.Tensor
with the to_tensor function.
to_tensor(input, **tensorargs)
Convert the input into a torch.Tensor
(via numpy.ndarray
if necessary).
This function wrapps torch.as_tensor
(and numpy.asarray
) and tries to extract row and column names.
This function can handle arbitrary objects (such as pandas.DataFrame
) if they implement .to_numpy()
and, optionally, .index
and .columns
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input |
ToTensor
|
input data |
required |
Keyword Args:
**tensorargs: additional arguments to torch.as_tensor
Returns:
Name | Type | Description |
---|---|---|
output |
Tensor
|
output tensor |
rows |
Optional[Sequence[object]]
|
row names or |
columns |
Optional[Sequence[object]]
|
column names or |
Source code in slisemap/utils.py
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 |
|
Metadata
Bases: dict
Metadata for Slisemap objects.
Primarily row names, column names, and scaling information about the matrices (these are used when plotting). But other arbitrary information can also be stored in this dictionary (The main Slisemap class has predefined "slots").
Source code in slisemap/utils.py
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 |
|
__init__(root, **kwargs)
Create a Metadata dictionary.
Source code in slisemap/utils.py
521 522 523 524 |
|
set_rows(*rows)
Set the row names with checks to avoid saving ranges.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*rows |
Optional[Sequence[object]]
|
row names |
()
|
Source code in slisemap/utils.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 |
|
set_variables(variables=None, add_intercept=None)
Set the variable names with checks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
variables |
Optional[Sequence[Any]]
|
variable names |
None
|
add_intercept |
Optional[bool]
|
add "Intercept" to the variable names. Defaults to |
None
|
Source code in slisemap/utils.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
|
set_targets(targets=None)
Set the target names with checks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
targets |
Union[None, str, Sequence[Any]]
|
target names |
None
|
Source code in slisemap/utils.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
|
set_coefficients(coefficients=None)
Set the coefficient names with checks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coefficients |
Optional[Sequence[Any]]
|
coefficient names |
None
|
Source code in slisemap/utils.py
589 590 591 592 593 594 595 596 597 598 599 600 601 |
|
set_dimensions(dimensions=None)
Set the dimension names with checks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dimensions |
Optional[Sequence[Any]]
|
dimension names |
None
|
Source code in slisemap/utils.py
603 604 605 606 607 608 609 610 611 612 613 614 615 |
|
get_coefficients(fallback=True)
Get a list of coefficient names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fallback |
bool
|
If metadata for coefficients is missing, return a new list instead of None. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Optional[List[str]]
|
list of coefficient names |
Source code in slisemap/utils.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
|
get_targets(fallback=True)
Get a list of target names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fallback |
bool
|
If metadata for targets is missing, return a new list instead of None. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Optional[List[str]]
|
list of target names |
Source code in slisemap/utils.py
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 |
|
get_variables(intercept=True, fallback=True)
Get a list of variable names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
intercept |
bool
|
include the intercept in the list. Defaults to True. |
True
|
fallback |
bool
|
If metadata for variables is missing, return a new list instead of None. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Optional[List[str]]
|
list of variable names |
Source code in slisemap/utils.py
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 |
|
get_dimensions(fallback=True, long=False)
Get a list of dimension names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fallback |
bool
|
If metadata for dimensions is missing, return a new list instead of None. Defaults to True. |
True
|
long |
bool
|
Use "SLISEMAP 1",... as fallback instead of "Z_0",... |
False
|
Returns:
Type | Description |
---|---|
Optional[List[str]]
|
list of dimension names |
Source code in slisemap/utils.py
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 |
|
get_rows(fallback=True)
Get a list of row names.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fallback |
bool
|
If metadata for rows is missing, return a range instead of None. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Optional[Sequence[Any]]
|
list (or range) of row names |
Source code in slisemap/utils.py
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
|
set_scale_X(center=None, scale=None)
Set scaling information with checks.
Use if X
has been scaled before being input to Slisemap.
Assuming the scaling can be converted to the form X = (X_unscaled - center) / scale
.
This allows some plots to (temporarily) revert the scaling (for more intuitive units).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
center |
Union[None, Tensor, ndarray, Sequence[float]]
|
The constant offset of |
None
|
scale |
Union[None, Tensor, ndarray, Sequence[float]]
|
The scaling factor of |
None
|
Source code in slisemap/utils.py
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 |
|
set_scale_Y(center=None, scale=None)
Set scaling information with checks.
Use if Y
has been scaled before being input to Slisemap.
Assuming the scaling can be converted to the form Y = (Y_unscaled - center) / scale
.
This allows some plots to (temporarily) revert the scaling (for more intuitive units).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
center |
Union[None, Tensor, ndarray, Sequence[float]]
|
The constant offset of |
None
|
scale |
Union[None, Tensor, ndarray, Sequence[float]]
|
The scaling factor of |
None
|
Source code in slisemap/utils.py
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 |
|
unscale_X(X=None)
Unscale X if the scaling information has been given (see set_scale_X
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
Optional[ndarray]
|
The data matrix X (or |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
Possibly scaled X. |
Source code in slisemap/utils.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 |
|
unscale_Y(Y=None)
Unscale Y if the scaling information has been given (see set_scale_Y
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
Y |
Optional[ndarray]
|
The response matrix Y (or |
None
|
Returns:
Type | Description |
---|---|
ndarray
|
Possibly scaled Y. |
Source code in slisemap/utils.py
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 |
|
make_grid(num=50, d=2, hex=True)
Create a circular grid of points with radius 1.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num |
int
|
The approximate number of points. Defaults to 50. |
50
|
d |
int
|
The number of dimensions. Defaults to 2. |
2
|
hex |
bool
|
If |
True
|
Returns:
Type | Description |
---|---|
ndarray
|
A matrix of coordinates |
Source code in slisemap/utils.py
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 |
|
make_hex_grid(num=52)
Create a circular grid of 2D points with a hexagon pattern and radius 1.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num |
int
|
The approximate number of points. Defaults to 52. |
52
|
Returns:
Type | Description |
---|---|
ndarray
|
A matrix of coordinates |
Source code in slisemap/utils.py
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 |
|