-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
225 lines (195 loc) · 7.48 KB
/
Copy pathmain.py
File metadata and controls
225 lines (195 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import argparse
import contextlib
import io
from pathlib import Path
import pandas as pd
from src.dataloader import DataLoader
from src.predictor import Predictor, ShapExplanationResult
from src.preprocessor import Preprocessor
from src.trainer import Trainer
def build_parser() -> argparse.ArgumentParser:
"""Create the command-line interface for the regression pipeline."""
parser = argparse.ArgumentParser(
description="Train and evaluate a salary regression model."
)
parser.add_argument("--data", required=True, help="Path to a CSV or Excel dataset.")
parser.add_argument(
"--model", choices=("linear", "lasso"), default="linear", help="Model to train."
)
parser.add_argument("--alpha", type=float, default=1.0, help="Lasso alpha value.")
parser.add_argument(
"--scaling",
choices=("standard", "minmax", "none"),
default="standard",
help="Feature scaling strategy.",
)
parser.add_argument("--test-size", type=float, default=0.2, help="Test-set proportion.")
parser.add_argument(
"--random-state", type=int, default=42, help="Random seed for the train/test split."
)
parser.add_argument(
"--model-output", help="Path for the saved model artifact (.pkl)."
)
parser.add_argument(
"--explain",
action="store_true",
help="Print SHAP feature contributions for one prediction.",
)
parser.add_argument(
"--exam-score",
type=float,
help="Exam score for a new salary prediction.",
)
parser.add_argument(
"--years-exp",
type=float,
help="Years of experience for a new salary prediction.",
)
return parser
def default_model_output(model_name: str) -> Path:
"""Return the standard artifact path for a model type."""
filename = "linear_regression.pkl" if model_name == "linear" else "lasso_regression.pkl"
return Path("models") / filename
def has_prediction_input(args: argparse.Namespace) -> bool:
"""Return whether the CLI includes a complete manual prediction input."""
provided_values = [args.exam_score is not None, args.years_exp is not None]
if any(provided_values) and not all(provided_values):
raise ValueError("--exam-score and --years-exp must be provided together.")
if args.explain and not all(provided_values):
raise ValueError(
"--explain requires --exam-score and --years-exp so it can explain "
"one specific prediction."
)
return all(provided_values)
def build_prediction_features(
*,
exam_score: float,
years_exp: float,
preprocessor: Preprocessor,
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Build raw and model-ready feature frames for one manual prediction."""
raw_features = pd.DataFrame(
[{"exam_score": exam_score, "years_exp": years_exp}],
columns=preprocessor.feature_columns,
)
if preprocessor.scaler is None:
return raw_features, raw_features
model_features = pd.DataFrame(
preprocessor.scaler.transform(raw_features),
columns=preprocessor.feature_columns,
)
return raw_features, model_features
def print_section(title: str) -> None:
"""Print a readable CLI section header."""
line = "=" * 72
print()
print(line)
print(title)
print(line)
def print_model_report(
*,
model_name: str,
scaling: str,
model: object,
feature_columns: list[str],
train_rows: int,
test_rows: int,
metrics: dict[str, float],
saved_path: Path,
manual_prediction: float | None = None,
exam_score: float | None = None,
years_exp: float | None = None,
) -> None:
"""Print the important model results before any optional explanation."""
print_section("Model Summary")
print(f"Model type : {model_name}")
print(f"Scaling : {scaling}")
print(f"Training rows : {train_rows}")
print(f"Test rows : {test_rows}")
print(f"RMSE : {metrics['rmse']:,.2f}")
print(f"R2 : {metrics['r2']:.4f}")
if hasattr(model, "coef_"):
print_section("Learned Parameters")
print("Coefficients:")
for feature, coefficient in zip(feature_columns, model.coef_):
print(f" {feature:<12} {coefficient:>12,.4f}")
if hasattr(model, "intercept_"):
print(f"Intercept : {model.intercept_:,.4f}")
if manual_prediction is not None:
print_section("Manual Prediction")
print(f"Exam score : {exam_score:,.2f}")
print(f"Years experience: {years_exp:,.2f}")
print(f"Predicted salary: {manual_prediction:,.2f}")
print_section("Saved Artifact")
print(f"Path : {saved_path}")
def print_shap_explanation(explanation: ShapExplanationResult) -> None:
"""Print SHAP output as the final optional section."""
print_section("SHAP Explanation")
print("Feature contributions for the supplied prediction:")
print(explanation.feature_contributions.to_string(index=False))
def main() -> None:
parser = build_parser()
args = parser.parse_args()
try:
manual_prediction = has_prediction_input(args)
data = DataLoader(args.data).load_data()
preprocessor = Preprocessor(
scaling=args.scaling,
test_size=args.test_size,
random_state=args.random_state,
)
X_train, X_test, y_train, y_test = preprocessor.preprocess(data)
trainer = Trainer(model_name=args.model, alpha=args.alpha)
model = trainer.train(X_train, y_train)
predictor = Predictor(model)
predictions = predictor.predict(X_test)
with contextlib.redirect_stdout(io.StringIO()):
metrics = predictor.evaluate(y_test, predictions)
manual_predictions = None
explanation = None
if manual_prediction:
raw_features, model_features = build_prediction_features(
exam_score=args.exam_score,
years_exp=args.years_exp,
preprocessor=preprocessor,
)
manual_predictions = predictor.predict(model_features)
if args.explain:
explanation = predictor.explain(
model_features,
background_data=X_train,
display_features=raw_features,
)
output_path = (
Path(args.model_output)
if args.model_output
else default_model_output(args.model)
)
with contextlib.redirect_stdout(io.StringIO()):
saved_path = trainer.save_artifact(
output_path,
scaler=preprocessor.scaler,
feature_columns=preprocessor.feature_columns,
target_column=preprocessor.target_column,
)
print_model_report(
model_name=args.model,
scaling=args.scaling,
model=model,
feature_columns=preprocessor.feature_columns,
train_rows=len(X_train),
test_rows=len(X_test),
metrics=metrics,
saved_path=saved_path,
manual_prediction=(
float(manual_predictions[0]) if manual_predictions is not None else None
),
exam_score=args.exam_score,
years_exp=args.years_exp,
)
if explanation is not None:
print_shap_explanation(explanation)
except (FileNotFoundError, ValueError) as error:
parser.error(str(error))
if __name__ == "__main__":
main()