Utility Functions
build_cox_model(df, duration_col, event_col)
Fits a Cox Proportional Hazards model to the data.
- df: Pandas DataFrame containing the clinical variables, predicted risk scores, durations, and event indicators.
- duration_col: The name of the column in df that contains the survival times.
- event_col: The name of the column in df that contains the event occurrence indicator (1 if event occurred, 0 otherwise).
Returns: - cox_model: Fitted CoxPH model.
Source code in flexynesis/utils.py
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 |
|
evaluate_baseline_performance(train_dataset, test_dataset, variable_name, methods, n_folds=5, n_jobs=4)
Evaluates the performance of RandomForest, Support Vector Machine, and/or XGBoost models on a given variable from the provided datasets using cross-validation.
This function preprocesses the training and testing data, performs grid search with cross-validation to find the best hyperparameters for the specified methods, and then evaluates the performance of these models on the testing set. It supports evaluation for both categorical and numerical variables using appropriate machine learning models.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
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 |
|
evaluate_baseline_survival_performance(train_dataset, test_dataset, duration_col, event_col, n_folds=5, n_jobs=4)
Evaluates the baseline performance of a Random Survival Forest model on survival data using the Concordance Index.
The function preprocesses both training and testing datasets to prepare appropriate survival data (comprising durations and event occurrences), performs cross-validation to assess model robustness, and then calculates the Concordance Index on the test data. It uses a Random Survival Forest (RSF) as the predictive model.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
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 |
|
evaluate_classifier(y_true, y_pred, print_report=False)
Evaluate the performance of a classifier using multiple metrics and optionally print a detailed classification report.
This function computes balanced accuracy, F1 score (macro), and Cohen's Kappa score for the given true and predicted labels.
If print_report
is set to True, it prints a detailed classification report.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
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 |
|
evaluate_regressor(y_true, y_pred)
Evaluate the performance of a regression model using mean squared error, R-squared, and Pearson correlation coefficient.
This function computes the mean squared error (MSE) between true and predicted values as a measure of prediction accuracy. It also performs a linear regression analysis between the true and predicted values to obtain the R-squared value, which explains the variance ratio, and the Pearson correlation coefficient, providing insight into the linear relationship strength.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
|
evaluate_survival(outputs, durations, events)
Computes the concordance index (c-index) for survival predictions.
Parameters: - durations: A numpy array or a torch tensor of true survival times or durations. - events: A numpy array or a torch tensor indicating whether an event (e.g., death) occurred. - risk_scores: Predicted risk scores from the model. Higher scores should indicate higher risk of event.
Returns: - A dictionary containing the c-index.
Source code in flexynesis/utils.py
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 |
|
evaluate_wrapper(method, y_pred_dict, dataset, surv_event_var=None, surv_time_var=None)
Evaluates predictions for different variables within a dataset using appropriate metrics based on the variable type. Supports evaluation for numerical, categorical, and survival data.
This function loops through each variable in the predictions dictionary, determines the type of the variable, and evaluates the predictions using the appropriate method: regression, classification, or survival analysis. It compiles the metrics into a list of dictionaries, which is then converted into a pandas DataFrame.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
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 |
|
get_optimal_clusters(data, min_k=2, max_k=10)
Find the optimal number of clusters (k) for k-means clustering on the given data, based on the silhouette score, and return the cluster labels for the optimal k.
Parameters: - data: pandas DataFrame or numpy array, dataset for clustering. - min_k: int, minimum number of clusters to try. - max_k: int, maximum number of clusters to try.
Returns: - int, the optimal number of clusters based on the silhouette score. - DataFrame, silhouette scores for each k. - array, cluster labels for the optimal number of clusters.
Source code in flexynesis/utils.py
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 |
|
k_means_clustering(data, k)
Perform k-means clustering on a given pandas DataFrame.
Parameters: - data: pandas DataFrame, where rows are samples and columns are features. - k: int, the number of clusters to form.
Returns: - cluster_labels: A pandas Series indicating the cluster label for each sample. - kmeans: The fitted KMeans instance, which can be used to access cluster centers and other attributes.
Source code in flexynesis/utils.py
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 |
|
louvain_clustering(X, threshold=None, k=None)
Create a graph from pairwise distances within X. You can define a threshold to connect edges or specify k for k-nearest neighbors.
Parameters: - X: numpy array, shape (n_samples, n_features) - threshold: float, distance threshold to create an edge between two nodes. - k: int, number of nearest neighbors to connect for each node.
Returns: - G: a networkx graph
Source code in flexynesis/utils.py
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 |
|
plot_dim_reduced(matrix, labels, method='pca', color_type='categorical', scatter_kwargs=None, legend_kwargs=None, figsize=(10, 8))
Plots the first two dimensions of the transformed input matrix in a 2D scatter plot, with points colored based on the provided labels. The transformation method can be either PCA or UMAP.
This function allows users to control several aspects of the plot such as the figure size, scatter plot properties, and legend properties.
Parameters: |
|
---|
Source code in flexynesis/utils.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|
plot_hazard_ratios(cox_model)
Plots the sorted log hazard ratios from a fitted Cox Proportional Hazards model, sorted by their p-values and annotated with stars to indicate levels of statistical significance.
Parameters: - cox_model: A fitted CoxPH model from the lifelines package.
Source code in flexynesis/utils.py
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 |
|
plot_kaplan_meier_curves(durations, events, categorical_variable)
Plots Kaplan-Meier survival curves for different groups defined by a categorical variable.
Parameters: - durations: An array-like object of survival times or durations. - events: An array-like object indicating whether an event (e.g., death) occurred (1) or was censored (0). - categorical_variable: An array-like object defining groups for plotting different survival curves.
Source code in flexynesis/utils.py
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 |
|
plot_label_concordance_heatmap(labels1, labels2, figsize=(12, 10))
Plot a heatmap reflecting the concordance between two sets of labels using pandas crosstab.
Parameters: - labels1: The first set of labels. - labels2: The second set of labels.
Source code in flexynesis/utils.py
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 |
|
plot_scatter(true_values, predicted_values)
Plots a scatterplot of true vs predicted values, with a regression line and annotated with the Pearson correlation coefficient.
Parameters: |
|
---|
Source code in flexynesis/utils.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 152 153 154 155 156 157 |
|
remove_batch_associated_variables(data, variable_types, target_dict, batch_dict=None, mi_threshold=0.1)
Filter the data matrix to keep only the columns that are predictive of the target variables and not predictive of the batch variables.
Parameters: |
|
---|
Returns: |
|
---|
Source code in flexynesis/utils.py
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 |
|