mait-pipeline 0.1.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 PERSIMUNE Health Informatics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,39 @@
1
+ # MAIT — Medical Artificial Intelligence Toolbox
2
+
3
+ MAIT provides explainable machine-learning workflows for tabular research data. This alpha package offers a CPU classification demonstration using Logistic Regression and Random Forest, with evaluation tables, a saved model, and explanation plots.
4
+
5
+ ## Install and run
6
+
7
+ ```bash
8
+ python -m pip install "mait-pipeline[analysis]"
9
+ mait demo ./my-mait-demo
10
+ ```
11
+
12
+ These commands apply after the PyPI release is published. For the trial release, install the MAIT wheel from TestPyPI separately from analysis dependencies sourced from PyPI. For a repository checkout, use `python -m pip install ".[analysis]"`.
13
+
14
+ Choose a new output directory. The demo command runs the pipeline in a separate process and saves its input data, configured script, and results there. It does not modify your notebook's working directory.
15
+
16
+ To export the script without running it:
17
+
18
+ ```bash
19
+ mait export-demo ./my-export
20
+ ```
21
+
22
+ Or in Python:
23
+
24
+ ```python
25
+ from mait import export_demo
26
+ script = export_demo("./my-export")
27
+ ```
28
+
29
+ ## Scope and validation
30
+
31
+ The installed demo completed on Apple Silicon macOS with Python 3.11, including a fresh analysis-environment installation and installation of the uploaded TestPyPI wheel. Other platforms, model combinations, survival analysis, regression, and equivalence to historical versions remain unverified. This small demonstration does not establish clinical predictive performance.
32
+
33
+ The analysis extra still includes legacy dependencies that will be separated as MAIT becomes a modular library. LightGBM is excluded; its separate `lightgbm` extra also needs a native OpenMP runtime on macOS.
34
+
35
+ The packaged template is synchronized with the repository tutorial template and checked automatically. See the [source repository](https://github.com/PERSIMUNE/MAIT) for methods, tutorials, limitations, and release instructions.
36
+
37
+ ## Citation
38
+
39
+ Ramtin Zargari Marandi, Anne Svane Frahm, Jens Lundgren, Daniel Dawson Murray, and Maja Milojevic. Medical artificial intelligence toolbox (MAIT): an explainable machine learning framework for binary classification, survival modelling, and regression analyses. 2025. https://doi.org/10.48550/arXiv.2501.04547
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: mait-pipeline
3
+ Version: 0.1.0a2
4
+ Summary: Medical Artificial Intelligence Toolbox: experimental packaging of the existing MAIT pipeline
5
+ Author: Ramtin Zargari Marandi
6
+ Maintainer: MAIT contributors
7
+ License: MIT License
8
+
9
+ Copyright (c) 2024 PERSIMUNE Health Informatics
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: Repository, https://github.com/PERSIMUNE/MAIT
30
+ Requires-Python: >=3.10
31
+ Description-Content-Type: text/markdown
32
+ License-File: LICENSE
33
+ Provides-Extra: analysis
34
+ Requires-Dist: numpy<2,>=1.26; extra == "analysis"
35
+ Requires-Dist: pandas<3,>=2.2; extra == "analysis"
36
+ Requires-Dist: scikit-learn<1.7,>=1.6; extra == "analysis"
37
+ Requires-Dist: scipy<1.18,>=1.13; extra == "analysis"
38
+ Requires-Dist: shap<0.48,>=0.47; extra == "analysis"
39
+ Requires-Dist: scikit-survival<0.25,>=0.24; extra == "analysis"
40
+ Requires-Dist: matplotlib; extra == "analysis"
41
+ Requires-Dist: seaborn; extra == "analysis"
42
+ Requires-Dist: joblib; extra == "analysis"
43
+ Requires-Dist: catboost; extra == "analysis"
44
+ Requires-Dist: feyn; extra == "analysis"
45
+ Requires-Dist: mrmr-selection; extra == "analysis"
46
+ Requires-Dist: survshap; extra == "analysis"
47
+ Requires-Dist: openpyxl; extra == "analysis"
48
+ Requires-Dist: sympy; extra == "analysis"
49
+ Requires-Dist: imbalanced-learn; extra == "analysis"
50
+ Requires-Dist: ipython; extra == "analysis"
51
+ Requires-Dist: psutil; extra == "analysis"
52
+ Provides-Extra: lightgbm
53
+ Requires-Dist: lightgbm; extra == "lightgbm"
54
+ Dynamic: license-file
55
+
56
+ # MAIT — Medical Artificial Intelligence Toolbox
57
+
58
+ MAIT provides explainable machine-learning workflows for tabular research data. This alpha package offers a CPU classification demonstration using Logistic Regression and Random Forest, with evaluation tables, a saved model, and explanation plots.
59
+
60
+ ## Install and run
61
+
62
+ ```bash
63
+ python -m pip install "mait-pipeline[analysis]"
64
+ mait demo ./my-mait-demo
65
+ ```
66
+
67
+ These commands apply after the PyPI release is published. For the trial release, install the MAIT wheel from TestPyPI separately from analysis dependencies sourced from PyPI. For a repository checkout, use `python -m pip install ".[analysis]"`.
68
+
69
+ Choose a new output directory. The demo command runs the pipeline in a separate process and saves its input data, configured script, and results there. It does not modify your notebook's working directory.
70
+
71
+ To export the script without running it:
72
+
73
+ ```bash
74
+ mait export-demo ./my-export
75
+ ```
76
+
77
+ Or in Python:
78
+
79
+ ```python
80
+ from mait import export_demo
81
+ script = export_demo("./my-export")
82
+ ```
83
+
84
+ ## Scope and validation
85
+
86
+ The installed demo completed on Apple Silicon macOS with Python 3.11, including a fresh analysis-environment installation and installation of the uploaded TestPyPI wheel. Other platforms, model combinations, survival analysis, regression, and equivalence to historical versions remain unverified. This small demonstration does not establish clinical predictive performance.
87
+
88
+ The analysis extra still includes legacy dependencies that will be separated as MAIT becomes a modular library. LightGBM is excluded; its separate `lightgbm` extra also needs a native OpenMP runtime on macOS.
89
+
90
+ The packaged template is synchronized with the repository tutorial template and checked automatically. See the [source repository](https://github.com/PERSIMUNE/MAIT) for methods, tutorials, limitations, and release instructions.
91
+
92
+ ## Citation
93
+
94
+ Ramtin Zargari Marandi, Anne Svane Frahm, Jens Lundgren, Daniel Dawson Murray, and Maja Milojevic. Medical artificial intelligence toolbox (MAIT): an explainable machine learning framework for binary classification, survival modelling, and regression analyses. 2025. https://doi.org/10.48550/arXiv.2501.04547
@@ -0,0 +1,454 @@
1
+ ![Alt Text](https://github.com/PERSIMUNE/MAIT/blob/main/MAITlogo.gif)
2
+ [![GitHub release](https://img.shields.io/github/v/release/PERSIMUNE/MAIT)](https://github.com/PERSIMUNE/MAIT/releases)
3
+ [![Docker Pulls](https://img.shields.io/docker/pulls/danishdyna/mait_30092024gpu)](https://hub.docker.com/r/danishdyna/mait_30092024gpu)
4
+ ![Python Versions](https://img.shields.io/badge/Python-3.10%20%7C%203.12-blue)
5
+ [![License](https://img.shields.io/github/license/PERSIMUNE/MAIT)](https://github.com/PERSIMUNE/MAIT/blob/main/LICENSE)
6
+ [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2FPERSIMUNE%2FMAIT&count_bg=%233DC853&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=MAIT+codes+visitors&edge_flat=false)](https://hits.seeyoufarm.com)
7
+ [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fpersimune.github.io%2FMAIT%2F&count_bg=%233D7CC8&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=MAIT+book+portal+visitors&edge_flat=false)](https://hits.seeyoufarm.com)
8
+ [![arXiv](https://img.shields.io/badge/arXiv-2501.04547-B31B1B)](https://arxiv.org/abs/2501.04547)
9
+ # MAIT - medical artificial intelligence toolbox
10
+
11
+ ## Start here
12
+
13
+ MAIT is an open-source Python workflow for explainable machine learning on tabular research data, supporting binary classification, survival modelling, and regression.
14
+
15
+ - **Explore the configuration interface:** [Open MAIT](https://maitconfig.streamlit.app/). This prepares a script; analysis runs in your own Python environment.
16
+ - **Try the included dataset:** follow the [quick-start guide](QUICK_START_DEMO.md).
17
+ - **See published applications:** [Research using MAIT](RESEARCH_USING_MAIT.md).
18
+ - **Understand the methods:** read the [manual](MANUAL.md) and [MAIT paper](https://arxiv.org/abs/2501.04547).
19
+
20
+ The configuration interface and the analysis pipeline have separate dependencies. Installing the interface alone does not install the full analysis environment.
21
+
22
+ ## Introduction
23
+ Welcome to the MAIT repository! This pipeline, implemented in Python, is designed to streamline your machine learning workflows using Jupyter Notebooks. It is compatible with both Windows and Linux operating systems. This repository also includes several tutorial notebooks to help you get started quickly. You can also refer to the `MANUAL` of MAIT for documentation. To overview MAIT's unique features and capabilities, we highly recommend reading the [MAIT preprint](https://arxiv.org/abs/2501.04547) on arXiv. If you use MAIT in your research, please remember to cite it in your publications.
24
+
25
+
26
+ ## MAIT Workflow Overview
27
+
28
+ The MAIT framework provides a comprehensive machine learning pipeline for medical data analysis. The workflow consists of several interconnected stages, from data preprocessing to model interpretation:
29
+
30
+ ```mermaid
31
+ flowchart TD
32
+ %% Data Input Layer
33
+ subgraph DataInput ["� Data Input Layer"]
34
+ RawData[("Raw Medical Data<br/>CSV format<br/>Tabular structure")]
35
+ ExtData[("External Validation Data<br/>Independent test set<br/>Same feature structure")]
36
+ ConfigFile[("Configuration Settings<br/>JSON parameters<br/>Streamlit interface")]
37
+ end
38
+
39
+ %% Data Preprocessing Layer
40
+ subgraph Preprocessing ["🧹 Data Preprocessing Layer"]
41
+ DataClean["Data Cleaning & Validation<br/>• Drop NaN outcome rows<br/>• Handle empty entries<br/>• Data type conversion"]
42
+ MissingData["Handle Missing Values<br/>• KNN imputation<br/>• Filter high missingness<br/>• Column/row filtering"]
43
+ OutlierDetect["Outlier Detection<br/>• Isolation Forest algorithm<br/>• Anomaly removal<br/>• Optional preprocessing"]
44
+ RareCategories["Rare Categories Merging<br/>• Threshold: 5% default<br/>• 'Missing' category<br/>• String conversion"]
45
+ end
46
+
47
+ %% Data Split Layer
48
+ subgraph DataSplit ["� Data Split Layer"]
49
+ TrainSet[("Training Set (80%)<br/>Model development<br/>Cross-validation")]
50
+ TestSet[("Test Set (20%)<br/>Final evaluation<br/>Hold-out validation")]
51
+ ExtVal[("External Validation<br/>Independent dataset<br/>Real-world testing")]
52
+ end
53
+
54
+ %% Feature Engineering Layer
55
+ subgraph FeatureEng ["⚙️ Feature Engineering Layer"]
56
+ FeatureSelect["Feature Selection (mRMR)<br/>• Min-redundancy Max-relevance<br/>• Configurable num features<br/>• Mutual information"]
57
+ DataScale["Data Scaling<br/>• Robust scaling method<br/>• Optional preprocessing<br/>• Numerical features"]
58
+ Encoding["Categorical Encoding<br/>• One-hot encoding<br/>• String conversion<br/>• Handle categories"]
59
+ end
60
+
61
+ %% Model Training Layer
62
+ subgraph ModelTraining ["Model Training Layer"]
63
+ CVFolds["Cross-Validation (5-fold)<br/>• Stratified K-fold<br/>• Random state control<br/>• Performance estimation"]
64
+ HPTuning["Hyperparameter Tuning<br/>• RandomizedSearchCV<br/>• 10 iterations default<br/>• ROC-AUC optimization"]
65
+ ModelFit["Model Training<br/>• Class weight balancing<br/>• Sample weights<br/>• Fit-predict cycle"]
66
+ ThresholdOpt["Threshold Optimization<br/>• Youden's J statistic<br/>• ROC curve analysis<br/>• Optimal cutoff"]
67
+ end
68
+
69
+ %% Available Models
70
+ subgraph Models ["Available Models"]
71
+ RF["Random Forest<br/>• n_estimators: 100-1000<br/>• max_depth: 3-10<br/>• Bootstrap sampling"]
72
+ LGB["LightGBM<br/>• Gradient boosting<br/>• GPU support<br/>• GOSS algorithm"]
73
+ CB["CatBoost<br/>• Categorical features<br/>• Ordered encoding<br/>• Symmetric trees"]
74
+ QLattice["QLattice (Symbolic)<br/>• Feyn library<br/>• Mathematical expressions<br/>• Symbolic regression"]
75
+ LR["Logistic Regression<br/>• Linear classification<br/>• L1/L2 regularization<br/>• Probability estimates"]
76
+ NB["Naive Bayes<br/>• Gaussian distribution<br/>• Probabilistic classifier<br/>• No hyperparameters"]
77
+ HGBC["Hist Gradient Boosting<br/>• Histogram-based<br/>• Fast performance<br/>• Large datasets"]
78
+ end
79
+
80
+ %% Model Evaluation Layer
81
+ subgraph Evaluation ["� Model Evaluation Layer"]
82
+ Performance["Performance Metrics<br/>• ROC-AUC & PR-AUC<br/>• MCC, F1-score<br/>• Sensitivity, Specificity"]
83
+ BestModel["Best Model Selection<br/>• Mean CV performance<br/>• ROC-AUC ranking<br/>• Statistical comparison"]
84
+ TestEval["Test Set Evaluation<br/>• Hold-out validation<br/>• Final performance<br/>• Generalization test"]
85
+ end
86
+
87
+ %% Model Interpretation Layer
88
+ subgraph Interpretation ["� Model Interpretation Layer"]
89
+ SHAP["SHAP Analysis<br/>• TreeExplainer<br/>• Feature contributions<br/>• Local explanations"]
90
+ FeatureImp["Feature Importance<br/>• Permutation importance<br/>• Tree-based importance<br/>• Ranking analysis"]
91
+ ModelExplain["Model Explainability<br/>• Global interpretations<br/>• Feature interactions<br/>• Decision paths"]
92
+ end
93
+
94
+ %% Results and Visualization Layer
95
+ subgraph Results ["� Results & Visualization Layer"]
96
+ ROCCurve["ROC Curves<br/>• Multi-model comparison<br/>• AUC visualization<br/>• Threshold analysis"]
97
+ SHAPPlots["SHAP Plots<br/>• Summary plots<br/>• Decision plots<br/>• Feature contributions"]
98
+ ConfMatrix["Confusion Matrix<br/>• Classification results<br/>• Error analysis<br/>• Threshold evaluation"]
99
+ Reports["Performance Reports<br/>• Comprehensive metrics<br/>• Model comparisons<br/>• Export formats"]
100
+ end
101
+
102
+ %% Optional Advanced Analysis
103
+ subgraph Advanced ["� Advanced Analysis (Optional)"]
104
+ Survival["Survival Analysis<br/>• Random Survival Forest<br/>• Cox regression<br/>• Time-to-event modeling"]
105
+ Regression["Regression Analysis<br/>• Random Forest Regressor<br/>• Linear regression<br/>• Continuous outcomes"]
106
+ Calibration["Model Calibration<br/>• Probability calibration<br/>• Conformal predictions<br/>• Uncertainty quantification"]
107
+ end
108
+
109
+ %% Connections between layers
110
+ DataInput --> Preprocessing
111
+ Preprocessing --> DataSplit
112
+ DataSplit --> FeatureEng
113
+ FeatureEng --> ModelTraining
114
+ ModelTraining --> Models
115
+ Models --> Evaluation
116
+ Evaluation --> Interpretation
117
+ Interpretation --> Results
118
+ Results --> Advanced
119
+
120
+ %% Styling for better readability
121
+ classDef dataInput fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#0d47a1
122
+ classDef preprocessing fill:#e1bee7,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
123
+ classDef models fill:#a5d6a7,stroke:#388e3c,stroke-width:2px,color:#1b5e20
124
+ classDef interpretation fill:#ffe0b2,stroke:#ef6c00,stroke-width:2px,color:#bf360c
125
+ classDef advanced fill:#f8bbd9,stroke:#c2185b,stroke-width:2px,color:#880e4f
126
+
127
+ %% Apply classes to subgraphs and nodes
128
+ class DataInput,RawData,ExtData,ConfigFile dataInput
129
+ class Preprocessing,DataSplit,FeatureEng,ModelTraining,DataClean,MissingData,OutlierDetect,RareCategories,TrainSet,TestSet,ExtVal,FeatureSelect,DataScale,Encoding,CVFolds,HPTuning,ModelFit,ThresholdOpt preprocessing
130
+ class Models,Evaluation,RF,LGB,CB,QLattice,LR,NB,HGBC,Performance,BestModel,TestEval models
131
+ class Interpretation,Results,SHAP,FeatureImp,ModelExplain,ROCCurve,SHAPPlots,ConfMatrix,Reports interpretation
132
+ class Advanced,Survival,Regression,Calibration advanced
133
+ ```
134
+
135
+ ### Key Features:
136
+ - **Multi-Modal Analysis**: Binary classification, survival analysis, and regression
137
+ - **Automated Pipeline**: Streamlined workflow from raw data to interpretable results
138
+ - **Explainable AI**: SHAP-based model interpretation and feature importance analysis
139
+ - **Multiple Algorithms**: Seven different machine learning models including tree-based, linear, and symbolic regression
140
+ - **Robust Validation**: Cross-validation, external validation, and comprehensive performance metrics
141
+ - **Advanced Analysis**: Optional survival analysis, regression modeling, and model calibration
142
+
143
+ ### Technical Implementation Details
144
+
145
+ #### Data Processing Pipeline
146
+ - **Missing Data Handling**: KNN imputation with adaptive neighbor selection based on dataset size
147
+ - **Outlier Detection**: Isolation Forest algorithm with contamination auto-estimation
148
+ - **Categorical Processing**: One-hot encoding with rare category merging (5% threshold default)
149
+ - **Feature Selection**: mRMR (minimum Redundancy Maximum Relevance) algorithm with mutual information
150
+ - **Data Scaling**: Robust scaling method resistant to outliers using median and IQR
151
+
152
+ #### Model Training & Evaluation
153
+ - **Cross-Validation**: 5-fold stratified cross-validation with class balance preservation
154
+ - **Hyperparameter Tuning**: RandomizedSearchCV with 10 iterations for efficient parameter optimization
155
+ - **Performance Metrics**: Comprehensive evaluation including ROC-AUC, PR-AUC, MCC, F1-score, sensitivity, specificity, and Brier score
156
+ - **Threshold Optimization**: Youden's J statistic for optimal classification threshold selection
157
+ - **Model Selection**: Best model selection based on mean cross-validation performance
158
+
159
+ #### Machine Learning Models
160
+ | Model | Key Features | Hyperparameters |
161
+ |-------|-------------|----------------|
162
+ | **Random Forest** | Bootstrap sampling, feature randomness | n_estimators (100-1000), max_depth (3-10), min_samples_split |
163
+ | **LightGBM** | Gradient boosting, GPU support, GOSS algorithm | num_leaves, min_child_samples, learning_rate, regularization |
164
+ | **CatBoost** | Categorical features, ordered encoding, symmetric trees | learning_rate, depth, l2_leaf_reg, iterations |
165
+ | **QLattice** | Symbolic regression, mathematical expressions | n_epochs, max_complexity |
166
+ | **Logistic Regression** | Linear classification, L1/L2 regularization | C, max_iter, tolerance |
167
+ | **Naive Bayes** | Probabilistic classifier, no hyperparameters | N/A |
168
+ | **Hist Gradient Boosting** | Histogram-based, fast on large datasets | max_iter, learning_rate, max_depth, regularization |
169
+
170
+ #### Interpretability & Explainability
171
+ - **SHAP Analysis**: TreeExplainer for tree-based models with local and global explanations
172
+ - **Feature Importance**: Multiple methods including permutation importance and tree-based importance
173
+ - **Visualization**: Comprehensive plots including ROC curves, SHAP summary plots, decision plots, and confusion matrices
174
+ - **Model Calibration**: Probability calibration and conformal predictions for uncertainty quantification
175
+
176
+ #### Configuration Options
177
+ The pipeline supports extensive configuration through JSON files or the Streamlit interface:
178
+ - **Data Configuration**: File paths, outcome variables, categorical features, data splitting options
179
+ - **Model Selection**: Choose from 7 algorithms, configure hyperparameter tuning
180
+ - **Feature Engineering**: Feature selection, scaling, outlier removal, rare category handling
181
+ - **Training Parameters**: Cross-validation folds, CPU/GPU allocation, performance metrics
182
+ - **Output Settings**: Result folders, visualization formats, class labels
183
+
184
+ ### MAIT Workflow - Process Flow
185
+
186
+ For a more detailed view of the decision points and process flow, here's the complete MAIT workflow as a flowchart:
187
+
188
+ ```mermaid
189
+ flowchart TD
190
+ %% Start
191
+ Start([Start MAIT Pipeline]) --> ConfigInput["Load Configuration Settings<br/>JSON config file<br/>Streamlit interface<br/>Parameter validation"]
192
+
193
+ %% Data Input
194
+ ConfigInput --> DataInput{Data Input Configuration}
195
+ DataInput -->|Raw Data| RawData[("Load Raw Medical Data<br/>CSV format<br/>Feature validation<br/>Data profiling")]
196
+ DataInput -->|With External| ExtData[("Load External Validation Data<br/>Independent test set<br/>Same feature structure<br/>Real-world validation")]
197
+ RawData --> DataPrep["Data Preparation<br/>Initial cleaning<br/>Column verification<br/>Data type inference"]
198
+ ExtData --> DataPrep
199
+
200
+ %% Data Preprocessing
201
+ DataPrep --> CleanData["Clean Data & Handle Missing Values<br/>• Drop NaN outcome rows<br/>• Replace empty strings with NaN<br/>• Data type conversion<br/>• Categorical string conversion"]
202
+ CleanData --> CheckOutliers{Remove Outliers?<br/>User configurable<br/>remove_outliers parameter}
203
+ CheckOutliers -->|Yes| OutlierRemoval["Isolation Forest Outlier Detection<br/>Isolation Forest algorithm<br/>KNN imputation preprocessing<br/>One-hot encoding<br/>Contamination estimation"]
204
+ CheckOutliers -->|No| CatProcess["Process Categorical Variables<br/>Category data type<br/>String conversion<br/>Handle mixed types"]
205
+ OutlierRemoval --> CatProcess
206
+ CatProcess --> RareCategories["Merge Rare Categories<br/>5% threshold default<br/>'Missing' category creation<br/>Frequency analysis"]
207
+ RareCategories --> ValidationCheck["Data Validation & Type Conversion<br/>Feature consistency<br/>Missing value patterns<br/>Data quality metrics"]
208
+
209
+ %% Data Splitting Decision
210
+ ValidationCheck --> SplitDecision{Data Split Strategy<br/>Discovery vs Prediction<br/>data_split parameter}
211
+ SplitDecision -->|Discovery Mode| DiscoveryMode["Use All Data for Cross-Validation<br/>5-fold stratified CV<br/>Full dataset utilization<br/>Exploratory analysis"]
212
+ SplitDecision -->|Prediction Mode| PredictionMode["Split Data 80/20<br/>Stratified split<br/>Train/test separation<br/>Hold-out validation"]
213
+
214
+ %% Prediction Mode Path
215
+ PredictionMode --> TrainTest["Training Set 80% / Test Set 20%<br/>Stratified sampling<br/>Class balance preservation<br/>Random state control"]
216
+ TrainTest --> FeatureEng["Feature Engineering Pipeline<br/>Preprocessing pipeline<br/>Feature transformations<br/>Data preparation"]
217
+ DiscoveryMode --> FeatureEng
218
+
219
+ %% Feature Engineering
220
+ FeatureEng --> FeatureSelect{Feature Selection?<br/>feat_sel parameter<br/>30 features default}
221
+ FeatureSelect -->|Yes| mRMR["Apply mRMR Feature Selection<br/>Min-redundancy Max-relevance<br/>Mutual information<br/>Feature ranking<br/>Configurable feature count"]
222
+ FeatureSelect -->|No| DataScale
223
+ mRMR --> DataScale{Scale Data?<br/>scale_data parameter<br/>Numerical features}
224
+ DataScale -->|Yes| Scaling["Apply Robust Scaling<br/>Robust scaler method<br/>Outlier resistant<br/>Median & IQR based"]
225
+ DataScale -->|No| Encoding["Categorical Encoding<br/>One-hot encoding<br/>Handle categories<br/>Binary features"]
226
+ Scaling --> Encoding
227
+ Encoding --> ModelSelection["Select Models to Train<br/>7 algorithms available<br/>User configurable<br/>Performance comparison"]
228
+
229
+ %% Model Selection
230
+ ModelSelection --> Models{Choose Models<br/>Multi-algorithm support<br/>Configurable selection}
231
+ Models --> RF["Random Forest<br/>n_estimators: 100-1000<br/>max_depth: 3-10<br/>Bootstrap sampling<br/>Class weight balancing"]
232
+ Models --> LGB["LightGBM<br/>Gradient boosting<br/>GPU support available<br/>GOSS algorithm<br/>Histogram-based"]
233
+ Models --> CB["CatBoost<br/>Categorical features<br/>Ordered encoding<br/>Symmetric trees<br/>Fast training"]
234
+ Models --> QLattice["QLattice (Symbolic)<br/>Feyn library<br/>Mathematical expressions<br/>Symbolic regression<br/>Interpretable models"]
235
+ Models --> LR["Logistic Regression<br/>Linear classification<br/>L1/L2 regularization<br/>Probability estimates<br/>Baseline model"]
236
+ Models --> NB["Naive Bayes<br/>Gaussian distribution<br/>Probabilistic classifier<br/>No hyperparameters<br/>Fast training"]
237
+ Models --> HGBC["Hist Gradient Boosting<br/>Histogram-based<br/>Fast performance<br/>Large datasets<br/>Early stopping"]
238
+
239
+ %% Model Training Process
240
+ RF --> CVProcess["Cross-Validation Process<br/>5-fold stratified<br/>Performance estimation<br/>Model comparison<br/>Sample weights"]
241
+ LGB --> CVProcess
242
+ CB --> CVProcess
243
+ QLattice --> CVProcess
244
+ LR --> CVProcess
245
+ NB --> CVProcess
246
+ HGBC --> CVProcess
247
+
248
+ %% Cross-Validation
249
+ CVProcess --> HPTuning{Hyperparameter Tuning?<br/>hp_tuning parameter<br/>10 iterations default}
250
+ HPTuning -->|Yes| RandomSearch["RandomizedSearchCV<br/>Random parameter sampling<br/>ROC-AUC optimization<br/>Grid search alternative<br/>Efficient search"]
251
+ HPTuning -->|No| ModelTrain["Train Models<br/>Fit algorithms<br/>Class weight balancing<br/>Sample weights<br/>CV training"]
252
+ RandomSearch --> ModelTrain
253
+ ModelTrain --> ThresholdOpt["Optimize Classification Threshold<br/>Youden's J statistic<br/>ROC curve analysis<br/>Optimal cutoff<br/>Sensitivity-specificity balance"]
254
+ ThresholdOpt --> PerformanceEval["Evaluate Performance Metrics<br/>Multiple metrics<br/>Comprehensive evaluation<br/>Statistical measures"]
255
+
256
+ %% Model Evaluation
257
+ PerformanceEval --> CalcMetrics["Calculate Metrics<br/>ROC-AUC & PR-AUC<br/>MCC & F1-score<br/>Sensitivity & Specificity<br/>Balanced accuracy<br/>Brier score"]
258
+ CalcMetrics --> BestModel["Select Best Model<br/>Mean CV performance<br/>ROC-AUC ranking<br/>Statistical comparison<br/>Multi-metric evaluation"]
259
+ BestModel --> TestEval{Test Set Available?<br/>Prediction mode<br/>Hold-out validation}
260
+ TestEval -->|Yes| TestPerformance["Evaluate on Test Set<br/>Hold-out validation<br/>Final performance<br/>Generalization test<br/>Unbiased evaluation"]
261
+ TestEval -->|No| ModelInterpret["Model Interpretation<br/>Explainability analysis<br/>Feature importance<br/>Decision insights"]
262
+ TestPerformance --> ModelInterpret
263
+
264
+ %% Model Interpretation
265
+ ModelInterpret --> SHAPAnalysis["SHAP Analysis<br/>TreeExplainer<br/>Feature contributions<br/>Local explanations<br/>Additive explanations"]
266
+ SHAPAnalysis --> FeatureImp["Feature Importance Analysis<br/>Permutation importance<br/>Tree-based importance<br/>Feature ranking<br/>Global importance"]
267
+ FeatureImp --> ExplainPlots["Generate Explanation Plots<br/>SHAP visualizations<br/>Feature plots<br/>Decision paths<br/>Model insights"]
268
+
269
+ %% Results Generation
270
+ ExplainPlots --> ResultsGen["Generate Results<br/>Comprehensive reports<br/>Performance summaries<br/>Model comparisons<br/>Export formats"]
271
+ ResultsGen --> ROCCurves["ROC Curves<br/>Multi-model comparison<br/>AUC visualization<br/>Threshold analysis<br/>Performance curves"]
272
+ ResultsGen --> SHAPPlots["SHAP Plots<br/>Summary plots<br/>Decision plots<br/>Feature contributions<br/>Waterfall plots"]
273
+ ResultsGen --> ConfMatrix["Confusion Matrix<br/>Classification results<br/>Error analysis<br/>Threshold evaluation<br/>TP/FP/TN/FN"]
274
+ ResultsGen --> Reports["Performance Reports<br/>Comprehensive metrics<br/>Model comparisons<br/>Export formats<br/>Summary statistics"]
275
+
276
+ %% Advanced Analysis Decision
277
+ ROCCurves --> AdvancedAnalysis{Advanced Analysis?<br/>Optional modules<br/>User configurable}
278
+ SHAPPlots --> AdvancedAnalysis
279
+ ConfMatrix --> AdvancedAnalysis
280
+ Reports --> AdvancedAnalysis
281
+
282
+ %% Advanced Analysis Options
283
+ AdvancedAnalysis -->|Survival Analysis| SurvivalAnalysis["Survival Analysis<br/>Random Survival Forest<br/>Cox regression<br/>Time-to-event modeling<br/>Kaplan-Meier curves"]
284
+ AdvancedAnalysis -->|Regression Analysis| RegressionAnalysis["Regression Analysis<br/>Random Forest Regressor<br/>Linear regression<br/>Continuous outcomes<br/>R² metrics"]
285
+ AdvancedAnalysis -->|Model Calibration| Calibration["Model Calibration<br/>Probability calibration<br/>Conformal predictions<br/>Uncertainty quantification<br/>Reliability curves"]
286
+ AdvancedAnalysis -->|No| EndPipeline
287
+
288
+ %% Advanced Analysis Outputs
289
+ SurvivalAnalysis --> AdvancedResults["Advanced Analysis Results<br/>Specialized metrics<br/>Advanced visualizations<br/>Domain-specific insights<br/>Extended reports"]
290
+ RegressionAnalysis --> AdvancedResults
291
+ Calibration --> AdvancedResults
292
+ AdvancedResults --> EndPipeline["End Pipeline<br/>Analysis complete<br/>Results exported<br/>Ready for deployment<br/>All outputs saved"]
293
+
294
+ %% External Validation Path
295
+ TestPerformance --> ExtValidation{External Validation?<br/>Independent dataset<br/>Real-world testing}
296
+ ExtValidation -->|Yes| ExtVal["Apply Model to External Data<br/>Independent validation<br/>Model generalization<br/>Real-world performance<br/>Deployment readiness"]
297
+ ExtValidation -->|No| ModelInterpret
298
+ ExtVal --> ExtResults["External Validation Results<br/>Performance metrics<br/>Generalization assessment<br/>Deployment confidence<br/>Model robustness"]
299
+ ExtResults --> ModelInterpret
300
+
301
+ %% Styling
302
+ classDef startEnd fill:#c8e6c9,stroke:#2e7d32,stroke-width:3px,color:#1b5e20
303
+ classDef process fill:#bbdefb,stroke:#1565c0,stroke-width:2px,color:#0d47a1
304
+ classDef decision fill:#ffe0b2,stroke:#ef6c00,stroke-width:2px,color:#bf360c
305
+ classDef data fill:#e1bee7,stroke:#7b1fa2,stroke-width:2px,color:#4a148c
306
+ classDef model fill:#a5d6a7,stroke:#388e3c,stroke-width:2px,color:#1b5e20
307
+ classDef results fill:#f8bbd9,stroke:#c2185b,stroke-width:2px,color:#880e4f
308
+ classDef advanced fill:#dcedc8,stroke:#689f38,stroke-width:2px,color:#33691e
309
+
310
+ class Start,EndPipeline startEnd
311
+ class ConfigInput,DataPrep,CleanData,CatProcess,RareCategories,ValidationCheck,FeatureEng,Encoding,CVProcess,ModelTrain,ThresholdOpt,PerformanceEval,CalcMetrics,BestModel,TestPerformance,ModelInterpret,SHAPAnalysis,FeatureImp,ExplainPlots,ResultsGen process
312
+ class DataInput,CheckOutliers,SplitDecision,FeatureSelect,DataScale,Models,HPTuning,TestEval,AdvancedAnalysis,ExtValidation decision
313
+ class RawData,ExtData,TrainTest,DiscoveryMode,PredictionMode data
314
+ class RF,LGB,CB,QLattice,LR,NB,HGBC,OutlierRemoval,mRMR,Scaling,RandomSearch model
315
+ class ROCCurves,SHAPPlots,ConfMatrix,Reports,ExtVal,ExtResults results
316
+ class SurvivalAnalysis,RegressionAnalysis,Calibration,AdvancedResults advanced
317
+ ```
318
+
319
+ This flowchart illustrates the complete decision-making process and shows how MAIT adapts to different analysis needs:
320
+
321
+ #### Key Decision Points:
322
+ - **Discovery vs. Prediction Mode**: Choose between exploration (cross-validation only) or prediction (train/test split)
323
+ - **Data Preprocessing Options**: Outlier removal, feature selection, data scaling
324
+ - **Model Selection**: Choose from 7 different machine learning algorithms
325
+ - **Advanced Analysis**: Optional survival analysis, regression modeling, or calibration
326
+ - **External Validation**: Apply trained models to independent datasets
327
+
328
+ ## How to Use
329
+
330
+ ### Step 1: Clone the Repository
331
+ First, clone this repository to your local machine using the following command:
332
+
333
+ ```bash
334
+ git clone https://github.com/PERSIMUNE/MAIT.git
335
+ cd MAIT
336
+ ```
337
+
338
+ ### Step 2: Install Conda and Setup the Environment
339
+
340
+ There are different ways to create an environment to use MAIT.
341
+ Ensure that you have [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html) installed.
342
+
343
+ Create a new conda environment using the provided `environment.yml` file:
344
+
345
+ ```bash
346
+ conda env create -f environment.yml
347
+ conda activate mait_py3_10_9
348
+ ```
349
+ Or if you prefer to use `pip` to install the required packages, you can create a conda environment and install the dependencies using `pip`:
350
+
351
+ ```bash
352
+ conda create --name mait_py3_10_9 python=3.10.9
353
+ conda activate mait_py3_10_9
354
+ pip install -r requirements.txt
355
+ ```
356
+ Also you can try an updated Python version, and also use mlflow (experimental).
357
+
358
+ ```bash
359
+ conda create -n mait_env python=3.12 \
360
+ numpy pandas scikit-learn scipy matplotlib seaborn joblib lightgbm catboost ipykernel \
361
+ imbalanced-learn mlflow shap scikit-survival -c conda-forge
362
+ conda activate mait_env
363
+ pip install feyn mrmr_selection survshap openpyxl
364
+ conda install protobuf=3.20.* -c conda-forge
365
+ pip install --upgrade mlflow
366
+ ```
367
+ ### Step 3: Using Docker
368
+ A Docker image is available for this pipeline. You can build and run the Docker container using the `Dockerfile` provided in the repository. Here are the steps:
369
+
370
+ 1. Build the Docker image (or use the one that is already available: https://hub.docker.com/r/danishdyna/mait_30092024gpu):
371
+
372
+ ```bash
373
+ docker build -t mait_py3_10_9:latest .
374
+ ```
375
+
376
+ 2. Run the Docker container where your MAIT pipeline files are located:
377
+
378
+ ```bash
379
+ docker run -it --rm -p 8888:8888 mait_py3_10_9:latest
380
+ ```
381
+ or do this
382
+ ```bash
383
+ docker run --gpus all -p 8888:8888 -v "$(pwd):/app" -it danishdyna/mait_30092024gpu /bin/bash
384
+ ```
385
+
386
+ Inside the container, you should activate the conda environment using `activate the conda mait_py3_10_9_30092024gpu` then run this to initiate Jupyter Notebook: `jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root`.
387
+
388
+ You can also refer to the `environment.yml` file to understand the dependencies and create your Docker environment. If you run the Docker container on an HPC server or a remote computer you can use http://your_HPC_server_address:8888/ to get access to the Jupyter Notebook to run MAIT.
389
+
390
+
391
+ ## Quick Start with Streamlit Configuration Interface
392
+
393
+ For new users who want to get started quickly without diving into Jupyter notebooks, MAIT includes a user-friendly **Streamlit web interface** for configuration:
394
+
395
+ ### Try Online (No Installation Required)
396
+ **Access the live app at: https://maitconfig.streamlit.app/**
397
+
398
+ ### Launch Locally
399
+ ```bash
400
+ cd MAIT
401
+ ./run_streamlit.sh
402
+ ```
403
+
404
+ Or manually:
405
+ ```bash
406
+ streamlit run streamlit_app.py
407
+ ```
408
+
409
+ ### Features
410
+ - **Interactive Configuration**: Set up your machine learning pipeline through an intuitive web interface
411
+ - **Demo Data Included**: Test MAIT immediately with built-in medical dataset
412
+ - **Ready-to-Run Scripts**: Generate complete Python scripts with your configurations pre-filled
413
+ - **No Manual Editing**: Generated scripts are ready to execute without any code modifications
414
+
415
+ ### Quick Demo
416
+ 1. Launch the Streamlit app
417
+ 2. Click "Use Demo Data" in the Data Configuration section
418
+ 3. Configure your preferred models and parameters
419
+ 4. Generate and download your customized MAIT pipeline script
420
+
421
+ This interface is perfect for users who want to explore MAIT's capabilities before diving into the detailed Jupyter tutorial notebooks.
422
+
423
+ ## Tutorials
424
+ The repository includes several Jupyter Notebooks that serve as tutorials. These notebooks cover various aspects of the pipeline and demonstrate how to use different components effectively. Below you can find a list of available tutorials:
425
+
426
+ 1. [Tutorial 1: Prediction of antimicrobial resistance for Azithromycin](https://github.com/PERSIMUNE/MAIT/blob/main/Tutorials/MAIT_Tutorial_Azithromycin_pub.html)
427
+ 2. [Tutorial 2: Prediction of antimicrobial resistance for Ciprofloxacin](https://github.com/PERSIMUNE/MAIT/blob/main/Tutorials/MAIT_Tutorial_Ciprofloxacin_pub.html)
428
+ 3. [Tutorial 3: Prediction of Dementia](https://github.com/PERSIMUNE/MAIT/blob/main/Tutorials/MAIT_Tutorial_Dementia_pub.html)
429
+ 4. [Tutorial 4: Prediction of Breast Cancer](https://github.com/PERSIMUNE/MAIT/blob/main/Tutorials/MAIT_Tutorial_BreastCancer_pub.html)
430
+
431
+ ## How to Cite
432
+ Here's how to cite MAIT:
433
+
434
+ ### **APA Style**
435
+ Zargari Marandi, R., Frahm, A. S., Lundgren, J., Murray, D. D., & Milojevic, M. (2025) "Medical artificial intelligence toolbox (MAIT): An explainable machine learning framework for binary classification, survival modelling, and regression analyses." arXiv preprint arXiv:2501.04547.
436
+
437
+ ### **BibTeX**
438
+ ```bibtex
439
+ @article{zargari2025mait,
440
+ title={Medical artificial intelligence toolbox (MAIT): An explainable machine learning framework for binary classification, survival modelling, and regression analyses},
441
+ author={Zargari Marandi, Ramtin and Frahm, Anne Svane and Lundgren, Jens and Murray, Daniel Dawson and Milojevic, Maja},
442
+ journal={arXiv preprint arXiv:2501.04547},
443
+ year={2025},
444
+ url={https://arxiv.org/abs/2501.04547}
445
+ }
446
+ ```
447
+
448
+ ## License
449
+ This pipeline is free to use for research purposes. Please ensure you follow the licenses of the individual packages used within this pipeline. For more details, refer to the `LICENSE` file in the repository.
450
+
451
+ ---
452
+
453
+ We hope you find this pipeline useful for your machine learning projects. If you encounter any issues or have any questions, feel free to open an issue on GitHub.
454
+ ![Alt Text](https://github.com/PERSIMUNE/MAIT/blob/main/MAIT_results_examples.gif)