Lasso Modeling
generate_modeling_data
Generate the response and predictor data, optionally filtering to the top x quantile.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
colname |
str
|
The column name to use as the response variable. This column name should exist in |
required |
response_df |
DataFrame
|
The transformed response variable DataFrame. |
required |
predictors_df |
DataFrame
|
The predictors DataFrame. |
required |
drop_intercept |
bool
|
Whether to drop the intercept in the formula. This adds a -1 to the formula if True. See the patsy docs https://patsy.readthedocs.io/en/latest/formulas.html#intercept-handling. |
True
|
formula |
str | None
|
The formula to use for the interaction model. If None, the formula will be generated automatically. The formula should be in the form of |
None
|
quantile_threshold |
float | None
|
If specified, filters the data to only include rows where |
None
|
Returns:
Type | Description |
---|---|
tuple[DataFrame, DataFrame]
|
A tuple of the response variable DataFrame and the predictors DataFrame. |
Raises:
Type | Description |
---|---|
ValueError
|
If |
ValueError
|
If any columns in |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.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 |
|
stratification_classification
Bin the binding and perturbation data and create groups for stratified k folds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
binding_series |
Series
|
The binding vector to use for stratification |
required |
perturbation_series |
Series
|
The perturbation vector to use for stratification |
required |
bins |
list
|
The bins to use for stratification. The default is [0, 8, 64, 512, np.inf] |
[0, 8, 64, 512, inf]
|
Returns:
Type | Description |
---|---|
ndarray
|
A numpy array of the stratified classes |
Raises:
Type | Description |
---|---|
ValueError
|
If the length of |
ValueError
|
If the length of |
ValueError
|
If |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
stratified_cv_modeling
This conducts the LassoCV modeling. The name stratified_cv_modeling
is a misnomer.
There is nothing in this function that requires any specific model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y |
DataFrame
|
The response variable to use for modeling. This should be a single column. See |
required |
X |
DataFrame
|
The predictors to use for modeling. This should be an NxP DataFrame where N == len(y) and P is the number of predictors. See |
required |
classes |
ndarray
|
The classes to use for stratified k-fold cross-validation. This should be an array of integers generated by |
required |
estimator |
BaseEstimator
|
The estimator to use for fitting the model. It must have a |
LassoCV()
|
skf |
StratifiedKFold
|
The StratifiedKFold object to use for stratified splits. Default is StratifiedKFold(n_splits=4, shuffle=True, random_state=42) |
StratifiedKFold(n_splits=4, shuffle=True, random_state=42)
|
sample_weight |
ndarray | None
|
The sample weights to use for fitting the model. Default is None, which is the default behavior for LassoCV.fit() |
None
|
Returns:
Type | Description |
---|---|
BaseEstimator
|
The LassoCV model |
Raises:
Type | Description |
---|---|
ValueError
|
if y is not a single column DataFrame |
ValueError
|
if X is not a DataFrame with 1 or more columns, or the number of rows in y does not match the number of rows in X |
ValueError
|
if classes is not a numpy array or is empty |
ValueError
|
If the estimator does not have a |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
bootstrap_stratified_cv_modeling
Perform bootstrap resampling to generate confidence intervals for Lasso coefficients. See 6.2 in https://hastie.su.domains/StatLearnSparsity/ – this is an implementation of the algorithm described in that section.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_bootstraps |
int
|
The number of bootstrap samples to generate. |
1000
|
ci_percentiles |
list[float]
|
A list of CI percentiles to calculate. Default to [95, 99] |
[95.0, 99.0]
|
use_sample_weight_in_cv |
bool
|
Whether to use sample weights, calculated as the proportion of times a given record appears, in boostrap iterations. Default is False. |
False
|
kwargs |
The required arguments to |
{}
|
Returns:
Type | Description |
---|---|
tuple[dict[str, dict[str, tuple[float, float]]], DataFrame, list[float]]
|
A tuple where: - The first element is a dictionary of confidence intervals, where keys are CI levels (e.g., “95.0”) and values are dictionaries mapping each coefficient to its lower and upper bounds, with columns named according to the predictors in |
Raises:
Type | Description |
---|---|
ValueError
|
If any of the required keyword arguments for |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If |
ValueError
|
If the response variable is not in the predictors DataFrame. If there are replicates, they are expected to have the suffix _rep\d+. This is attempted to be removed from the response variable name to match the predictors DataFrame. |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
examine_bootstrap_coefficients
Generate a plot, and output the set of coefficients that meet the ci_level and threshold criteria.
Usage:
Examples¶
Display the plot immediately:
fig, significant_cols = plot_significant_lasso_coefficients(
lasso_model_output,
ci_level="95.0",
threshold=0.5
)
fig.show()
Further customize the plot:
fig, significant_cols = plot_significant_lasso_coefficients(
lasso_model_output,
ci_level="95.0",
threshold=0.5
)
ax = fig.gca() # Get the current axes
ax.set_title("Custom Title for Lasso Coefficients", fontsize=16)
ax.set_ylabel("Custom Y-axis Label")
fig.show()
Save the plot to a file:
fig, significant_cols = plot_significant_lasso_coefficients(
lasso_model_output,
ci_level="95.0",
threshold=0.5
)
fig.savefig("significant_lasso_coefficients.png", dpi=300, bbox_inches='tight')
Embed in Jupyter Notebooks:
plot_significant_lasso_coefficients(
lasso_model_output,
ci_level="95.0",
threshold=0.5
)
Add annotations or modify appearance:
fig, significant_cols = plot_significant_lasso_coefficients(
lasso_model_output,
ci_level="95.0",
threshold=0.5
)
ax = fig.gca()
ax.annotate("Important Coefficient", xy=(1.5, 1), xytext=(2, 2),
arrowprops=dict(facecolor='black', shrink=0.05))
fig.show()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lasso_model_output |
The output from |
required | |
ci_level |
str
|
The confidence interval level to use, e.g., “95.0”. |
'95.0'
|
threshold |
float
|
The threshold for selecting coefficients to plot. Only coefficients with confidence intervals entirely above or below this threshold will be displayed. |
0.0
|
Returns:
Type | Description |
---|---|
tuple[Figure, dict[str, tuple[float, float]]]
|
A tuple containing: - The created Matplotlib Figure for further customization. - A dictionary where the keys are the significant coefficients and the values are the confidence intervals specified in the |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 |
|
get_significant_predictors
This function is used to get the significant predictors for a given TF using one of two methods, either the bootstrapped LassoCV, in which case we look for intervals that do not cross 0, or direct LassoCV with a selection on non-zero coefficients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method |
Literal['lassocv_ols', 'bootstrap_lassocv']
|
This must be ‘lassocv_ols’, which will conduct a single lassocv call followed by pruning non zero coefficients by pvalue until all are significant at a given threshold, or ‘bootstrap_lassocv’, which will conduct bootstrapped lassoCV and return only coefficients which are deemed significant by ci_percentile and threshold (see |
required |
perturbed_tf |
str
|
the TF for which the significant predictors are to be identified |
required |
response_df |
DataFrame
|
The DataFrame containing the response values |
required |
predictors_df |
DataFrame
|
The DataFrame containing the predictor values |
required |
add_max_lrb |
bool
|
A boolean to add/not add in the max_LRB term for a response TF into the formula that we perform bootstrapping on |
required |
kwargs |
Any
|
Additional arguments to be passed to the function. Expected arguments are ‘quantile_threshold’ from generate_modeling_data() and ‘ci_percentile’ from examine_bootstrap_coefficients() |
{}
|
Returns:
Type | Description |
---|---|
dict[str, set[str] | DataFrame | ndarray]
|
|
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
stratified_cv_r2
Calculate the average stratified CV r-squared for a given estimator and data. By default, this is a 4-fold stratified CV with a LinearRegression estimator. Note that this method will add an intercept to X if it doesn’t already exist.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y |
DataFrame
|
The response variable. See generate_modeling_data() |
required |
X |
DataFrame
|
The predictor variables. See generate_modeling_data() |
required |
classes |
ndarray
|
the stratification classes for the data |
required |
estimator |
BaseEstimator
|
the estimator to be used in the modeling. By default, this is a LinearRegression() model. |
LinearRegression()
|
skf |
StratifiedKFold
|
the StratifiedKFold object to be used in the modeling. By default, this is a 4-fold stratified CV with shuffle=True and random_state=42. |
StratifiedKFold(n_splits=4, shuffle=True, random_state=42)
|
Returns:
Type | Description |
---|---|
float
|
the average r-squared value for the stratified CV |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
try_interactor_variants
For a given interactor, replace the term in the formula with one variant: 1. the main effect For this variant, calculate the average stratified CV r-squared with stratified_cv_r2().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
intersect_coefficients |
set[str]
|
the set of coefficients that are determined to be significant, expected to be from either a bootstrap procedure on a LassoCV model on a full partition of the data and the top 10% by perturbed binding, or LassoCV followed by backwards selection by adj-rsquared. |
required |
interactor |
str
|
the interactor term to be tested |
required |
kwargs |
Any
|
additional arguments to be passed to the function. Expected arguments are ‘y’, ‘X’, and ‘stratification_classes’. See stratified_cv_r2() for more information. |
{}
|
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
a list with three dict entries, each with key ‘interactor’, ‘variant’, ‘avg_r2’ |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
get_interactor_importance
For each interactor in the intersect_coefficients, run test_interactor_importance to
compare the variants’ avg_rsquared to the input_model_avg_rsquared. If a variant of
the interactor term is better, record it in a dictionary. Return the
instersect_coefficient
model’s avg R-squared and the dictionary of interaction
alternatives that, when that alternative replaces a single interaction term,
improves the rsquared.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
y |
DataFrame
|
the response variable |
required |
full_X |
DataFrame
|
the full predictor matrix |
required |
stratification_classes |
ndarray
|
the stratification classes for the data |
required |
intersect_coefficients |
set
|
the set of coefficients that are determined to be significant, expected to be from either a bootstrap procedure on a LassoCV model on a full partition of the data and the top 10% by perturbed binding, or LassoCV followed by backwards selection by p-value significance. |
required |
Returns:
Type | Description |
---|---|
tuple[float, list[dict[str, Any]]]
|
a tuple with the first element being the input_model_avg_rsquared and the second element being a list of dictionaries with keys ‘interactor’, ‘variant’, and ‘avg_r2’ |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
OLSFeatureSelector
Bases: BaseEstimator
, TransformerMixin
This class performs iterative feature selection using OLS.
It removes non-significant features until all remaining features are significant.
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 |
|
__init__(p_value_threshold=0.05)
¶
Initialize the OLSFeatureSelector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p_value_threshold |
The threshold for significance of features. |
0.05
|
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
835 836 837 838 839 840 841 842 843 844 |
|
fit(X, y, **kwargs)
¶
Fit the OLS model and identify significant features. Significant features are selected based based on coef p-value <= p_value_threshold.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
A DataFrame of predictors. |
required | |
y |
A Series of the response variable. |
required | |
kwargs |
Optional arguments for |
{}
|
Returns:
Type | Description |
---|---|
OLSFeatureSelector
|
self |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
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 |
|
get_significant_features(drop_intercept=True)
¶
Get the list of significant features.
param drop_intercept: Whether to exclude the intercept term from the list. NOTE: this only looks for a feature called “Intercept”
Returns:
Type | Description |
---|---|
list
|
List of significant feature names. |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 |
|
get_summary()
¶
Get the OLS model summary as a DataFrame.
Returns:
Type | Description |
---|---|
DataFrame
|
A DataFrame containing coefficients, standard errors, t-values, and p-values. |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
943 944 945 946 947 948 949 950 951 952 953 |
|
refine_features(X, y)
¶
Iteratively fit the selector and transform the data in one step.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
A DataFrame of predictors. |
required | |
y |
A Series of the response variable. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
A DataFrame with only significant predictors. |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 |
|
transform(X)
¶
Iteratively apply OLS to remove non-significant features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
A DataFrame of predictors. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
A DataFrame with only significant features. |
Source code in yeastdnnexplorer/ml_models/lasso_modeling.py
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 |
|