mljunior 0.1.0__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.
mljunior-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Gopesh
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: mljunior
3
+ Version: 0.1.0
4
+ Summary: ML JUNIOR — automatically trains, tunes, evaluates, and saves machine learning models.
5
+ Author: Gopesh
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: pandas>=2.0
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: scikit-learn>=1.3
13
+ Requires-Dist: joblib>=1.3
14
+ Requires-Dist: openpyxl>=3.1
15
+ Requires-Dist: pyarrow>=14.0
16
+ Dynamic: license-file
17
+
18
+ # ML JUNIOR
19
+
20
+ An agent that does the model-selection and hyperparameter-tuning grind for
21
+ you: point it at a dataset, and it reads it, figures out the problem type,
22
+ suggests and applies preprocessing, trains and tunes several algorithms,
23
+ saves the best one, and writes an experiment report — announcing every step
24
+ as it happens.
25
+
26
+ ```
27
+ __ __ _ _ _ _ _ _ ___ ___ ____
28
+ | \/ | | | | | | | \ | |_ _/ _ \| _ \
29
+ | |\/| | | | | | | | \| || | | | | |_) |
30
+ | | | | |___ | | |_| | |\ || | |_| | _ <
31
+ |_| |_|_____| |_|\___/|_| \_|___\___/|_| \_\
32
+
33
+ your ML training + tuning agent
34
+ ```
35
+
36
+ ## Install (one time)
37
+
38
+ ```bash
39
+ unzip mljunior.zip
40
+ cd ml-junior
41
+ pip install -e .
42
+ ```
43
+
44
+ `mljunior` is now a system command, usable from any folder — no `cd`-ing
45
+ back into this repo required.
46
+
47
+ ## Use it
48
+
49
+ ```bash
50
+ mljunior --demo # try it on a built-in dataset
51
+ mljunior --data datasets/your_file.csv --target y # your own dataset
52
+ mljunior # no flags — it asks interactively
53
+ mljunior --data data.csv --target y --quick # faster: fewer CV folds/tuning iters
54
+ ```
55
+
56
+ Supports CSV, Excel (`.xlsx`), JSON, and Parquet. CSVs are read with automatic
57
+ encoding detection (handles Excel exports that aren't UTF-8).
58
+
59
+ ## What it does — step by step
60
+
61
+ 1. **Reads and cleans the dataset** — any of the formats above, profiles rows/columns/missingness/class balance
62
+ 2. **Identifies the problem type** — classification or regression, from the target column
63
+ 3. **Suggests + applies preprocessing** — imputation, one-hot/label encoding, scaling, class-imbalance handling — all explained in plain English before it's applied
64
+ 4. **Trains multiple algorithms** — cross-validated quick screen with default hyperparameters
65
+ 5. **Tunes hyperparameters** — `RandomizedSearchCV` on the top performers
66
+ 6. **Compares metrics** — a final leaderboard (accuracy/F1 for classification — F1 automatically when classes are imbalanced; R2 for regression)
67
+ 7. **Saves the best model** — `mljunior_output/best_model.joblib`, a full sklearn Pipeline (preprocessing + model together)
68
+ 8. **Generates an experiment report** — `mljunior_output/experiment_report.md`, documenting every step above
69
+
70
+ ##Seeing the features
71
+
72
+ ```python
73
+ import joblib
74
+
75
+ saved = joblib.load("mljunior_output/best_model.joblib")
76
+ pipeline = saved["pipeline"]
77
+
78
+ print(list(pipeline.feature_names_in_))
79
+ ```
80
+ ## Using the saved model later
81
+
82
+ ```python
83
+ import joblib
84
+
85
+ saved = joblib.load('mljunior_output/best_model.joblib')
86
+ pipeline = saved['pipeline']
87
+ label_encoder = saved['label_encoder'] # None for regression tasks
88
+
89
+ predictions = pipeline.predict(new_data_df) # same feature columns as training data
90
+ if label_encoder is not None:
91
+ predictions = label_encoder.inverse_transform(predictions) # back to original labels
92
+ ```
93
+
94
+ ## Adding your own dataset
95
+
96
+ Drop a CSV/Excel/JSON/Parquet file into the `datasets/` folder (or anywhere
97
+ else — it's just a suggested spot):
98
+
99
+ ```bash
100
+ mljunior --data datasets/my_data.csv --target my_target_column
101
+ ```
102
+
103
+ ## Uninstall
104
+
105
+ ```bash
106
+ pip uninstall mljunior
107
+ ```
@@ -0,0 +1,90 @@
1
+ # ML JUNIOR
2
+
3
+ An agent that does the model-selection and hyperparameter-tuning grind for
4
+ you: point it at a dataset, and it reads it, figures out the problem type,
5
+ suggests and applies preprocessing, trains and tunes several algorithms,
6
+ saves the best one, and writes an experiment report — announcing every step
7
+ as it happens.
8
+
9
+ ```
10
+ __ __ _ _ _ _ _ _ ___ ___ ____
11
+ | \/ | | | | | | | \ | |_ _/ _ \| _ \
12
+ | |\/| | | | | | | | \| || | | | | |_) |
13
+ | | | | |___ | | |_| | |\ || | |_| | _ <
14
+ |_| |_|_____| |_|\___/|_| \_|___\___/|_| \_\
15
+
16
+ your ML training + tuning agent
17
+ ```
18
+
19
+ ## Install (one time)
20
+
21
+ ```bash
22
+ unzip mljunior.zip
23
+ cd ml-junior
24
+ pip install -e .
25
+ ```
26
+
27
+ `mljunior` is now a system command, usable from any folder — no `cd`-ing
28
+ back into this repo required.
29
+
30
+ ## Use it
31
+
32
+ ```bash
33
+ mljunior --demo # try it on a built-in dataset
34
+ mljunior --data datasets/your_file.csv --target y # your own dataset
35
+ mljunior # no flags — it asks interactively
36
+ mljunior --data data.csv --target y --quick # faster: fewer CV folds/tuning iters
37
+ ```
38
+
39
+ Supports CSV, Excel (`.xlsx`), JSON, and Parquet. CSVs are read with automatic
40
+ encoding detection (handles Excel exports that aren't UTF-8).
41
+
42
+ ## What it does — step by step
43
+
44
+ 1. **Reads and cleans the dataset** — any of the formats above, profiles rows/columns/missingness/class balance
45
+ 2. **Identifies the problem type** — classification or regression, from the target column
46
+ 3. **Suggests + applies preprocessing** — imputation, one-hot/label encoding, scaling, class-imbalance handling — all explained in plain English before it's applied
47
+ 4. **Trains multiple algorithms** — cross-validated quick screen with default hyperparameters
48
+ 5. **Tunes hyperparameters** — `RandomizedSearchCV` on the top performers
49
+ 6. **Compares metrics** — a final leaderboard (accuracy/F1 for classification — F1 automatically when classes are imbalanced; R2 for regression)
50
+ 7. **Saves the best model** — `mljunior_output/best_model.joblib`, a full sklearn Pipeline (preprocessing + model together)
51
+ 8. **Generates an experiment report** — `mljunior_output/experiment_report.md`, documenting every step above
52
+
53
+ ##Seeing the features
54
+
55
+ ```python
56
+ import joblib
57
+
58
+ saved = joblib.load("mljunior_output/best_model.joblib")
59
+ pipeline = saved["pipeline"]
60
+
61
+ print(list(pipeline.feature_names_in_))
62
+ ```
63
+ ## Using the saved model later
64
+
65
+ ```python
66
+ import joblib
67
+
68
+ saved = joblib.load('mljunior_output/best_model.joblib')
69
+ pipeline = saved['pipeline']
70
+ label_encoder = saved['label_encoder'] # None for regression tasks
71
+
72
+ predictions = pipeline.predict(new_data_df) # same feature columns as training data
73
+ if label_encoder is not None:
74
+ predictions = label_encoder.inverse_transform(predictions) # back to original labels
75
+ ```
76
+
77
+ ## Adding your own dataset
78
+
79
+ Drop a CSV/Excel/JSON/Parquet file into the `datasets/` folder (or anywhere
80
+ else — it's just a suggested spot):
81
+
82
+ ```bash
83
+ mljunior --data datasets/my_data.csv --target my_target_column
84
+ ```
85
+
86
+ ## Uninstall
87
+
88
+ ```bash
89
+ pip uninstall mljunior
90
+ ```
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ML JUNIOR — an agent that does the hyperparameter-tuning grind for you.
4
+
5
+ Reads a dataset, cleans it, figures out the problem type, suggests
6
+ preprocessing, trains and tunes several algorithms, evaluates the winner on
7
+ a genuine held-out test set, saves the best model, and writes an experiment
8
+ report. Run `mljunior --demo` to see it end to end.
9
+ """
10
+
11
+ import argparse
12
+ import os
13
+ import sys
14
+
15
+ import joblib
16
+ import pandas as pd
17
+ from sklearn.base import clone
18
+ from sklearn.model_selection import train_test_split
19
+
20
+ from mljunior.data import load_data, load_demo_data, profile_dataset, print_profile
21
+ from mljunior.preprocessing import (
22
+ detect_task_type, clean_dataset, suggest_preprocessing,
23
+ build_pipeline_preprocessor, encode_target,
24
+ )
25
+ from mljunior.modeling import (
26
+ get_model_catalog, quick_screen, tune_model, scoring_metric, evaluate_on_holdout,
27
+ )
28
+ from mljunior.report import generate_report
29
+
30
+ BANNER = r"""
31
+ __ __ _ _ _ _ _ _ ___ ___ ____
32
+ | \/ | | | | | | | \ | |_ _/ _ \| _ \
33
+ | |\/| | | | | | | | \| || | | | | |_) |
34
+ | | | | |___ | | |_| | |\ || | |_| | _ <
35
+ |_| |_|_____| |_|\___/|_| \_|___\___/|_| \_\
36
+
37
+ your ML training + tuning agent
38
+ """
39
+
40
+ MIN_ROWS_FOR_HOLDOUT = 20
41
+
42
+
43
+ def step(n, title):
44
+ print(f"\n[Step {n}] {title}")
45
+ print("-" * 50)
46
+
47
+
48
+ def main():
49
+ print(BANNER)
50
+ parser = argparse.ArgumentParser(description="ML JUNIOR: clean data, tune models, save the best one, write a report.")
51
+ parser.add_argument("--data", type=str, help="Path to dataset (csv, xlsx, json, or parquet)")
52
+ parser.add_argument("--target", type=str, help="Target/label column name")
53
+ parser.add_argument("--demo", action="store_true", help="Run on a built-in demo dataset")
54
+ parser.add_argument("--out-dir", type=str, default="mljunior_output", help="Output directory for model + report")
55
+ parser.add_argument("--quick", action="store_true", help="Faster run: fewer CV folds and tuning iterations")
56
+ args = parser.parse_args()
57
+
58
+ # --- Step 1: Read the dataset ---
59
+ step(1, "Reading the dataset")
60
+ if args.demo:
61
+ df, target = load_demo_data()
62
+ print("Using built-in demo dataset (breast cancer classification)")
63
+ elif args.data and args.target:
64
+ df = load_data(args.data)
65
+ target = args.target
66
+ elif args.data and not args.target:
67
+ df = load_data(args.data)
68
+ print(f"Columns found: {list(df.columns)}")
69
+ target = input("Which column should I predict? ").strip()
70
+ else:
71
+ print("No dataset given.")
72
+ path = input("Dataset path (or Enter for demo): ").strip()
73
+ if not path:
74
+ df, target = load_demo_data()
75
+ else:
76
+ df = load_data(path)
77
+ print(f"Columns found: {list(df.columns)}")
78
+ target = input("Which column should I predict? ").strip()
79
+
80
+ if target not in df.columns:
81
+ print(f"Error: target column '{target}' not found. Available: {list(df.columns)}")
82
+ sys.exit(1)
83
+
84
+ profile = profile_dataset(df, target)
85
+ print_profile(profile)
86
+
87
+ # --- Step 2: Identify classification/regression ---
88
+ step(2, "Identifying the problem type")
89
+ task_type = detect_task_type(df[target])
90
+ print(f"Detected: {task_type}")
91
+
92
+ # --- Step 3: Clean the data, then suggest + apply preprocessing ---
93
+ step(3, "Cleaning the dataset")
94
+ df, cleanup_notes = clean_dataset(df, target)
95
+ if cleanup_notes:
96
+ for note in cleanup_notes:
97
+ print(f" - {note}")
98
+ else:
99
+ print(" - Dataset was already clean, nothing to do")
100
+
101
+ y_raw = df[target]
102
+ X = df.drop(columns=[target])
103
+
104
+ print("\nPreprocessing plan:")
105
+ suggestions = suggest_preprocessing(X, y_raw, task_type)
106
+ for s in suggestions:
107
+ print(f" - {s}")
108
+ if not suggestions:
109
+ print(" - No special preprocessing needed")
110
+
111
+ preprocessor, id_cols = build_pipeline_preprocessor(X)
112
+ if id_cols:
113
+ X = X.drop(columns=id_cols)
114
+ y, label_encoder = encode_target(y_raw, task_type)
115
+
116
+ imbalanced = False
117
+ if task_type == "classification":
118
+ counts = y_raw.value_counts(normalize=True)
119
+ imbalanced = (counts.max() / max(counts.min(), 1e-9)) > 3
120
+
121
+ # --- Held-out split: tuning never sees this data ---
122
+ skip_holdout = len(X) < MIN_ROWS_FOR_HOLDOUT
123
+ if task_type == "classification" and not skip_holdout:
124
+ class_counts = pd.Series(y).value_counts()
125
+ if class_counts.min() < 2:
126
+ skip_holdout = True
127
+
128
+ if skip_holdout:
129
+ print(f"\n(Dataset too small for a reliable held-out test set — reporting "
130
+ f"cross-validated scores instead of true holdout performance)")
131
+ X_train, y_train = X, y
132
+ X_test, y_test = None, None
133
+ else:
134
+ try:
135
+ X_train, X_test, y_train, y_test = train_test_split(
136
+ X, y, test_size=0.2, random_state=42,
137
+ stratify=y if task_type == "classification" else None,
138
+ )
139
+ except ValueError:
140
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
141
+
142
+ # --- Step 4-5: Train multiple models, quick cross-val screen (on train only) ---
143
+ step(4, "Training candidate models (quick cross-validated screen)")
144
+ cv_folds = 3
145
+ catalog = get_model_catalog(task_type, class_weight_balanced=imbalanced)
146
+ screen_scores = quick_screen(preprocessor, catalog, X_train, y_train, task_type, cv=cv_folds, imbalanced=imbalanced)
147
+ metric_name = scoring_metric(task_type, imbalanced)
148
+ if imbalanced:
149
+ print(f" (using {metric_name} instead of accuracy since classes are imbalanced)")
150
+ for name, score in sorted(screen_scores.items(), key=lambda kv: (kv[1] is None, -(kv[1] or 0))):
151
+ print(f" {name:<22} {metric_name}={score}")
152
+
153
+ ranked = sorted(
154
+ [(n, s) for n, s in screen_scores.items() if s is not None],
155
+ key=lambda kv: -kv[1],
156
+ )
157
+ if not ranked:
158
+ print("\nError: every candidate model failed during cross-validation.")
159
+ print("This usually means the dataset is too small or too imbalanced for the "
160
+ "requested number of CV folds (e.g. fewer than 2 samples in some class).")
161
+ print("Try a larger dataset, or a target column with more examples per class.")
162
+ sys.exit(1)
163
+
164
+ n_iter = 4 if args.quick else 8
165
+ shortlist = [name for name, _ in ranked[: 4 if not args.quick else 2]]
166
+
167
+ # --- Step 5: Hyperparameter tuning (on train only) ---
168
+ step(5, f"Tuning hyperparameters for top {len(shortlist)} models")
169
+ tuned_results = []
170
+ fitted_pipelines = {}
171
+ for name in shortlist:
172
+ estimator, param_dist = catalog[name]
173
+ print(f" Tuning {name}...")
174
+ pipe, best_params, cv_score, std = tune_model(
175
+ preprocessor, estimator, param_dist, X_train, y_train, task_type,
176
+ n_iter=n_iter, cv=cv_folds, imbalanced=imbalanced,
177
+ )
178
+ row = {"name": name, "cv_score": cv_score, "std": std, "params": best_params}
179
+
180
+ if not skip_holdout:
181
+ holdout_metrics = evaluate_on_holdout(pipe, X_test, y_test, task_type)
182
+ primary_key = "F1" if (task_type == "classification" and imbalanced) else (
183
+ "Accuracy" if task_type == "classification" else "R2"
184
+ )
185
+ row["holdout_metrics"] = holdout_metrics
186
+ row["rank_score"] = holdout_metrics[primary_key]
187
+ else:
188
+ row["holdout_metrics"] = None
189
+ row["rank_score"] = cv_score
190
+
191
+ tuned_results.append(row)
192
+ fitted_pipelines[name] = pipe
193
+
194
+ tuned_results.sort(key=lambda r: -r["rank_score"])
195
+
196
+ # --- Step 6: Compare metrics ---
197
+ step(6, "Final leaderboard")
198
+ if skip_holdout:
199
+ print(f"{'Rank':<5}{'Model':<22}{'CV ' + metric_name:<16}")
200
+ for i, row in enumerate(tuned_results, 1):
201
+ print(f"{i:<5}{row['name']:<22}{row['cv_score']:<16}")
202
+ else:
203
+ print("(Scores below are on a held-out test set the models never trained or tuned on)")
204
+ header_metrics = list(tuned_results[0]["holdout_metrics"].keys())
205
+ print(f"{'Rank':<5}{'Model':<22}" + "".join(f"{m:<12}" for m in header_metrics) + f"{'CV ' + metric_name:<14}")
206
+ for i, row in enumerate(tuned_results, 1):
207
+ metric_str = "".join(f"{row['holdout_metrics'][m]:<12}" for m in header_metrics)
208
+ print(f"{i:<5}{row['name']:<22}{metric_str}{row['cv_score']:<14}")
209
+
210
+ best = tuned_results[0]
211
+ best_name = best["name"]
212
+ best_pipeline = fitted_pipelines[best_name]
213
+ print(f"\nBest model: {best_name} ({'holdout' if not skip_holdout else 'CV'} {metric_name}={best['rank_score']})")
214
+
215
+ # --- Step 7: Save best model (refit on ALL data for the production artifact) ---
216
+ step(7, "Saving the best model")
217
+ final_pipeline = clone(best_pipeline)
218
+ final_pipeline.fit(X, y) # refit on train+test combined, now that we've honestly measured generalization
219
+
220
+ os.makedirs(args.out_dir, exist_ok=True)
221
+ model_path = os.path.join(args.out_dir, "best_model.joblib")
222
+ joblib.dump({
223
+ "pipeline": final_pipeline,
224
+ "label_encoder": label_encoder,
225
+ "target": target,
226
+ "task_type": task_type,
227
+ "feature_columns": list(X.columns),
228
+ "dropped_id_columns": id_cols,
229
+ }, model_path)
230
+ print(f"Saved to: {model_path}")
231
+ print("(Refit on the full cleaned dataset for production use, after honestly measuring "
232
+ "generalization on the held-out split above)")
233
+
234
+ # --- Step 8: Generate experiment report ---
235
+ step(8, "Writing experiment report")
236
+ report_path = os.path.join(args.out_dir, "experiment_report.md")
237
+ generate_report(
238
+ profile=profile,
239
+ cleanup_notes=cleanup_notes,
240
+ task_type=task_type,
241
+ suggestions=suggestions,
242
+ screen_scores=screen_scores,
243
+ tuned_results=tuned_results,
244
+ skip_holdout=skip_holdout,
245
+ best_name=best_name,
246
+ best_params=best["params"],
247
+ model_path=model_path,
248
+ out_path=report_path,
249
+ )
250
+ print(f"Saved to: {report_path}")
251
+
252
+ print("\nDone. ML JUNIOR finished its shift.")
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main()