Optimizers¶
Gradient descent and the adaptive methods built on top of it.
Each optimizer is written to be read alongside the explanation that derives it, so the update rule appears in the code in the same form it appears in the mathematics.
dlhub.optimizers ¶
Optimizers¶
Gradient descent and the adaptive methods built on top of it.
Each optimizer is written to be read alongside the explanation that derives it, so the update rule appears in the code in the same form it appears in the mathematics.
License
MIT
AdamOptimizer ¶
Adam (Adaptive Moment Estimation) Optimizer
Adam combines the advantages of AdaGrad and RMSProp by computing adaptive learning rates for each parameter using estimates of first and second moments of the gradients.
The algorithm maintains exponentially decaying averages of past gradients and past squared gradients, which act as estimates of the first moment (mean) and second moment (uncentered variance) of the gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate (alpha in the paper) |
0.001
|
beta1
|
float
|
Exponential decay rate for first moment estimates |
0.9
|
beta2
|
float
|
Exponential decay rate for second moment estimates |
0.999
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
weight_decay
|
float
|
Weight decay coefficient (L2 regularization) |
0.0
|
amsgrad
|
bool
|
Whether to use AMSGrad variant which maintains maximum of squared gradients |
False
|
gradient_clip_norm
|
float
|
Maximum norm for gradient clipping |
None
|
gradient_clip_value
|
float
|
Maximum absolute value for gradient clipping |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
m |
dict
|
First moment estimates (exponentially decaying average of gradients) |
v |
dict
|
Second moment estimates (exponentially decaying average of squared gradients) |
v_hat_max |
dict
|
Maximum of v_hat values (used in AMSGrad) |
t |
int
|
Time step (number of updates performed) |
Source code in src/dlhub/optimizers/adam.py
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 | |
update ¶
update(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Perform a single optimization step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict
|
Dictionary of parameters to optimize |
required |
gradients
|
dict
|
Dictionary of gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters |
Source code in src/dlhub/optimizers/adam.py
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 | |
get_config ¶
get_config() -> dict
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
dict
|
Configuration dictionary |
Source code in src/dlhub/optimizers/adam.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
reset_state ¶
reset_state() -> None
Reset optimizer state (moments and time step).
Source code in src/dlhub/optimizers/adam.py
250 251 252 253 254 255 256 257 258 259 260 261 | |
get_state ¶
get_state() -> dict
Get complete optimizer state.
Returns:
| Type | Description |
|---|---|
dict
|
Complete state dictionary |
Source code in src/dlhub/optimizers/adam.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
load_state ¶
load_state(state: dict) -> None
Load optimizer state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
State dictionary from get_state() |
required |
Source code in src/dlhub/optimizers/adam.py
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 | |
BaseOptimizer ¶
Base class for all optimizers with common functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates. |
0.01
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Step size applied to each update. |
name |
str
|
Human-readable label, used to key and plot results. Subclasses set it to the name of the method they implement. |
Source code in src/dlhub/optimizers/base.py
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 | |
update_parameters ¶
update_parameters(params: dict[str, ndarray], grads: dict[str, ndarray], t: int) -> dict[str, np.ndarray]
Update parameters using optimization algorithm.
Implementations return a new dictionary rather than mutating the one they were given, so that a caller can keep the parameter trajectory of a run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration, counted from one. Optimizers applying bias
correction divide by |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, on the base class. An optimizer is defined by its update rule, so there is no meaningful default to inherit. |
Source code in src/dlhub/optimizers/base.py
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 | |
reset ¶
reset() -> None
Reset optimizer state for new optimization run.
The base implementation does nothing, which is correct for a stateless optimizer such as plain gradient descent. Any optimizer accumulating state across steps -- a velocity, a second moment -- must override this and clear it, or a second run starts from wherever the first one ended and its trajectory is not reproducible.
Source code in src/dlhub/optimizers/base.py
103 104 105 106 107 108 109 110 111 112 113 | |
BealeFunction ¶
Bases: OptimizationProblem
Beale function: f(x,y) = (1.5 - x + xy)² + (2.25 - x + xy²)² + (2.625 - x + xy³)².
Multimodal function with global minimum and several local minima. Tests optimizer robustness to local minima and saddle points.
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute Beale function value.
Source code in src/dlhub/optimizers/comparison.py
500 501 502 503 504 505 506 | |
gradients ¶
gradients(params: dict) -> dict
Compute Beale function gradients analytically.
Source code in src/dlhub/optimizers/comparison.py
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize at challenging starting point.
Source code in src/dlhub/optimizers/comparison.py
527 528 529 | |
OptimizationAnalytics ¶
Advanced analytics utilities for optimization comparison results.
Provides statistical analysis, performance ranking, and detailed insights into optimizer behavior across different problem types.
Source code in src/dlhub/optimizers/comparison.py
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 | |
compute_convergence_metrics
staticmethod
¶
compute_convergence_metrics(result: OptimizationRun) -> dict[str, float]
Compute detailed convergence metrics for a single optimization run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
OptimizationRun
|
Single optimization result to analyze. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of computed metrics. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
rank_optimizers
staticmethod
¶
rank_optimizers(all_results: dict[str, dict[str, OptimizationRun]]) -> dict[str, dict[str, int]]
Rank optimizers across different problems and metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from optimization comparison. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Rankings for each optimizer on each problem. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
generate_performance_heatmap
staticmethod
¶
generate_performance_heatmap(all_results: dict[str, dict[str, OptimizationRun]])
Generate performance heatmap comparing optimizers across problems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from optimization comparison. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
OptimizationComparison ¶
Comprehensive framework for comparing optimization algorithms.
Provides utilities to run multiple optimizers on various problems, collect performance metrics, and generate comparative visualizations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_iterations
|
int
|
Maximum number of optimization iterations. |
1000
|
tolerance
|
float
|
Convergence tolerance for loss change. |
1e-6
|
verbose
|
bool
|
Whether to print progress information. |
True
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
create_optimizer ¶
create_optimizer(optimizer_type: OptimizerType, **kwargs) -> BaseOptimizer
Factory method to create optimizer instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer_type
|
OptimizerType
|
Type of optimizer to create. |
required |
**kwargs
|
Additional parameters for optimizer initialization. |
{}
|
Returns:
| Type | Description |
|---|---|
BaseOptimizer
|
Configured optimizer instance. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
run_optimization ¶
run_optimization(problem: OptimizationProblem, optimizer: BaseOptimizer) -> OptimizationRun
Run single optimization experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
OptimizationProblem
|
Problem to optimize. |
required |
optimizer
|
BaseOptimizer
|
Optimizer to use. |
required |
Returns:
| Type | Description |
|---|---|
OptimizationRun
|
Results of optimization including metrics and trajectory. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
compare_optimizers ¶
compare_optimizers(problem: OptimizationProblem, optimizer_configs: dict[OptimizerType, dict]) -> dict[str, OptimizationRun]
Compare multiple optimizers on a single problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
OptimizationProblem
|
Problem to optimize. |
required |
optimizer_configs
|
dict
|
Dictionary mapping optimizer types to their configuration parameters. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Results for each optimizer. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
run_comprehensive_comparison ¶
run_comprehensive_comparison() -> dict[str, dict[str, OptimizationRun]]
Run comprehensive comparison across multiple problems and optimizers.
Returns:
| Type | Description |
|---|---|
dict
|
Nested dictionary: {problem_name: {optimizer_name: result}} |
Source code in src/dlhub/optimizers/comparison.py
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 | |
plot_convergence_comparison ¶
plot_convergence_comparison(results: dict[str, OptimizationRun], problem_name: str, log_scale: bool = True)
Plot convergence curves for optimizer comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict
|
Results from optimizer comparison. |
required |
problem_name
|
str
|
Name of the problem for plot title. |
required |
log_scale
|
bool
|
Whether to use logarithmic scale for loss. |
True
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
plot_optimization_paths ¶
plot_optimization_paths(results: dict[str, OptimizationRun], problem: OptimizationProblem, contour_levels: int = 20)
Plot optimization trajectories on loss landscape contours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict
|
Results from optimizer comparison. |
required |
problem
|
OptimizationProblem
|
Problem instance for computing loss landscape. |
required |
contour_levels
|
int
|
Number of contour levels to display. |
20
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
generate_summary_table ¶
generate_summary_table(all_results: dict[str, dict[str, OptimizationRun]]) -> None
Generate formatted summary table of optimization results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from comprehensive comparison. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
OptimizationProblem ¶
Base class for defining optimization problems with loss functions and gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the optimization problem. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute loss for given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameter values. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Loss value. |
Source code in src/dlhub/optimizers/comparison.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
gradients ¶
gradients(params: dict) -> dict
Compute gradients for given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameter values. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Gradients for each parameter. |
Source code in src/dlhub/optimizers/comparison.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
initial_parameters ¶
initial_parameters() -> dict
Get initial parameter values for optimization.
Returns:
| Type | Description |
|---|---|
dict
|
Initial parameter values. |
Source code in src/dlhub/optimizers/comparison.py
406 407 408 409 410 411 412 413 414 415 | |
OptimizationRun
dataclass
¶
The trace of one optimizer descending one problem, and its summary.
Not to be confused with :class:dlhub.tuning.ExperimentResult, which records
the outcome of a hyperparameter search rather than a single descent.
Attributes:
| Name | Type | Description |
|---|---|---|
optimizer_name |
str
|
Name of the optimizer used. |
losses |
List[float]
|
Loss values recorded during training. |
parameters |
List[Dict]
|
Parameter values at each iteration. |
convergence_time |
float
|
Time taken for convergence (in seconds). |
final_loss |
float
|
Final loss value achieved. |
iterations_to_converge |
int
|
Number of iterations required for convergence. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
OptimizerType ¶
Bases: Enum
Enumeration of available optimizer types.
Source code in src/dlhub/optimizers/comparison.py
77 78 79 80 81 82 83 | |
QuadraticBowl ¶
Bases: OptimizationProblem
Simple quadratic bowl optimization problem: f(x,y) = ax² + by².
Well-conditioned convex problem useful for demonstrating basic optimizer behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Coefficient for x² term. |
1.0
|
b
|
float
|
Coefficient for y² term. |
1.0
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute quadratic loss: ax² + by².
Source code in src/dlhub/optimizers/comparison.py
437 438 439 440 | |
gradients ¶
gradients(params: dict) -> dict
Compute gradients: [2ax, 2by].
Source code in src/dlhub/optimizers/comparison.py
442 443 444 445 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize at (5, 5) for clear visualization.
Source code in src/dlhub/optimizers/comparison.py
447 448 449 | |
RosenbrockFunction ¶
Bases: OptimizationProblem
Rosenbrock function: f(x,y) = (a-x)² + b(y-x²)².
Classic non-convex optimization benchmark with narrow curved valley. Challenging for optimizers due to ill-conditioning and plateau regions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Parameter controlling x-offset of minimum. |
1.0
|
b
|
float
|
Parameter controlling valley curvature (higher = more challenging). |
100.0
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute Rosenbrock function value.
Source code in src/dlhub/optimizers/comparison.py
472 473 474 475 | |
gradients ¶
gradients(params: dict) -> dict
Compute Rosenbrock gradients analytically.
Source code in src/dlhub/optimizers/comparison.py
477 478 479 480 481 482 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize away from minimum for interesting optimization path.
Source code in src/dlhub/optimizers/comparison.py
484 485 486 | |
AveragingStrategy ¶
Bases: Enum
Enumeration of different averaging strategies.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
44 45 46 47 48 49 50 | |
ExponentialWeightedAverage ¶
Exponential Weighted Average with bias correction and multiple strategies.
This class implements exponential weighted averages (also known as exponentially weighted moving averages) with various correction techniques commonly used in deep learning optimization algorithms.
The basic formula is: v_t = beta * v_{t-1} + (1 - beta) * theta_t
Where: - v_t is the average at time t - beta is the decay parameter - theta_t is the current value - v_0 = 0 (initial value)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
Decay parameter (0 < beta < 1). Higher values give more weight to past values. Common values: 0.9 (momentum), 0.999 (second moments in Adam) |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction to account for initialization bias |
True
|
strategy
|
AveragingStrategy
|
Averaging strategy to use |
AveragingStrategy.BIAS_CORRECTED
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
warmup_steps
|
int
|
Number of warmup steps before applying full averaging |
0
|
Attributes:
| Name | Type | Description |
|---|---|---|
v |
float or ndarray
|
Current average value |
t |
int
|
Time step (number of updates) |
history |
list
|
History of average values |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 | |
update ¶
update(value: float | ndarray) -> float | np.ndarray
Update the exponential weighted average with a new value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float or ndarray
|
New value to incorporate into the average |
required |
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Updated average value |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
get_current_average ¶
get_current_average() -> float | np.ndarray | None
Get the current average value.
Returns:
| Type | Description |
|---|---|
float, np.ndarray, or None
|
Current average value, None if no updates have been made |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
get_variance ¶
get_variance() -> float | np.ndarray | None
Get the current variance estimate (only available with VARIANCE_CORRECTED strategy).
Returns:
| Type | Description |
|---|---|
float, np.ndarray, or None
|
Current variance estimate, None if not available |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
reset ¶
reset() -> None
Reset the exponential weighted average to initial state.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
251 252 253 254 255 256 257 258 | |
get_effective_window_size ¶
get_effective_window_size() -> float
Get the effective window size of the exponential weighted average.
The effective window size is approximately 1/(1-beta).
Returns:
| Type | Description |
|---|---|
float
|
Effective window size |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
260 261 262 263 264 265 266 267 268 269 270 271 | |
get_config ¶
get_config() -> dict[str, Any]
Get configuration dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Configuration dictionary |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete state dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Complete state dictionary |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
load_state ¶
load_state(state: dict[str, Any]) -> None
Load state from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
State dictionary from get_state() |
required |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
MultiVariateEWA ¶
Multi-variate Exponential Weighted Average for handling multiple variables simultaneously.
This class manages multiple exponential weighted averages, commonly used in optimization algorithms where different parameters need separate averages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
Common decay parameter for all variables |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction |
True
|
strategy
|
AveragingStrategy
|
Averaging strategy |
AveragingStrategy.BIAS_CORRECTED
|
**kwargs
|
Additional parameters passed to individual EWA instances |
{}
|
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
update ¶
update(values: dict[str, float | ndarray]) -> dict[str, float | np.ndarray]
Update all averages with new values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
dict
|
Dictionary of new values for each variable |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of updated averages |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
get_averages ¶
get_averages() -> dict[str, float | np.ndarray]
Get current averages for all variables.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
399 400 401 | |
reset ¶
reset() -> None
Reset all averages.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
403 404 405 406 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete state for all averages.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
408 409 410 411 412 413 414 415 416 417 418 | |
MiniBatchGradientDescent ¶
Mini-batch Gradient Descent optimizer with configurable batch size and shuffling.
This implementation provides efficient mini-batch processing with proper data shuffling and batch creation for neural network training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for gradient descent updates |
0.001
|
batch_size
|
int
|
Size of mini-batches for training |
64
|
shuffle
|
bool
|
Whether to shuffle data at each epoch |
True
|
random_seed
|
int
|
Random seed for reproducibility |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
batch_size |
int
|
Mini-batch size |
shuffle |
bool
|
Shuffling flag |
history |
dict
|
Training history including losses and metrics |
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
create_mini_batches ¶
create_mini_batches(X: ndarray, Y: ndarray) -> list[tuple[np.ndarray, np.ndarray]]
Create mini-batches from training data with optional shuffling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[ndarray, ndarray]]
|
List of (X_batch, Y_batch) tuples |
Notes
If shuffle is True, data is randomly permuted before creating batches. The last batch may be smaller if the dataset size is not divisible by batch_size.
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update model parameters using gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using the standard gradient descent rule: θ = θ - α * ∇J(θ)
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
train_epoch ¶
train_epoch(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray], float]
Train for one epoch using mini-batch gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and epoch loss |
Notes
Performs one complete epoch of mini-batch gradient descent training.
Source code in src/dlhub/optimizers/mini_batch.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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using mini-batch gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Notes
Trains the model for the specified number of epochs using mini-batch gradient descent. Training history is stored in self.history.
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/mini_batch.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
MomentumOptimizer ¶
Gradient Descent with Momentum optimizer.
This implementation uses exponential weighted averages to accumulate gradients and includes bias correction for better convergence, especially in early training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates |
0.001
|
beta
|
float
|
Momentum parameter (exponential decay rate) |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction to momentum estimates |
True
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
beta |
float
|
Momentum parameter |
bias_correction |
bool
|
Bias correction flag |
epsilon |
float
|
Numerical stability constant |
v |
Dict[str, ndarray]
|
Momentum (velocity) estimates for each parameter |
t |
int
|
Time step counter for bias correction |
history |
Dict[str, List[float]]
|
Training history |
Source code in src/dlhub/optimizers/momentum.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 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 | |
initialize_velocity ¶
initialize_velocity(parameters: dict[str, ndarray]) -> None
Initialize velocity (momentum) estimates for all parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Model parameters to initialize velocity for |
required |
Notes
Velocities are initialized to zero arrays with the same shape as parameters.
Source code in src/dlhub/optimizers/momentum.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update parameters using momentum-based gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using momentum: v_t = β * v_{t-1} + (1-β) * g_t θ_t = θ_{t-1} - α * v_t_corrected
Where v_t_corrected includes bias correction if enabled.
Source code in src/dlhub/optimizers/momentum.py
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 | |
compute_gradient_norm ¶
compute_gradient_norm(gradients: dict[str, ndarray]) -> float
Compute the L2 norm of gradients for monitoring convergence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradients
|
Dict[str, ndarray]
|
Gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
float
|
L2 norm of all gradients |
Source code in src/dlhub/optimizers/momentum.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
train_step ¶
train_step(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray]]
Perform one training step with momentum optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and current loss |
Source code in src/dlhub/optimizers/momentum.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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using momentum optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Source code in src/dlhub/optimizers/momentum.py
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 | |
get_momentum_statistics ¶
get_momentum_statistics() -> dict[str, dict[str, float]]
Get statistics about momentum estimates.
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, float]]
|
Statistics for each parameter's momentum |
Source code in src/dlhub/optimizers/momentum.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
reset_optimizer_state ¶
reset_optimizer_state() -> None
Reset optimizer state including velocity estimates and time step.
Source code in src/dlhub/optimizers/momentum.py
276 277 278 279 280 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/momentum.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
RMSpropOptimizer ¶
RMSprop (Root Mean Square Propagation) optimizer.
RMSprop adapts the learning rate for each parameter by dividing by a running average of the magnitudes of recent gradients. This helps with convergence on non-convex functions and handles different scaling of parameters. It also applies a learning rate decay technique based on current step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates |
0.001
|
beta
|
float
|
Exponential decay rate for the second moment estimates |
0.9
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
bias_correction
|
bool
|
Whether to apply bias correction (not standard in RMSprop) |
False
|
decay
|
float
|
Learning rate decay factor |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
beta |
float
|
Decay rate for second moment estimates |
epsilon |
float
|
Numerical stability constant |
s |
Dict[str, ndarray]
|
Second moment estimates (squared gradients) for each parameter |
t |
int
|
Time step counter |
history |
Dict[str, List[float]]
|
Training history including losses and learning rates |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
initialize_second_moments ¶
initialize_second_moments(parameters: dict[str, ndarray]) -> None
Initialize second moment estimates for all parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Model parameters to initialize second moments for |
required |
Notes
Second moments are initialized to zero arrays with the same shape as parameters.
Source code in src/dlhub/optimizers/rmsprop.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
update_learning_rate ¶
update_learning_rate() -> None
Update learning rate with decay if specified.
Notes
Applies learning rate decay: lr = lr_initial / (1 + decay * t)
Source code in src/dlhub/optimizers/rmsprop.py
101 102 103 104 105 106 107 108 109 110 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update parameters using RMSprop optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using RMSprop: s_t = β * s_{t-1} + (1-β) * g_t² θ_t = θ_{t-1} - α * g_t / (√s_t + ε)
Where s_t is the exponential weighted average of squared gradients. Stores average RMS gradient for monitoring
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
compute_gradient_norm ¶
compute_gradient_norm(gradients: dict[str, ndarray]) -> float
Compute the L2 norm of gradients for monitoring convergence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradients
|
Dict[str, ndarray]
|
Gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
float
|
L2 norm of all gradients |
Source code in src/dlhub/optimizers/rmsprop.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
get_effective_learning_rates ¶
get_effective_learning_rates(parameters: dict[str, ndarray]) -> dict[str, np.ndarray]
Compute effective learning rates for each parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Effective learning rates for each parameter |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
train_step ¶
train_step(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray], float]
Perform one training step with RMSprop optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and current loss |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using RMSprop optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
get_second_moment_statistics ¶
get_second_moment_statistics() -> dict[str, dict[str, float]]
Get statistics about second moment estimates.
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, float]]
|
Statistics for each parameter's second moments |
Source code in src/dlhub/optimizers/rmsprop.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
reset_optimizer_state ¶
reset_optimizer_state() -> None
Reset optimizer state including second moment estimates and time step.
Source code in src/dlhub/optimizers/rmsprop.py
352 353 354 355 356 357 358 359 360 361 362 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/rmsprop.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
LearningRateScheduler ¶
Comprehensive Learning Rate Scheduler with multiple scheduling strategies.
This class provides various learning rate scheduling strategies commonly used in deep learning training, including step decay, cosine annealing, cyclical learning rates, and warm restarts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_lr
|
float
|
Initial learning rate |
required |
scheduler_type
|
SchedulerType
|
Type of scheduling strategy to use |
CONSTANT
|
total_steps
|
int
|
Total number of training steps (required for some schedulers) |
None
|
**kwargs
|
Additional parameters specific to each scheduler type |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
current_lr |
float
|
Current learning rate |
step_count |
int
|
Number of steps taken |
history |
list
|
History of learning rates |
Source code in src/dlhub/optimizers/schedules.py
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 | |
step ¶
step(metric: float | None = None) -> float
Update the learning rate for one step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
float
|
Current metric value (required for REDUCE_ON_PLATEAU) |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Updated learning rate |
Source code in src/dlhub/optimizers/schedules.py
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 | |
get_lr ¶
get_lr() -> float
Get current learning rate.
Source code in src/dlhub/optimizers/schedules.py
448 449 450 | |
reset ¶
reset() -> None
Reset scheduler to initial state.
Source code in src/dlhub/optimizers/schedules.py
452 453 454 455 456 457 458 459 460 461 | |
get_config ¶
get_config() -> dict[str, Any]
Get scheduler configuration.
Source code in src/dlhub/optimizers/schedules.py
463 464 465 466 467 468 469 470 471 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete scheduler state.
Source code in src/dlhub/optimizers/schedules.py
473 474 475 476 477 478 479 480 481 482 483 484 | |
load_state ¶
load_state(state: dict[str, Any]) -> None
Load scheduler state.
Source code in src/dlhub/optimizers/schedules.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
SchedulerType ¶
Bases: Enum
Enumeration of different scheduling strategies.
Source code in src/dlhub/optimizers/schedules.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
create_adam_optimizer ¶
create_adam_optimizer(learning_rate: float = 0.001, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-08, **kwargs) -> AdamOptimizer
Factory function to create Adam optimizer with common configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate |
0.001
|
beta1
|
float
|
First moment decay rate |
0.9
|
beta2
|
float
|
Second moment decay rate |
0.999
|
epsilon
|
float
|
Numerical stability constant |
1e-08
|
**kwargs
|
Additional optimizer parameters |
{}
|
Returns:
| Type | Description |
|---|---|
AdamOptimizer
|
Configured Adam optimizer |
Source code in src/dlhub/optimizers/adam.py
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 | |
create_adam_ewa_pair ¶
create_adam_ewa_pair(beta1: float = 0.9, beta2: float = 0.999) -> tuple[ExponentialWeightedAverage, ExponentialWeightedAverage]
Create EWA pair for Adam optimizer (first and second moments).
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
435 436 437 438 439 440 441 442 443 444 445 446 447 | |
create_momentum_ewa ¶
create_momentum_ewa(beta: float = 0.9) -> ExponentialWeightedAverage
Create EWA for momentum optimization.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
421 422 423 424 425 | |
create_rmsprop_ewa ¶
create_rmsprop_ewa(beta: float = 0.999) -> ExponentialWeightedAverage
Create EWA for RMSprop (second moments).
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
428 429 430 431 432 | |
create_cosine_scheduler ¶
create_cosine_scheduler(initial_lr: float, total_steps: int, eta_min: float = 0.0) -> LearningRateScheduler
Create cosine annealing scheduler.
Source code in src/dlhub/optimizers/schedules.py
517 518 519 520 521 522 523 524 525 526 | |
create_one_cycle_scheduler ¶
create_one_cycle_scheduler(initial_lr: float, max_lr: float, total_steps: int, pct_start: float = 0.3) -> LearningRateScheduler
Create one cycle scheduler.
Source code in src/dlhub/optimizers/schedules.py
529 530 531 532 533 534 535 536 537 538 539 | |
create_step_scheduler ¶
create_step_scheduler(initial_lr: float, step_size: int, gamma: float = 0.1) -> LearningRateScheduler
Create step decay scheduler.
Source code in src/dlhub/optimizers/schedules.py
505 506 507 508 509 510 511 512 513 514 | |
create_warmup_cosine_scheduler ¶
create_warmup_cosine_scheduler(initial_lr: float, total_steps: int, warmup_steps: int) -> LearningRateScheduler
Create warmup + cosine scheduler.
Source code in src/dlhub/optimizers/schedules.py
542 543 544 545 546 547 548 549 550 551 | |
adam ¶
Adam Optimizer Implementation¶
A comprehensive implementation of the Adam (Adaptive Moment Estimation) optimizer with bias correction, gradient clipping, and numerical stability features.
References
- Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization. https://arxiv.org/abs/1412.6980
License
MIT
AdamOptimizer ¶
Adam (Adaptive Moment Estimation) Optimizer
Adam combines the advantages of AdaGrad and RMSProp by computing adaptive learning rates for each parameter using estimates of first and second moments of the gradients.
The algorithm maintains exponentially decaying averages of past gradients and past squared gradients, which act as estimates of the first moment (mean) and second moment (uncentered variance) of the gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate (alpha in the paper) |
0.001
|
beta1
|
float
|
Exponential decay rate for first moment estimates |
0.9
|
beta2
|
float
|
Exponential decay rate for second moment estimates |
0.999
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
weight_decay
|
float
|
Weight decay coefficient (L2 regularization) |
0.0
|
amsgrad
|
bool
|
Whether to use AMSGrad variant which maintains maximum of squared gradients |
False
|
gradient_clip_norm
|
float
|
Maximum norm for gradient clipping |
None
|
gradient_clip_value
|
float
|
Maximum absolute value for gradient clipping |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
m |
dict
|
First moment estimates (exponentially decaying average of gradients) |
v |
dict
|
Second moment estimates (exponentially decaying average of squared gradients) |
v_hat_max |
dict
|
Maximum of v_hat values (used in AMSGrad) |
t |
int
|
Time step (number of updates performed) |
Source code in src/dlhub/optimizers/adam.py
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 | |
update ¶
update(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Perform a single optimization step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict
|
Dictionary of parameters to optimize |
required |
gradients
|
dict
|
Dictionary of gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters |
Source code in src/dlhub/optimizers/adam.py
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 | |
get_config ¶
get_config() -> dict
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
dict
|
Configuration dictionary |
Source code in src/dlhub/optimizers/adam.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |
reset_state ¶
reset_state() -> None
Reset optimizer state (moments and time step).
Source code in src/dlhub/optimizers/adam.py
250 251 252 253 254 255 256 257 258 259 260 261 | |
get_state ¶
get_state() -> dict
Get complete optimizer state.
Returns:
| Type | Description |
|---|---|
dict
|
Complete state dictionary |
Source code in src/dlhub/optimizers/adam.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | |
load_state ¶
load_state(state: dict) -> None
Load optimizer state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
State dictionary from get_state() |
required |
Source code in src/dlhub/optimizers/adam.py
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 | |
create_adam_optimizer ¶
create_adam_optimizer(learning_rate: float = 0.001, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-08, **kwargs) -> AdamOptimizer
Factory function to create Adam optimizer with common configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate |
0.001
|
beta1
|
float
|
First moment decay rate |
0.9
|
beta2
|
float
|
Second moment decay rate |
0.999
|
epsilon
|
float
|
Numerical stability constant |
1e-08
|
**kwargs
|
Additional optimizer parameters |
{}
|
Returns:
| Type | Description |
|---|---|
AdamOptimizer
|
Configured Adam optimizer |
Source code in src/dlhub/optimizers/adam.py
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 | |
base ¶
Optimizer Contract¶
The interface every optimizer in this subpackage presents to code that drives a training loop: given the current parameters and their gradients, return the updated parameters.
The base class is deliberately thin. An optimizer is the artifact a reader came to read, so the update rule stays written out in full in its own module rather than being assembled from hooks defined here. What this class supplies is the uniform signature that lets a driver hold a collection of optimizers without knowing which one it has -- the comparison harness being the case that motivated extracting it.
Two conventions worth stating, because they are the ones a new optimizer gets wrong:
Bias correction is the optimizer's own decision, not the contract's. Momentum and RMSprop maintain running averages that start at zero and are therefore biased toward zero for the first few steps; whether to divide that bias out is a property of the method, and the modules that implement those methods expose it as a constructor flag. A driver that wants a like-for-like race across optimizers has to set that flag deliberately rather than inherit whatever each default happens to be.
The step index is passed in. Optimizers whose update depends on how many steps
have been taken -- anything applying bias correction -- read it from the argument
rather than counting internally, so that a driver resetting an optimizer between
runs does not have to trust it to reset its own counter. The canonical optimizer
modules in this subpackage predate this contract and count internally instead; the
adapters in comparison bridge the two by clearing that counter in reset,
which is the property the contract actually cares about and the one its tests
check.
License
MIT
BaseOptimizer ¶
Base class for all optimizers with common functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates. |
0.01
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Step size applied to each update. |
name |
str
|
Human-readable label, used to key and plot results. Subclasses set it to the name of the method they implement. |
Source code in src/dlhub/optimizers/base.py
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 | |
update_parameters ¶
update_parameters(params: dict[str, ndarray], grads: dict[str, ndarray], t: int) -> dict[str, np.ndarray]
Update parameters using optimization algorithm.
Implementations return a new dictionary rather than mutating the one they were given, so that a caller can keep the parameter trajectory of a run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration, counted from one. Optimizers applying bias
correction divide by |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always, on the base class. An optimizer is defined by its update rule, so there is no meaningful default to inherit. |
Source code in src/dlhub/optimizers/base.py
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 | |
reset ¶
reset() -> None
Reset optimizer state for new optimization run.
The base implementation does nothing, which is correct for a stateless optimizer such as plain gradient descent. Any optimizer accumulating state across steps -- a velocity, a second moment -- must override this and clear it, or a second run starts from wherever the first one ended and its trajectory is not reproducible.
Source code in src/dlhub/optimizers/base.py
103 104 105 106 107 108 109 110 111 112 113 | |
comparison ¶
Optimization Algorithms Comparison¶
A comprehensive comparison framework for evaluating different optimization algorithms in deep learning contexts. This module provides implementations and utilities to compare gradient descent variants (SGD, Momentum, RMSprop, Adam) on various loss landscapes and datasets, demonstrating their convergence properties and performance characteristics.
This implementation serves as both a practical tool for optimizer selection and an educational resource for understanding optimization dynamics in neural networks.
References
- Kingma, D. P., & Ba, J. (2014). Adam: A Method for Stochastic Optimization. arXiv preprint arXiv:1412.6980.
- Ruder, S. (2016). An overview of gradient descent optimization algorithms. arXiv preprint arXiv:1609.04747.
- Duchi, J., Hazan, E., & Singer, Y. (2011). Adaptive subgradient methods for online learning and stochastic optimization. JMLR, 12, 2121-2159.
License
MIT License
Notes
This implementation focuses on numerical stability and educational clarity.
The optimizers raced here are the canonical implementations from this
subpackage, presented through a uniform driver interface rather than
reimplemented; see :data:RACE_BIAS_CORRECTION for the one configuration
decision the race makes on their behalf.
Visualization utilities require matplotlib and are designed for Jupyter notebooks.
OptimizerType ¶
Bases: Enum
Enumeration of available optimizer types.
Source code in src/dlhub/optimizers/comparison.py
77 78 79 80 81 82 83 | |
OptimizationRun
dataclass
¶
The trace of one optimizer descending one problem, and its summary.
Not to be confused with :class:dlhub.tuning.ExperimentResult, which records
the outcome of a hyperparameter search rather than a single descent.
Attributes:
| Name | Type | Description |
|---|---|---|
optimizer_name |
str
|
Name of the optimizer used. |
losses |
List[float]
|
Loss values recorded during training. |
parameters |
List[Dict]
|
Parameter values at each iteration. |
convergence_time |
float
|
Time taken for convergence (in seconds). |
final_loss |
float
|
Final loss value achieved. |
iterations_to_converge |
int
|
Number of iterations required for convergence. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
SGDOptimizer ¶
Bases: BaseOptimizer
Stochastic Gradient Descent optimizer.
Basic gradient descent with fixed learning rate. Simple but often effective baseline for comparison with more sophisticated optimizers.
The update rule itself lives in :mod:dlhub.optimizers.mini_batch, which is
where the hub teaches plain gradient descent; this class exists to present it
through the driver contract so the race can hold it alongside the others.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size for parameter updates. |
0.01
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
update_parameters ¶
update_parameters(params: dict, grads: dict, t: int) -> dict
Update parameters using vanilla gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration. Unused: the step is the same at every iteration, since plain gradient descent carries no state to correct for. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters after SGD step. |
Source code in src/dlhub/optimizers/comparison.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
MomentumOptimizer ¶
Bases: BaseOptimizer
Momentum optimizer using exponential moving averages.
Accelerates gradient descent by accumulating momentum in consistent directions and dampening oscillations. Particularly effective in ravines and saddle points.
Wraps :class:dlhub.optimizers.momentum.MomentumOptimizer, which is where the
update rule is derived and written out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size for parameter updates. |
0.01
|
beta
|
float
|
Momentum coefficient for exponential moving average. |
0.9
|
bias_correction
|
bool
|
Whether to divide out the bias of the zero-initialised velocity. See
:data: |
``RACE_BIAS_CORRECTION``
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
update_parameters ¶
update_parameters(params: dict, grads: dict, t: int) -> dict
Update parameters using momentum-based gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration. Unused: the canonical optimizer counts its own
steps, and :meth: |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters after momentum step. |
Source code in src/dlhub/optimizers/comparison.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
reset ¶
reset() -> None
Reset momentum terms for new optimization run.
Source code in src/dlhub/optimizers/comparison.py
220 221 222 | |
RMSpropOptimizer ¶
Bases: BaseOptimizer
RMSprop (Root Mean Square Propagation) optimizer.
Adapts the learning rate per parameter using a running average of squared gradients, so that parameters with consistently large gradients take smaller steps.
Wraps :class:dlhub.optimizers.rmsprop.RMSpropOptimizer, which is where the
update rule is derived and written out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size for parameter updates. |
0.001
|
beta
|
float
|
Decay rate for the running average of squared gradients. |
0.9
|
epsilon
|
float
|
Small constant to prevent division by zero. |
1e-8
|
bias_correction
|
bool
|
Whether to divide out the bias of the zero-initialised second moment.
The canonical module defaults this off, which is how RMSprop is usually
written; see :data: |
``RACE_BIAS_CORRECTION``
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
update_parameters ¶
update_parameters(params: dict, grads: dict, t: int) -> dict
Update parameters using RMSprop optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration. Unused, for the reason given on
:meth: |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters after RMSprop step. |
Source code in src/dlhub/optimizers/comparison.py
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | |
reset ¶
reset() -> None
Reset second moment estimates for new optimization run.
Source code in src/dlhub/optimizers/comparison.py
290 291 292 | |
AdamOptimizer ¶
Bases: BaseOptimizer
Adam (Adaptive Moment Estimation) optimizer.
Combines benefits of Momentum and RMSprop by maintaining both first and second moment estimates of gradients. Generally robust and effective across many problems.
Wraps :class:dlhub.optimizers.adam.AdamOptimizer, which is where the update
rule is derived and written out. Adam bias-corrects both moments by
construction, so it takes no flag: the correction is part of the method
rather than an option on it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Step size for parameter updates. |
0.001
|
beta1
|
float
|
Exponential decay rate for first moment estimates. |
0.9
|
beta2
|
float
|
Exponential decay rate for second moment estimates. |
0.999
|
epsilon
|
float
|
Small constant to prevent division by zero. |
1e-8
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
update_parameters ¶
update_parameters(params: dict, grads: dict, t: int) -> dict
Update parameters using Adam optimization algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Current parameter values. |
required |
grads
|
dict
|
Gradients for each parameter. |
required |
t
|
int
|
Current iteration. Unused, for the reason given on
:meth: |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Updated parameters after Adam step. |
Source code in src/dlhub/optimizers/comparison.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
reset ¶
reset() -> None
Reset first and second moment estimates for new optimization run.
Source code in src/dlhub/optimizers/comparison.py
356 357 358 | |
OptimizationProblem ¶
Base class for defining optimization problems with loss functions and gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the optimization problem. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute loss for given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameter values. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Loss value. |
Source code in src/dlhub/optimizers/comparison.py
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
gradients ¶
gradients(params: dict) -> dict
Compute gradients for given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameter values. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Gradients for each parameter. |
Source code in src/dlhub/optimizers/comparison.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | |
initial_parameters ¶
initial_parameters() -> dict
Get initial parameter values for optimization.
Returns:
| Type | Description |
|---|---|
dict
|
Initial parameter values. |
Source code in src/dlhub/optimizers/comparison.py
406 407 408 409 410 411 412 413 414 415 | |
QuadraticBowl ¶
Bases: OptimizationProblem
Simple quadratic bowl optimization problem: f(x,y) = ax² + by².
Well-conditioned convex problem useful for demonstrating basic optimizer behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Coefficient for x² term. |
1.0
|
b
|
float
|
Coefficient for y² term. |
1.0
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute quadratic loss: ax² + by².
Source code in src/dlhub/optimizers/comparison.py
437 438 439 440 | |
gradients ¶
gradients(params: dict) -> dict
Compute gradients: [2ax, 2by].
Source code in src/dlhub/optimizers/comparison.py
442 443 444 445 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize at (5, 5) for clear visualization.
Source code in src/dlhub/optimizers/comparison.py
447 448 449 | |
RosenbrockFunction ¶
Bases: OptimizationProblem
Rosenbrock function: f(x,y) = (a-x)² + b(y-x²)².
Classic non-convex optimization benchmark with narrow curved valley. Challenging for optimizers due to ill-conditioning and plateau regions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Parameter controlling x-offset of minimum. |
1.0
|
b
|
float
|
Parameter controlling valley curvature (higher = more challenging). |
100.0
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute Rosenbrock function value.
Source code in src/dlhub/optimizers/comparison.py
472 473 474 475 | |
gradients ¶
gradients(params: dict) -> dict
Compute Rosenbrock gradients analytically.
Source code in src/dlhub/optimizers/comparison.py
477 478 479 480 481 482 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize away from minimum for interesting optimization path.
Source code in src/dlhub/optimizers/comparison.py
484 485 486 | |
BealeFunction ¶
Bases: OptimizationProblem
Beale function: f(x,y) = (1.5 - x + xy)² + (2.25 - x + xy²)² + (2.625 - x + xy³)².
Multimodal function with global minimum and several local minima. Tests optimizer robustness to local minima and saddle points.
Source code in src/dlhub/optimizers/comparison.py
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 | |
loss_function ¶
loss_function(params: dict) -> float
Compute Beale function value.
Source code in src/dlhub/optimizers/comparison.py
500 501 502 503 504 505 506 | |
gradients ¶
gradients(params: dict) -> dict
Compute Beale function gradients analytically.
Source code in src/dlhub/optimizers/comparison.py
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
initial_parameters ¶
initial_parameters() -> dict
Initialize at challenging starting point.
Source code in src/dlhub/optimizers/comparison.py
527 528 529 | |
OptimizationComparison ¶
Comprehensive framework for comparing optimization algorithms.
Provides utilities to run multiple optimizers on various problems, collect performance metrics, and generate comparative visualizations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_iterations
|
int
|
Maximum number of optimization iterations. |
1000
|
tolerance
|
float
|
Convergence tolerance for loss change. |
1e-6
|
verbose
|
bool
|
Whether to print progress information. |
True
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
create_optimizer ¶
create_optimizer(optimizer_type: OptimizerType, **kwargs) -> BaseOptimizer
Factory method to create optimizer instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer_type
|
OptimizerType
|
Type of optimizer to create. |
required |
**kwargs
|
Additional parameters for optimizer initialization. |
{}
|
Returns:
| Type | Description |
|---|---|
BaseOptimizer
|
Configured optimizer instance. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
run_optimization ¶
run_optimization(problem: OptimizationProblem, optimizer: BaseOptimizer) -> OptimizationRun
Run single optimization experiment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
OptimizationProblem
|
Problem to optimize. |
required |
optimizer
|
BaseOptimizer
|
Optimizer to use. |
required |
Returns:
| Type | Description |
|---|---|
OptimizationRun
|
Results of optimization including metrics and trajectory. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
compare_optimizers ¶
compare_optimizers(problem: OptimizationProblem, optimizer_configs: dict[OptimizerType, dict]) -> dict[str, OptimizationRun]
Compare multiple optimizers on a single problem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
OptimizationProblem
|
Problem to optimize. |
required |
optimizer_configs
|
dict
|
Dictionary mapping optimizer types to their configuration parameters. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Results for each optimizer. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
run_comprehensive_comparison ¶
run_comprehensive_comparison() -> dict[str, dict[str, OptimizationRun]]
Run comprehensive comparison across multiple problems and optimizers.
Returns:
| Type | Description |
|---|---|
dict
|
Nested dictionary: {problem_name: {optimizer_name: result}} |
Source code in src/dlhub/optimizers/comparison.py
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 | |
plot_convergence_comparison ¶
plot_convergence_comparison(results: dict[str, OptimizationRun], problem_name: str, log_scale: bool = True)
Plot convergence curves for optimizer comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict
|
Results from optimizer comparison. |
required |
problem_name
|
str
|
Name of the problem for plot title. |
required |
log_scale
|
bool
|
Whether to use logarithmic scale for loss. |
True
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
plot_optimization_paths ¶
plot_optimization_paths(results: dict[str, OptimizationRun], problem: OptimizationProblem, contour_levels: int = 20)
Plot optimization trajectories on loss landscape contours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
dict
|
Results from optimizer comparison. |
required |
problem
|
OptimizationProblem
|
Problem instance for computing loss landscape. |
required |
contour_levels
|
int
|
Number of contour levels to display. |
20
|
Source code in src/dlhub/optimizers/comparison.py
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 | |
generate_summary_table ¶
generate_summary_table(all_results: dict[str, dict[str, OptimizationRun]]) -> None
Generate formatted summary table of optimization results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from comprehensive comparison. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
OptimizationAnalytics ¶
Advanced analytics utilities for optimization comparison results.
Provides statistical analysis, performance ranking, and detailed insights into optimizer behavior across different problem types.
Source code in src/dlhub/optimizers/comparison.py
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 | |
compute_convergence_metrics
staticmethod
¶
compute_convergence_metrics(result: OptimizationRun) -> dict[str, float]
Compute detailed convergence metrics for a single optimization run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
OptimizationRun
|
Single optimization result to analyze. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of computed metrics. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
rank_optimizers
staticmethod
¶
rank_optimizers(all_results: dict[str, dict[str, OptimizationRun]]) -> dict[str, dict[str, int]]
Rank optimizers across different problems and metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from optimization comparison. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Rankings for each optimizer on each problem. |
Source code in src/dlhub/optimizers/comparison.py
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 | |
generate_performance_heatmap
staticmethod
¶
generate_performance_heatmap(all_results: dict[str, dict[str, OptimizationRun]])
Generate performance heatmap comparing optimizers across problems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_results
|
dict
|
Complete results from optimization comparison. |
required |
Source code in src/dlhub/optimizers/comparison.py
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 | |
main ¶
main()
Main function demonstrating comprehensive optimization comparison.
Runs all optimizers on multiple test problems and generates comparative visualizations and summary statistics.
Source code in src/dlhub/optimizers/comparison.py
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 | |
run_custom_experiment ¶
run_custom_experiment()
Example of running custom optimization experiment with specific configurations.
Demonstrates how to use the framework for targeted analysis with custom hyperparameters and problems.
Source code in src/dlhub/optimizers/comparison.py
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 | |
demonstrate_hyperparameter_sensitivity ¶
demonstrate_hyperparameter_sensitivity()
Demonstrate sensitivity of optimizers to hyperparameter choices.
Shows how different learning rates affect optimizer performance on the same problem, highlighting the importance of tuning.
Source code in src/dlhub/optimizers/comparison.py
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 | |
exponential_weighted_averages ¶
Exponential Weighted Averages (EWA) Implementation¶
A comprehensive implementation of exponential weighted averages with bias correction, multiple averaging strategies, and numerical stability features.
Exponential weighted averages are fundamental building blocks for modern optimization algorithms like Adam, RMSprop, and momentum-based optimizers.
References
- Used in Adam, RMSprop, Momentum optimizers
- Bias correction technique from Adam paper (Kingma & Ba, 2014)
License
MIT
Notes
Bias correction divides the accumulator by the total weight it has applied to its
samples. Textbooks write that weight as 1 - beta**t, which is its closed form
when beta is the same at every step.
This implementation tracks the weight directly, through
weight = beta_t * weight + (1 - beta_t). The two agree exactly for a constant
beta. They diverge once beta varies with t, which is what warmup_steps and the
EXPONENTIAL_DECAY strategy both do: there the closed form understates the
applied weight and the correction inflates the result.
AveragingStrategy ¶
Bases: Enum
Enumeration of different averaging strategies.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
44 45 46 47 48 49 50 | |
ExponentialWeightedAverage ¶
Exponential Weighted Average with bias correction and multiple strategies.
This class implements exponential weighted averages (also known as exponentially weighted moving averages) with various correction techniques commonly used in deep learning optimization algorithms.
The basic formula is: v_t = beta * v_{t-1} + (1 - beta) * theta_t
Where: - v_t is the average at time t - beta is the decay parameter - theta_t is the current value - v_0 = 0 (initial value)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
Decay parameter (0 < beta < 1). Higher values give more weight to past values. Common values: 0.9 (momentum), 0.999 (second moments in Adam) |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction to account for initialization bias |
True
|
strategy
|
AveragingStrategy
|
Averaging strategy to use |
AveragingStrategy.BIAS_CORRECTED
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
warmup_steps
|
int
|
Number of warmup steps before applying full averaging |
0
|
Attributes:
| Name | Type | Description |
|---|---|---|
v |
float or ndarray
|
Current average value |
t |
int
|
Time step (number of updates) |
history |
list
|
History of average values |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 | |
update ¶
update(value: float | ndarray) -> float | np.ndarray
Update the exponential weighted average with a new value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float or ndarray
|
New value to incorporate into the average |
required |
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Updated average value |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
get_current_average ¶
get_current_average() -> float | np.ndarray | None
Get the current average value.
Returns:
| Type | Description |
|---|---|
float, np.ndarray, or None
|
Current average value, None if no updates have been made |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
get_variance ¶
get_variance() -> float | np.ndarray | None
Get the current variance estimate (only available with VARIANCE_CORRECTED strategy).
Returns:
| Type | Description |
|---|---|
float, np.ndarray, or None
|
Current variance estimate, None if not available |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
reset ¶
reset() -> None
Reset the exponential weighted average to initial state.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
251 252 253 254 255 256 257 258 | |
get_effective_window_size ¶
get_effective_window_size() -> float
Get the effective window size of the exponential weighted average.
The effective window size is approximately 1/(1-beta).
Returns:
| Type | Description |
|---|---|
float
|
Effective window size |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
260 261 262 263 264 265 266 267 268 269 270 271 | |
get_config ¶
get_config() -> dict[str, Any]
Get configuration dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Configuration dictionary |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete state dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Complete state dictionary |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
load_state ¶
load_state(state: dict[str, Any]) -> None
Load state from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
State dictionary from get_state() |
required |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
MultiVariateEWA ¶
Multi-variate Exponential Weighted Average for handling multiple variables simultaneously.
This class manages multiple exponential weighted averages, commonly used in optimization algorithms where different parameters need separate averages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
Common decay parameter for all variables |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction |
True
|
strategy
|
AveragingStrategy
|
Averaging strategy |
AveragingStrategy.BIAS_CORRECTED
|
**kwargs
|
Additional parameters passed to individual EWA instances |
{}
|
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
update ¶
update(values: dict[str, float | ndarray]) -> dict[str, float | np.ndarray]
Update all averages with new values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
dict
|
Dictionary of new values for each variable |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary of updated averages |
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
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 | |
get_averages ¶
get_averages() -> dict[str, float | np.ndarray]
Get current averages for all variables.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
399 400 401 | |
reset ¶
reset() -> None
Reset all averages.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
403 404 405 406 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete state for all averages.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
408 409 410 411 412 413 414 415 416 417 418 | |
create_momentum_ewa ¶
create_momentum_ewa(beta: float = 0.9) -> ExponentialWeightedAverage
Create EWA for momentum optimization.
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
421 422 423 424 425 | |
create_rmsprop_ewa ¶
create_rmsprop_ewa(beta: float = 0.999) -> ExponentialWeightedAverage
Create EWA for RMSprop (second moments).
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
428 429 430 431 432 | |
create_adam_ewa_pair ¶
create_adam_ewa_pair(beta1: float = 0.9, beta2: float = 0.999) -> tuple[ExponentialWeightedAverage, ExponentialWeightedAverage]
Create EWA pair for Adam optimizer (first and second moments).
Source code in src/dlhub/optimizers/exponential_weighted_averages.py
435 436 437 438 439 440 441 442 443 444 445 446 447 | |
mini_batch ¶
Mini-batch Gradient Descent Implementation¶
This module implements efficient mini-batch gradient descent with proper shuffling and batch creation for neural network training.
License
MIT
MiniBatchGradientDescent ¶
Mini-batch Gradient Descent optimizer with configurable batch size and shuffling.
This implementation provides efficient mini-batch processing with proper data shuffling and batch creation for neural network training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for gradient descent updates |
0.001
|
batch_size
|
int
|
Size of mini-batches for training |
64
|
shuffle
|
bool
|
Whether to shuffle data at each epoch |
True
|
random_seed
|
int
|
Random seed for reproducibility |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
batch_size |
int
|
Mini-batch size |
shuffle |
bool
|
Shuffling flag |
history |
dict
|
Training history including losses and metrics |
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
create_mini_batches ¶
create_mini_batches(X: ndarray, Y: ndarray) -> list[tuple[np.ndarray, np.ndarray]]
Create mini-batches from training data with optional shuffling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[ndarray, ndarray]]
|
List of (X_batch, Y_batch) tuples |
Notes
If shuffle is True, data is randomly permuted before creating batches. The last batch may be smaller if the dataset size is not divisible by batch_size.
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update model parameters using gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using the standard gradient descent rule: θ = θ - α * ∇J(θ)
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
train_epoch ¶
train_epoch(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray], float]
Train for one epoch using mini-batch gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and epoch loss |
Notes
Performs one complete epoch of mini-batch gradient descent training.
Source code in src/dlhub/optimizers/mini_batch.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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using mini-batch gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features of shape (n_features, m_examples) |
required |
Y
|
ndarray
|
Target labels of shape (n_classes, m_examples) |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Notes
Trains the model for the specified number of epochs using mini-batch gradient descent. Training history is stored in self.history.
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/mini_batch.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
initialize_parameters ¶
initialize_parameters(layer_dims: list[int]) -> dict[str, np.ndarray]
Initialize parameters for a neural network with given layer dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer_dims
|
List[int]
|
List containing the dimensions of each layer |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Dictionary containing initialized parameters |
Source code in src/dlhub/optimizers/mini_batch.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
example_usage ¶
example_usage()
Example demonstrating how to use MiniBatchGradientDescent.
Source code in src/dlhub/optimizers/mini_batch.py
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 | |
momentum ¶
Momentum Optimizer Implementation¶
This module implements gradient descent with momentum, including exponential weighted averages and bias correction for efficient neural network training.
License
MIT
MomentumOptimizer ¶
Gradient Descent with Momentum optimizer.
This implementation uses exponential weighted averages to accumulate gradients and includes bias correction for better convergence, especially in early training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates |
0.001
|
beta
|
float
|
Momentum parameter (exponential decay rate) |
0.9
|
bias_correction
|
bool
|
Whether to apply bias correction to momentum estimates |
True
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
beta |
float
|
Momentum parameter |
bias_correction |
bool
|
Bias correction flag |
epsilon |
float
|
Numerical stability constant |
v |
Dict[str, ndarray]
|
Momentum (velocity) estimates for each parameter |
t |
int
|
Time step counter for bias correction |
history |
Dict[str, List[float]]
|
Training history |
Source code in src/dlhub/optimizers/momentum.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 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 | |
initialize_velocity ¶
initialize_velocity(parameters: dict[str, ndarray]) -> None
Initialize velocity (momentum) estimates for all parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Model parameters to initialize velocity for |
required |
Notes
Velocities are initialized to zero arrays with the same shape as parameters.
Source code in src/dlhub/optimizers/momentum.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update parameters using momentum-based gradient descent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using momentum: v_t = β * v_{t-1} + (1-β) * g_t θ_t = θ_{t-1} - α * v_t_corrected
Where v_t_corrected includes bias correction if enabled.
Source code in src/dlhub/optimizers/momentum.py
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 | |
compute_gradient_norm ¶
compute_gradient_norm(gradients: dict[str, ndarray]) -> float
Compute the L2 norm of gradients for monitoring convergence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradients
|
Dict[str, ndarray]
|
Gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
float
|
L2 norm of all gradients |
Source code in src/dlhub/optimizers/momentum.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
train_step ¶
train_step(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray]]
Perform one training step with momentum optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and current loss |
Source code in src/dlhub/optimizers/momentum.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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using momentum optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Source code in src/dlhub/optimizers/momentum.py
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 | |
get_momentum_statistics ¶
get_momentum_statistics() -> dict[str, dict[str, float]]
Get statistics about momentum estimates.
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, float]]
|
Statistics for each parameter's momentum |
Source code in src/dlhub/optimizers/momentum.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
reset_optimizer_state ¶
reset_optimizer_state() -> None
Reset optimizer state including velocity estimates and time step.
Source code in src/dlhub/optimizers/momentum.py
276 277 278 279 280 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/momentum.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
example_usage ¶
example_usage()
Example demonstrating how to use MomentumOptimizer.
Source code in src/dlhub/optimizers/momentum.py
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 | |
rmsprop ¶
RMSprop Optimizer Implementation¶
This module implements the RMSprop (Root Mean Square Propagation) optimizer with adaptive learning rate optimization using squared gradient accumulation and parameter-wise learning rate adjustment.
License
MIT
RMSpropOptimizer ¶
RMSprop (Root Mean Square Propagation) optimizer.
RMSprop adapts the learning rate for each parameter by dividing by a running average of the magnitudes of recent gradients. This helps with convergence on non-convex functions and handles different scaling of parameters. It also applies a learning rate decay technique based on current step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
learning_rate
|
float
|
Learning rate for parameter updates |
0.001
|
beta
|
float
|
Exponential decay rate for the second moment estimates |
0.9
|
epsilon
|
float
|
Small constant for numerical stability |
1e-8
|
bias_correction
|
bool
|
Whether to apply bias correction (not standard in RMSprop) |
False
|
decay
|
float
|
Learning rate decay factor |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Current learning rate |
beta |
float
|
Decay rate for second moment estimates |
epsilon |
float
|
Numerical stability constant |
s |
Dict[str, ndarray]
|
Second moment estimates (squared gradients) for each parameter |
t |
int
|
Time step counter |
history |
Dict[str, List[float]]
|
Training history including losses and learning rates |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
initialize_second_moments ¶
initialize_second_moments(parameters: dict[str, ndarray]) -> None
Initialize second moment estimates for all parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Model parameters to initialize second moments for |
required |
Notes
Second moments are initialized to zero arrays with the same shape as parameters.
Source code in src/dlhub/optimizers/rmsprop.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
update_learning_rate ¶
update_learning_rate() -> None
Update learning rate with decay if specified.
Notes
Applies learning rate decay: lr = lr_initial / (1 + decay * t)
Source code in src/dlhub/optimizers/rmsprop.py
101 102 103 104 105 106 107 108 109 110 | |
update_parameters ¶
update_parameters(parameters: dict[str, ndarray], gradients: dict[str, ndarray]) -> dict[str, np.ndarray]
Update parameters using RMSprop optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
gradients
|
Dict[str, ndarray]
|
Computed gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Updated parameters |
Notes
Updates parameters using RMSprop: s_t = β * s_{t-1} + (1-β) * g_t² θ_t = θ_{t-1} - α * g_t / (√s_t + ε)
Where s_t is the exponential weighted average of squared gradients. Stores average RMS gradient for monitoring
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
compute_gradient_norm ¶
compute_gradient_norm(gradients: dict[str, ndarray]) -> float
Compute the L2 norm of gradients for monitoring convergence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gradients
|
Dict[str, ndarray]
|
Gradients for each parameter |
required |
Returns:
| Type | Description |
|---|---|
float
|
L2 norm of all gradients |
Source code in src/dlhub/optimizers/rmsprop.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
get_effective_learning_rates ¶
get_effective_learning_rates(parameters: dict[str, ndarray]) -> dict[str, np.ndarray]
Compute effective learning rates for each parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Effective learning rates for each parameter |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
train_step ¶
train_step(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable) -> tuple[dict[str, np.ndarray], float]
Perform one training step with RMSprop optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Current model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
Returns:
| Type | Description |
|---|---|
Tuple[Dict[str, ndarray], float]
|
Updated parameters and current loss |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
fit ¶
fit(X: ndarray, Y: ndarray, parameters: dict[str, ndarray], forward_propagation_fn: callable, backward_propagation_fn: callable, compute_cost_fn: callable, epochs: int = 1000, print_cost: bool = True, print_every: int = 100) -> dict[str, np.ndarray]
Train the model using RMSprop optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input features |
required |
Y
|
ndarray
|
Target labels |
required |
parameters
|
Dict[str, ndarray]
|
Initial model parameters |
required |
forward_propagation_fn
|
callable
|
Function to compute forward propagation |
required |
backward_propagation_fn
|
callable
|
Function to compute backward propagation |
required |
compute_cost_fn
|
callable
|
Function to compute cost/loss |
required |
epochs
|
int
|
Number of training epochs |
1000
|
print_cost
|
bool
|
Whether to print cost during training |
True
|
print_every
|
int
|
Print cost every N epochs |
100
|
Returns:
| Type | Description |
|---|---|
Dict[str, ndarray]
|
Trained parameters |
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
get_second_moment_statistics ¶
get_second_moment_statistics() -> dict[str, dict[str, float]]
Get statistics about second moment estimates.
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[str, float]]
|
Statistics for each parameter's second moments |
Source code in src/dlhub/optimizers/rmsprop.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
reset_optimizer_state ¶
reset_optimizer_state() -> None
Reset optimizer state including second moment estimates and time step.
Source code in src/dlhub/optimizers/rmsprop.py
352 353 354 355 356 357 358 359 360 361 362 | |
get_config ¶
get_config() -> dict[str, Any]
Get optimizer configuration.
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Configuration dictionary |
Source code in src/dlhub/optimizers/rmsprop.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
adaptive_learning_rate_analysis ¶
adaptive_learning_rate_analysis(optimizer: RMSpropOptimizer, parameters: dict[str, ndarray]) -> None
Analyze and visualize adaptive learning rates in RMSprop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
RMSpropOptimizer
|
Trained RMSprop optimizer |
required |
parameters
|
Dict[str, ndarray]
|
Model parameters |
required |
Source code in src/dlhub/optimizers/rmsprop.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
example_usage ¶
example_usage()
Example demonstrating how to use RMSpropOptimizer.
Source code in src/dlhub/optimizers/rmsprop.py
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 | |
schedules ¶
Learning Rate Scheduler Implementation¶
A comprehensive implementation of various learning rate scheduling strategies commonly used in deep learning optimization.
Learning rate scheduling is crucial for training stability and convergence. This module provides multiple scheduling strategies with configurable parameters.
References
- Loshchilov, I., & Hutter, F. (2016). SGDR: Stochastic Gradient Descent with Warm Restarts
- Smith, L. N. (2017). Cyclical Learning Rates for Training Neural Networks
- Goyal, P. et al. (2017). Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour
License
MIT
SchedulerType ¶
Bases: Enum
Enumeration of different scheduling strategies.
Source code in src/dlhub/optimizers/schedules.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
LearningRateScheduler ¶
Comprehensive Learning Rate Scheduler with multiple scheduling strategies.
This class provides various learning rate scheduling strategies commonly used in deep learning training, including step decay, cosine annealing, cyclical learning rates, and warm restarts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_lr
|
float
|
Initial learning rate |
required |
scheduler_type
|
SchedulerType
|
Type of scheduling strategy to use |
CONSTANT
|
total_steps
|
int
|
Total number of training steps (required for some schedulers) |
None
|
**kwargs
|
Additional parameters specific to each scheduler type |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
current_lr |
float
|
Current learning rate |
step_count |
int
|
Number of steps taken |
history |
list
|
History of learning rates |
Source code in src/dlhub/optimizers/schedules.py
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 | |
step ¶
step(metric: float | None = None) -> float
Update the learning rate for one step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric
|
float
|
Current metric value (required for REDUCE_ON_PLATEAU) |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Updated learning rate |
Source code in src/dlhub/optimizers/schedules.py
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 | |
get_lr ¶
get_lr() -> float
Get current learning rate.
Source code in src/dlhub/optimizers/schedules.py
448 449 450 | |
reset ¶
reset() -> None
Reset scheduler to initial state.
Source code in src/dlhub/optimizers/schedules.py
452 453 454 455 456 457 458 459 460 461 | |
get_config ¶
get_config() -> dict[str, Any]
Get scheduler configuration.
Source code in src/dlhub/optimizers/schedules.py
463 464 465 466 467 468 469 470 471 | |
get_state ¶
get_state() -> dict[str, Any]
Get complete scheduler state.
Source code in src/dlhub/optimizers/schedules.py
473 474 475 476 477 478 479 480 481 482 483 484 | |
load_state ¶
load_state(state: dict[str, Any]) -> None
Load scheduler state.
Source code in src/dlhub/optimizers/schedules.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 | |
create_step_scheduler ¶
create_step_scheduler(initial_lr: float, step_size: int, gamma: float = 0.1) -> LearningRateScheduler
Create step decay scheduler.
Source code in src/dlhub/optimizers/schedules.py
505 506 507 508 509 510 511 512 513 514 | |
create_cosine_scheduler ¶
create_cosine_scheduler(initial_lr: float, total_steps: int, eta_min: float = 0.0) -> LearningRateScheduler
Create cosine annealing scheduler.
Source code in src/dlhub/optimizers/schedules.py
517 518 519 520 521 522 523 524 525 526 | |
create_one_cycle_scheduler ¶
create_one_cycle_scheduler(initial_lr: float, max_lr: float, total_steps: int, pct_start: float = 0.3) -> LearningRateScheduler
Create one cycle scheduler.
Source code in src/dlhub/optimizers/schedules.py
529 530 531 532 533 534 535 536 537 538 539 | |
create_warmup_cosine_scheduler ¶
create_warmup_cosine_scheduler(initial_lr: float, total_steps: int, warmup_steps: int) -> LearningRateScheduler
Create warmup + cosine scheduler.
Source code in src/dlhub/optimizers/schedules.py
542 543 544 545 546 547 548 549 550 551 | |