statstudio 0.1.0__py3-none-any.whl

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.
Files changed (110) hide show
  1. statstudio/__init__.py +9 -0
  2. statstudio/__main__.py +3 -0
  3. statstudio/app.py +83 -0
  4. statstudio/cli.py +116 -0
  5. statstudio/core/__init__.py +3 -0
  6. statstudio/core/archive.py +27 -0
  7. statstudio/core/commands.py +67 -0
  8. statstudio/core/formula_catalog.py +74 -0
  9. statstudio/core/formulas.py +605 -0
  10. statstudio/core/joins.py +123 -0
  11. statstudio/core/project.py +358 -0
  12. statstudio/core/runtime.py +321 -0
  13. statstudio/core/scripting.py +594 -0
  14. statstudio/core/table.py +796 -0
  15. statstudio/core/transform.py +450 -0
  16. statstudio/feature_help.py +595 -0
  17. statstudio/io/__init__.py +3 -0
  18. statstudio/io/docx.py +201 -0
  19. statstudio/io/export.py +99 -0
  20. statstudio/io/file_import.py +199 -0
  21. statstudio/io/odbc.py +334 -0
  22. statstudio/io/sample_data.py +164 -0
  23. statstudio/io/table_io.py +118 -0
  24. statstudio/plots/__init__.py +19 -0
  25. statstudio/plots/advanced.py +651 -0
  26. statstudio/plots/basic.py +957 -0
  27. statstudio/plots/bayesian_plots.py +94 -0
  28. statstudio/plots/common.py +334 -0
  29. statstudio/plots/diagnostics.py +214 -0
  30. statstudio/plots/doe_plots.py +235 -0
  31. statstudio/plots/plotly_builders.py +719 -0
  32. statstudio/plots/predictive_plots.py +72 -0
  33. statstudio/plots/registry.py +251 -0
  34. statstudio/plugins.py +111 -0
  35. statstudio/resources/help_topics.json +13195 -0
  36. statstudio/resources/logo.ico +0 -0
  37. statstudio/resources/logo.png +0 -0
  38. statstudio/resources/statstudio.svg +8 -0
  39. statstudio/stats/__init__.py +42 -0
  40. statstudio/stats/bayesian.py +1094 -0
  41. statstudio/stats/bayesian_optimization.py +590 -0
  42. statstudio/stats/common.py +140 -0
  43. statstudio/stats/correlation.py +135 -0
  44. statstudio/stats/custom_doe.py +1714 -0
  45. statstudio/stats/descriptive.py +200 -0
  46. statstudio/stats/desirability.py +132 -0
  47. statstudio/stats/distributions.py +331 -0
  48. statstudio/stats/doe.py +1070 -0
  49. statstudio/stats/hypothesis.py +1305 -0
  50. statstudio/stats/multivariate.py +307 -0
  51. statstudio/stats/optimal_doe.py +264 -0
  52. statstudio/stats/power.py +194 -0
  53. statstudio/stats/predictive.py +605 -0
  54. statstudio/stats/profiler.py +379 -0
  55. statstudio/stats/quality.py +1218 -0
  56. statstudio/stats/regression.py +1600 -0
  57. statstudio/stats/results.py +235 -0
  58. statstudio/stats/simulator.py +95 -0
  59. statstudio/stats/survival.py +637 -0
  60. statstudio/stats/timeseries.py +643 -0
  61. statstudio/stats/tolerance.py +154 -0
  62. statstudio/ui/__init__.py +0 -0
  63. statstudio/ui/analysis_hub.py +271 -0
  64. statstudio/ui/command_catalog.py +460 -0
  65. statstudio/ui/command_palette.py +55 -0
  66. statstudio/ui/console.py +239 -0
  67. statstudio/ui/dialogs/__init__.py +0 -0
  68. statstudio/ui/dialogs/advanced_dialogs.py +392 -0
  69. statstudio/ui/dialogs/base.py +537 -0
  70. statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
  71. statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
  72. statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
  73. statstudio/ui/dialogs/doe_dialogs.py +220 -0
  74. statstudio/ui/dialogs/extended_dialogs.py +665 -0
  75. statstudio/ui/dialogs/graph_builder.py +139 -0
  76. statstudio/ui/dialogs/help_dialog.py +207 -0
  77. statstudio/ui/dialogs/help_topics.py +280 -0
  78. statstudio/ui/dialogs/lazy.py +184 -0
  79. statstudio/ui/dialogs/odbc_dialog.py +311 -0
  80. statstudio/ui/dialogs/plot_dialog.py +1385 -0
  81. statstudio/ui/dialogs/report_composer.py +218 -0
  82. statstudio/ui/dialogs/script_dialogs.py +267 -0
  83. statstudio/ui/dialogs/stats_dialogs.py +1688 -0
  84. statstudio/ui/dialogs/table_dialogs.py +997 -0
  85. statstudio/ui/dialogs/window.py +58 -0
  86. statstudio/ui/docks/__init__.py +0 -0
  87. statstudio/ui/formula_editor.py +121 -0
  88. statstudio/ui/icons.py +257 -0
  89. statstudio/ui/jobs.py +179 -0
  90. statstudio/ui/main_window.py +3934 -0
  91. statstudio/ui/plot_interaction.py +178 -0
  92. statstudio/ui/profiler_widget.py +437 -0
  93. statstudio/ui/recent.py +82 -0
  94. statstudio/ui/reports/__init__.py +0 -0
  95. statstudio/ui/reports/report_view.py +1632 -0
  96. statstudio/ui/script_jobs.py +35 -0
  97. statstudio/ui/scripts_panel.py +271 -0
  98. statstudio/ui/table_document.py +233 -0
  99. statstudio/ui/table_model.py +285 -0
  100. statstudio/ui/table_view.py +285 -0
  101. statstudio/ui/theme.py +645 -0
  102. statstudio/ui/welcome.py +453 -0
  103. statstudio/ui/window_controls.py +53 -0
  104. statstudio/ui/workers.py +53 -0
  105. statstudio-0.1.0.dist-info/METADATA +261 -0
  106. statstudio-0.1.0.dist-info/RECORD +110 -0
  107. statstudio-0.1.0.dist-info/WHEEL +5 -0
  108. statstudio-0.1.0.dist-info/entry_points.txt +5 -0
  109. statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
  110. statstudio-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,605 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Sequence
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from sklearn.base import clone
8
+ from sklearn.compose import TransformedTargetRegressor
9
+ from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
10
+ from sklearn.naive_bayes import GaussianNB
11
+ from sklearn.svm import SVC, SVR
12
+ from sklearn.metrics import (
13
+ accuracy_score,
14
+ balanced_accuracy_score,
15
+ confusion_matrix,
16
+ f1_score,
17
+ mean_absolute_error,
18
+ mean_squared_error,
19
+ precision_score,
20
+ r2_score,
21
+ recall_score,
22
+ roc_auc_score,
23
+ )
24
+ from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score, train_test_split
25
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
26
+ from sklearn.pipeline import Pipeline
27
+ from sklearn.preprocessing import StandardScaler
28
+ from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
29
+
30
+ from statstudio.stats.results import AnalysisResult
31
+
32
+ DEFAULT_PREDICTORS = "__default__"
33
+
34
+
35
+ def _is_classification(series: pd.Series) -> bool:
36
+ if pd.api.types.is_bool_dtype(series):
37
+ return True
38
+ if not pd.api.types.is_numeric_dtype(series):
39
+ return True
40
+ return series.nunique(dropna=True) <= 10 and not pd.api.types.is_float_dtype(series)
41
+
42
+
43
+ def _prepare(
44
+ df: pd.DataFrame,
45
+ response: str,
46
+ predictors: Sequence[str] | None,
47
+ criterion: str = "auto",
48
+ ) -> tuple[pd.DataFrame, np.ndarray, np.ndarray, bool, list[str], pd.Series]:
49
+ if response not in df.columns:
50
+ raise KeyError(response)
51
+ if not predictors:
52
+ numeric = [c for c in df.columns if c != response and pd.api.types.is_numeric_dtype(df[c])]
53
+ predictors = numeric
54
+ predictors = [p for p in predictors if p != response and p in df.columns]
55
+ if not predictors:
56
+ raise ValueError("Choose at least one predictor.")
57
+ frame = df[[response] + predictors].copy()
58
+ for predictor in predictors:
59
+ if not pd.api.types.is_numeric_dtype(frame[predictor]):
60
+ frame[predictor] = frame[predictor].astype(object)
61
+ frame[predictor] = frame[predictor].where(frame[predictor].notna(), "(missing)")
62
+ frame = frame.dropna(subset=[response])
63
+ numeric_predictors = [p for p in predictors if pd.api.types.is_numeric_dtype(frame[p])]
64
+ if numeric_predictors:
65
+ frame = frame.dropna(subset=numeric_predictors)
66
+ if len(frame) < 10:
67
+ raise ValueError("At least ten complete rows are required.")
68
+ if criterion == "classification":
69
+ classification = True
70
+ elif criterion == "regression":
71
+ classification = False
72
+ else:
73
+ classification = _is_classification(frame[response])
74
+ y = frame[response]
75
+ if classification:
76
+ classes = sorted(y.astype(str).unique().tolist())
77
+ mapping = {label: index for index, label in enumerate(classes)}
78
+ y_array = y.astype(str).map(mapping).to_numpy(dtype=int)
79
+ else:
80
+ y_array = pd.to_numeric(y, errors="coerce").to_numpy(dtype=float)
81
+ mask = ~np.isnan(y_array)
82
+ frame = frame.loc[mask]
83
+ y_array = y_array[mask]
84
+ X = pd.get_dummies(frame[predictors], drop_first=False, dtype=float)
85
+ return frame, X.to_numpy(dtype=float), np.asarray(y_array), classification, list(X.columns), y
86
+
87
+
88
+ def _split_indices(n: int, y: np.ndarray, validation: float, seed: int, classification: bool) -> tuple[np.ndarray, np.ndarray]:
89
+ if 0 < validation < 100 and n >= 20:
90
+ stratify = y if classification else None
91
+ return train_test_split(np.arange(n), test_size=validation / 100.0, random_state=seed, stratify=stratify)
92
+ return np.arange(n), np.arange(0)
93
+
94
+
95
+ def _split(X: np.ndarray, y: np.ndarray, validation: float, seed: int, classification: bool):
96
+ train, test = _split_indices(len(X), y, validation, seed, classification)
97
+ return X[train], X[test], y[train], y[test]
98
+
99
+
100
+ def _metrics(
101
+ y_true: np.ndarray,
102
+ y_pred: np.ndarray,
103
+ classification: bool,
104
+ probability: np.ndarray | None = None,
105
+ ) -> dict[str, float]:
106
+ if classification:
107
+ values = {
108
+ "Accuracy": float(accuracy_score(y_true, y_pred)),
109
+ "Balanced accuracy": float(balanced_accuracy_score(y_true, y_pred)),
110
+ "Precision (weighted)": float(precision_score(y_true, y_pred, average="weighted", zero_division=0)),
111
+ "Recall (weighted)": float(recall_score(y_true, y_pred, average="weighted", zero_division=0)),
112
+ "F1 (weighted)": float(f1_score(y_true, y_pred, average="weighted", zero_division=0)),
113
+ }
114
+ if probability is not None and len(np.unique(y_true)) == 2:
115
+ try:
116
+ values["ROC AUC"] = float(roc_auc_score(y_true, probability))
117
+ except Exception:
118
+ pass
119
+ return values
120
+ return {
121
+ "RMSE": float(np.sqrt(mean_squared_error(y_true, y_pred))),
122
+ "MAE": float(mean_absolute_error(y_true, y_pred)),
123
+ "R-squared": float(r2_score(y_true, y_pred)),
124
+ }
125
+
126
+
127
+ def _importance(model, feature_names: list[str], X: np.ndarray, y: np.ndarray) -> pd.DataFrame:
128
+ values = None
129
+ if hasattr(model, "feature_importances_"):
130
+ values = np.asarray(model.feature_importances_)
131
+ elif hasattr(model, "coef_"):
132
+ coef = np.atleast_2d(model.coef_)
133
+ values = np.abs(coef).mean(axis=0)[: len(feature_names)]
134
+ if values is None:
135
+ try:
136
+ from sklearn.inspection import permutation_importance
137
+
138
+ outcome = permutation_importance(model, X, y, n_repeats=5, random_state=42)
139
+ values = outcome.importances_mean
140
+ except Exception:
141
+ return pd.DataFrame()
142
+ values = np.asarray(values).ravel()
143
+ if len(values) != len(feature_names):
144
+ values = values[: len(feature_names)]
145
+ frame = pd.DataFrame({"Variable": feature_names, "Importance": values})
146
+ return frame.sort_values("Importance", ascending=False).reset_index(drop=True)
147
+
148
+
149
+ def _predictions_frame(frame: pd.DataFrame, y_true: np.ndarray, y_pred: np.ndarray, classification: bool, probability: np.ndarray | None, label_map: dict[int, str] | None) -> pd.DataFrame:
150
+ prediction = pd.DataFrame(
151
+ {
152
+ "Row": np.arange(1, len(y_true) + 1),
153
+ "Actual": y_true,
154
+ "Predicted": y_pred,
155
+ }
156
+ )
157
+ if classification:
158
+ if label_map:
159
+ prediction["Actual"] = [label_map.get(int(v), v) for v in y_true]
160
+ prediction["Predicted"] = [label_map.get(int(v), v) for v in y_pred]
161
+ else:
162
+ prediction["Residual"] = prediction["Actual"] - prediction["Predicted"]
163
+ if probability is not None:
164
+ prediction["Probability"] = probability
165
+ return prediction.head(500)
166
+
167
+
168
+ def _add_common_outputs(
169
+ result: AnalysisResult,
170
+ frame: pd.DataFrame,
171
+ y_true: np.ndarray,
172
+ y_pred: np.ndarray,
173
+ classification: bool,
174
+ probability: np.ndarray | None,
175
+ label_map: dict[int, str] | None,
176
+ ) -> None:
177
+ if classification:
178
+ labels = sorted(set(np.asarray(y_true).tolist()) | set(np.asarray(y_pred).tolist()))
179
+ matrix = confusion_matrix(y_true, y_pred, labels=labels)
180
+ display = label_map or {int(v): str(v) for v in labels}
181
+ confusion = pd.DataFrame(matrix, index=[display.get(int(v), v) for v in labels], columns=[display.get(int(v), v) for v in labels])
182
+ confusion = confusion.reset_index().rename(columns={"index": "Actual"})
183
+ result.add_table("Confusion Matrix", confusion)
184
+ result.add_plot(
185
+ "confusion",
186
+ {"labels": [display.get(int(v), v) for v in labels], "matrix": matrix.tolist()},
187
+ title="Confusion Matrix",
188
+ )
189
+ prediction = _predictions_frame(frame, y_true, y_pred, True, probability, display)
190
+ else:
191
+ prediction = _predictions_frame(frame, y_true, y_pred, False, None, None)
192
+ plot_frame = pd.DataFrame({"Actual": y_true, "Predicted": y_pred})
193
+ result.add_plot("actual_predicted", {"actual": "Actual", "predicted": "Predicted", "identity": True}, title="Actual vs Predicted", data=plot_frame)
194
+ result.add_table("Predictions", prediction)
195
+ if classification and probability is not None:
196
+ threshold_rows = []
197
+ for threshold in np.linspace(0.05, 0.95, 19):
198
+ predicted = (np.asarray(probability) >= threshold).astype(int)
199
+ tp = int(np.sum((predicted == 1) & (np.asarray(y_true) == 1)))
200
+ tn = int(np.sum((predicted == 0) & (np.asarray(y_true) == 0)))
201
+ fp = int(np.sum((predicted == 1) & (np.asarray(y_true) == 0)))
202
+ fn = int(np.sum((predicted == 0) & (np.asarray(y_true) == 1)))
203
+ threshold_rows.append({
204
+ "Threshold": float(threshold),
205
+ "Accuracy": (tp + tn) / max(1, len(y_true)),
206
+ "Sensitivity": tp / max(1, tp + fn),
207
+ "Specificity": tn / max(1, tn + fp),
208
+ "Precision": tp / max(1, tp + fp),
209
+ "Predicted Positive": int(tp + fp),
210
+ })
211
+ result.add_table("Threshold / Cost Table", pd.DataFrame(threshold_rows))
212
+ order = np.argsort(-np.asarray(probability, dtype=float))
213
+ actual_sorted = np.asarray(y_true)[order]
214
+ positives = max(1, int(np.sum(actual_sorted == 1)))
215
+ cumulative_gain = np.cumsum(actual_sorted == 1) / positives
216
+ population = np.arange(1, len(actual_sorted) + 1) / len(actual_sorted)
217
+ lift = cumulative_gain / population
218
+ gain_table = pd.DataFrame({"Population Fraction": population, "Cumulative Gain": cumulative_gain, "Lift": lift})
219
+ result.add_table("Lift / Gain", gain_table.iloc[:: max(1, len(gain_table) // 20)].reset_index(drop=True))
220
+ result.add_plot("line", {"x": "Population Fraction", "y": "Cumulative Gain", "y2": "Lift"}, title="Cumulative Gain / Lift", data=gain_table)
221
+
222
+
223
+ def _outcome_table(name: str, train_metrics: dict[str, float], test_metrics: dict[str, float], extra: dict[str, Any] | None = None) -> pd.DataFrame:
224
+ rows = [("Model", name), ("Training N", extra.get("train_n") if extra else None), ("Test N", extra.get("test_n") if extra else None)]
225
+ for key, value in train_metrics.items():
226
+ rows.append((f"Train {key}", value))
227
+ for key, value in test_metrics.items():
228
+ rows.append((f"Test {key}", value))
229
+ if extra:
230
+ for key, value in extra.items():
231
+ if key not in {"train_n", "test_n"}:
232
+ rows.append((key, value))
233
+ return pd.DataFrame(rows, columns=["Metric", "Value"])
234
+
235
+
236
+ def _model_wrapper(kind: str, classification: bool, params: dict[str, Any]):
237
+ if kind == "cart":
238
+ if classification:
239
+ return DecisionTreeClassifier(max_depth=params.get("max_depth"), min_samples_leaf=params.get("min_leaf", 1), ccp_alpha=params.get("cp", 0.0), random_state=params.get("seed", 42))
240
+ return DecisionTreeRegressor(max_depth=params.get("max_depth"), min_samples_leaf=params.get("min_leaf", 1), ccp_alpha=params.get("cp", 0.0), random_state=params.get("seed", 42))
241
+ if kind == "random_forest":
242
+ common = dict(
243
+ n_estimators=params.get("trees", 100),
244
+ max_features=params.get("mtry"),
245
+ min_samples_leaf=params.get("min_leaf", 1),
246
+ random_state=params.get("seed", 42),
247
+ n_jobs=-1,
248
+ )
249
+ return RandomForestClassifier(**common) if classification else RandomForestRegressor(**common)
250
+ if kind == "svm":
251
+ common = dict(C=params.get("c", 1.0), gamma=params.get("gamma", "scale"), random_state=params.get("seed", 42))
252
+ if classification:
253
+ return SVC(**common, probability=True)
254
+ return SVR(**common)
255
+ if kind == "naive_bayes":
256
+ if not classification:
257
+ raise ValueError("Naive Bayes is available for classification responses only.")
258
+ return GaussianNB()
259
+ if kind == "neural":
260
+ common = dict(
261
+ hidden_layer_sizes=(params.get("hidden", 10),),
262
+ alpha=params.get("decay", 0.0001),
263
+ max_iter=max(200, int(params.get("max_iter", 500))),
264
+ random_state=params.get("seed", 42),
265
+ activation="logistic",
266
+ solver="lbfgs",
267
+ )
268
+ scaler = StandardScaler()
269
+ if classification:
270
+ return Pipeline([("scale", scaler), ("model", MLPClassifier(**common))])
271
+ return Pipeline([
272
+ ("scale", scaler),
273
+ ("model", TransformedTargetRegressor(regressor=MLPRegressor(**common), transformer=StandardScaler())),
274
+ ])
275
+ if kind == "xgboost":
276
+ try:
277
+ from xgboost import XGBClassifier, XGBRegressor
278
+ except Exception as exc:
279
+ raise ValueError("XGBoost is not installed. Install the 'xgboost' package to use this model.") from exc
280
+ common = dict(
281
+ n_estimators=params.get("rounds", 100),
282
+ max_depth=params.get("max_depth", 3),
283
+ learning_rate=params.get("learning_rate", 0.1),
284
+ subsample=params.get("subsample", 1.0),
285
+ colsample_bytree=params.get("colsample", 1.0),
286
+ min_child_weight=params.get("min_child_weight", 1),
287
+ reg_lambda=params.get("reg_lambda", 1.0),
288
+ reg_alpha=params.get("reg_alpha", 0.0),
289
+ random_state=params.get("seed", 42),
290
+ )
291
+ if classification:
292
+ return XGBClassifier(**common, eval_metric="mlogloss")
293
+ return XGBRegressor(**common)
294
+ raise ValueError(f"Unknown model: {kind}")
295
+
296
+
297
+ def _run_model(
298
+ kind: str,
299
+ title: str,
300
+ df: pd.DataFrame,
301
+ response: str,
302
+ predictors: Sequence[str] | None,
303
+ criterion: str,
304
+ validation: float,
305
+ seed: int,
306
+ params: dict[str, Any],
307
+ extra: dict[str, Any] | None = None,
308
+ ) -> AnalysisResult:
309
+ frame, X, y, classification, feature_names, original_y = _prepare(df, response, predictors, criterion)
310
+ train_idx, test_idx = _split_indices(len(X), y, validation, seed, classification)
311
+ X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
312
+ model = _model_wrapper(kind, classification, {**params, "seed": seed})
313
+ model.fit(X_train, y_train)
314
+ train_probability = None
315
+ test_probability = None
316
+ if classification and hasattr(model, "predict_proba"):
317
+ try:
318
+ proba = model.predict_proba(X_train)
319
+ if proba.shape[1] == 2:
320
+ train_probability = proba[:, 1]
321
+ except Exception:
322
+ pass
323
+ train_metrics = _metrics(y_train, model.predict(X_train), classification, train_probability)
324
+ test_metrics: dict[str, float] = {}
325
+ if len(X_test):
326
+ if classification and hasattr(model, "predict_proba"):
327
+ try:
328
+ proba = model.predict_proba(X_test)
329
+ if proba.shape[1] == 2:
330
+ test_probability = proba[:, 1]
331
+ except Exception:
332
+ pass
333
+ test_metrics = _metrics(y_test, model.predict(X_test), classification, test_probability)
334
+ evaluation_X, evaluation_y, evaluation_frame, evaluation_original = (X_test, y_test, frame.iloc[test_idx].reset_index(drop=True), original_y.iloc[test_idx]) if len(X_test) else (X_train, y_train, frame.iloc[train_idx].reset_index(drop=True), original_y.iloc[train_idx])
335
+ y_pred = model.predict(evaluation_X)
336
+ probability = test_probability if len(X_test) else train_probability
337
+ classes = sorted(pd.unique(evaluation_original.astype(str)).tolist())
338
+ label_map = {index: label for index, label in enumerate(classes)} if classification else None
339
+ result = AnalysisResult(title=title, analysis_type=kind, params={"response": response, "predictors": list(predictors or []), "criterion": criterion, "validation": validation, "seed": seed, **params})
340
+ result.add_table("Model Summary", _outcome_table(kind.replace("_", " ").title(), train_metrics, test_metrics, {**(extra or {}), "train_n": len(X_train), "test_n": len(X_test), "Evaluation": "Test holdout" if len(X_test) else "Training", "Predictors": len(feature_names)}))
341
+ importance = _importance(model, feature_names, evaluation_X, evaluation_y)
342
+ if not importance.empty:
343
+ result.add_table("Variable Importance", importance)
344
+ result.add_plot("importance", {"variable": "Variable", "importance": "Importance"}, title="Variable Importance", data=importance)
345
+ try:
346
+ folds = max(2, min(5, len(X_train)))
347
+ if classification:
348
+ folds = max(2, min(folds, int(pd.Series(y_train).value_counts().min())))
349
+ splitter = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)
350
+ scoring = "accuracy"
351
+ else:
352
+ splitter = KFold(n_splits=folds, shuffle=True, random_state=seed)
353
+ scoring = "neg_root_mean_squared_error"
354
+ scores = cross_val_score(clone(model), X_train, y_train, cv=splitter, scoring=scoring, n_jobs=-1)
355
+ cv_value = float(np.mean(scores))
356
+ if not classification:
357
+ cv_value = -cv_value
358
+ result.add_table("Cross-Validation", pd.DataFrame([{"Folds": folds, "Metric": scoring, "Score": cv_value, "Std Dev": float(np.std(scores))}]))
359
+ except Exception:
360
+ pass
361
+ _add_common_outputs(result, evaluation_frame, evaluation_y, y_pred, classification, probability, label_map)
362
+ metric_text = ", ".join(f"{key} = {value:.4g}" for key, value in (test_metrics or train_metrics).items())
363
+ evaluation_label = "held-out test" if len(X_test) else "training"
364
+ result.summary = f"{title} on {len(evaluation_frame)} {evaluation_label} rows ({len(feature_names)} encoded predictors). {metric_text}."
365
+ return result
366
+
367
+
368
+ def cart(
369
+ df: pd.DataFrame,
370
+ response: str,
371
+ predictors: Sequence[str] | None = None,
372
+ criterion: str = "auto",
373
+ max_depth: int | None = 6,
374
+ min_leaf: int = 1,
375
+ cp: float = 0.0,
376
+ validation: float = 20.0,
377
+ seed: int = 42,
378
+ ) -> AnalysisResult:
379
+ return _run_model("cart", f"Partition (CART): {response}", df, response, predictors, criterion, validation, seed, {"max_depth": max_depth, "min_leaf": min_leaf, "cp": cp})
380
+
381
+
382
+ def random_forest(
383
+ df: pd.DataFrame,
384
+ response: str,
385
+ predictors: Sequence[str] | None = None,
386
+ criterion: str = "auto",
387
+ trees: int = 100,
388
+ mtry: int | None = None,
389
+ min_leaf: int = 1,
390
+ validation: float = 20.0,
391
+ seed: int = 42,
392
+ ) -> AnalysisResult:
393
+ return _run_model("random_forest", f"Random Forest: {response}", df, response, predictors, criterion, validation, seed, {"trees": trees, "mtry": mtry, "min_leaf": min_leaf}, {"Trees": trees})
394
+
395
+
396
+ def neural_network(
397
+ df: pd.DataFrame,
398
+ response: str,
399
+ predictors: Sequence[str] | None = None,
400
+ criterion: str = "auto",
401
+ hidden: int = 10,
402
+ decay: float = 0.0001,
403
+ max_iter: int = 500,
404
+ validation: float = 20.0,
405
+ seed: int = 42,
406
+ ) -> AnalysisResult:
407
+ return _run_model("neural", f"Neural Network: {response}", df, response, predictors, criterion, validation, seed, {"hidden": hidden, "decay": decay, "max_iter": max_iter}, {"Hidden Units": hidden})
408
+
409
+
410
+ def xgboost_model(
411
+ df: pd.DataFrame,
412
+ response: str,
413
+ predictors: Sequence[str] | None = None,
414
+ criterion: str = "auto",
415
+ rounds: int = 100,
416
+ max_depth: int = 3,
417
+ learning_rate: float = 0.1,
418
+ subsample: float = 1.0,
419
+ colsample: float = 1.0,
420
+ min_child_weight: float = 1.0,
421
+ reg_lambda: float = 1.0,
422
+ reg_alpha: float = 0.0,
423
+ validation: float = 20.0,
424
+ seed: int = 42,
425
+ ) -> AnalysisResult:
426
+ return _run_model(
427
+ "xgboost",
428
+ f"XGBoost: {response}",
429
+ df,
430
+ response,
431
+ predictors,
432
+ criterion,
433
+ validation,
434
+ seed,
435
+ {
436
+ "rounds": rounds,
437
+ "max_depth": max_depth,
438
+ "learning_rate": learning_rate,
439
+ "subsample": subsample,
440
+ "colsample": colsample,
441
+ "min_child_weight": min_child_weight,
442
+ "reg_lambda": reg_lambda,
443
+ "reg_alpha": reg_alpha,
444
+ },
445
+ {"Boosting Rounds": rounds, "Learning Rate": learning_rate},
446
+ )
447
+
448
+
449
+ def automl(
450
+ df: pd.DataFrame,
451
+ response: str,
452
+ predictors: Sequence[str] | None = None,
453
+ criterion: str = "auto",
454
+ validation: float = 20.0,
455
+ folds: int = 5,
456
+ seed: int = 42,
457
+ max_depth: int | None = 6,
458
+ cp: float = 0.0,
459
+ rf_trees: int = 100,
460
+ rf_mtry: int | None = None,
461
+ rf_min_leaf: int = 1,
462
+ rounds: int = 100,
463
+ boost_depth: int = 3,
464
+ learning_rate: float = 0.1,
465
+ hidden: int = 10,
466
+ decay: float = 0.0001,
467
+ max_iter: int = 500,
468
+ ) -> AnalysisResult:
469
+ frame, X, y, classification, feature_names, original_y = _prepare(df, response, predictors, criterion)
470
+ train_idx, test_idx = _split_indices(len(X), y, validation, seed, classification)
471
+ X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
472
+ candidates = {
473
+ "CART": _model_wrapper("cart", classification, {"max_depth": max_depth, "cp": cp, "seed": seed}),
474
+ "Random Forest": _model_wrapper("random_forest", classification, {"trees": rf_trees, "mtry": rf_mtry, "min_leaf": rf_min_leaf, "seed": seed}),
475
+ "Neural Network": _model_wrapper("neural", classification, {"hidden": hidden, "decay": decay, "max_iter": max_iter, "seed": seed}),
476
+ }
477
+ try:
478
+ candidates["XGBoost"] = _model_wrapper("xgboost", classification, {"rounds": rounds, "max_depth": boost_depth, "learning_rate": learning_rate, "seed": seed})
479
+ except Exception:
480
+ pass
481
+ folds = max(2, min(folds, len(X_train)))
482
+ if classification:
483
+ min_class = int(pd.Series(y_train).value_counts().min())
484
+ folds = max(2, min(folds, min_class)) if min_class >= 2 else 2
485
+ splitter = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)
486
+ scoring = "accuracy"
487
+ else:
488
+ splitter = KFold(n_splits=folds, shuffle=True, random_state=seed)
489
+ scoring = "neg_root_mean_squared_error"
490
+ rows = []
491
+ best_name = None
492
+ best_score = -np.inf
493
+ for name, model in candidates.items():
494
+ try:
495
+ scores = cross_val_score(model, X_train, y_train, cv=splitter, scoring=scoring, n_jobs=-1)
496
+ except Exception:
497
+ continue
498
+ mean = float(np.mean(scores))
499
+ rows.append({"Model": name, f"CV {scoring}": mean, "CV Std": float(np.std(scores)), "Folds": folds})
500
+ if mean > best_score:
501
+ best_score = mean
502
+ best_name = name
503
+ if not rows:
504
+ raise ValueError("No candidate model could be evaluated.")
505
+ comparison = pd.DataFrame(rows).sort_values(f"CV {scoring}", ascending=False).reset_index(drop=True)
506
+ comparison["Rank"] = np.arange(1, len(comparison) + 1)
507
+ best_model = candidates[best_name]
508
+ best_model.fit(X_train, y_train)
509
+ train_probability = None
510
+ test_probability = None
511
+ if classification and hasattr(best_model, "predict_proba"):
512
+ try:
513
+ proba = best_model.predict_proba(X_train)
514
+ if proba.shape[1] == 2:
515
+ train_probability = proba[:, 1]
516
+ except Exception:
517
+ pass
518
+ train_metrics = _metrics(y_train, best_model.predict(X_train), classification, train_probability)
519
+ test_metrics: dict[str, float] = {}
520
+ if len(X_test):
521
+ if classification and hasattr(best_model, "predict_proba"):
522
+ try:
523
+ proba = best_model.predict_proba(X_test)
524
+ if proba.shape[1] == 2:
525
+ test_probability = proba[:, 1]
526
+ except Exception:
527
+ pass
528
+ test_metrics = _metrics(y_test, best_model.predict(X_test), classification, test_probability)
529
+ evaluation_X, evaluation_y, evaluation_frame, evaluation_original = (X_test, y_test, frame.iloc[test_idx].reset_index(drop=True), original_y.iloc[test_idx]) if len(X_test) else (X_train, y_train, frame.iloc[train_idx].reset_index(drop=True), original_y.iloc[train_idx])
530
+ y_pred = best_model.predict(evaluation_X)
531
+ probability = test_probability if len(X_test) else train_probability
532
+ classes = sorted(pd.unique(evaluation_original.astype(str)).tolist())
533
+ label_map = {index: label for index, label in enumerate(classes)} if classification else None
534
+ result = AnalysisResult(
535
+ title=f"Auto Model: {response}",
536
+ analysis_type="automl",
537
+ params={
538
+ "response": response,
539
+ "predictors": list(predictors or []),
540
+ "criterion": criterion,
541
+ "validation": validation,
542
+ "folds": folds,
543
+ "seed": seed,
544
+ "max_depth": max_depth,
545
+ "cp": cp,
546
+ "rf_trees": rf_trees,
547
+ "rf_mtry": rf_mtry,
548
+ "rf_min_leaf": rf_min_leaf,
549
+ "rounds": rounds,
550
+ "boost_depth": boost_depth,
551
+ "learning_rate": learning_rate,
552
+ "hidden": hidden,
553
+ "decay": decay,
554
+ "max_iter": max_iter,
555
+ },
556
+ )
557
+ result.add_table("Model Comparison", comparison)
558
+ result.add_table(
559
+ "Best Model",
560
+ pd.DataFrame(
561
+ [
562
+ ("Selected model", best_name),
563
+ ("CV metric", scoring),
564
+ ("CV score", best_score),
565
+ ("Training N", len(X_train)),
566
+ ("Test N", len(X_test)),
567
+ ("CV folds", folds),
568
+ *train_metrics.items(),
569
+ *{f"Test {key}": value for key, value in test_metrics.items()}.items(),
570
+ ],
571
+ columns=["Metric", "Value"],
572
+ ),
573
+ )
574
+ importance = _importance(best_model, feature_names, evaluation_X, evaluation_y)
575
+ if not importance.empty:
576
+ result.add_table("Variable Importance", importance)
577
+ result.add_plot("importance", {"variable": "Variable", "importance": "Importance"}, title="Variable Importance", data=importance)
578
+ _add_common_outputs(result, evaluation_frame, evaluation_y, y_pred, classification, probability, label_map)
579
+ result.add_plot("model_comparison", {"model": "Model", "score": f"CV {scoring}"}, title="Model Comparison", data=comparison)
580
+ result.summary = f"Best model: {best_name} with CV {scoring} = {best_score:.4g} across {folds} folds."
581
+ return result
582
+
583
+
584
+ def svm_model(
585
+ df: pd.DataFrame,
586
+ response: str,
587
+ predictors: Sequence[str] | None = None,
588
+ criterion: str = "auto",
589
+ c: float = 1.0,
590
+ gamma: str = "scale",
591
+ validation: float = 20.0,
592
+ seed: int = 42,
593
+ ) -> AnalysisResult:
594
+ return _run_model("svm", f"Support Vector Machine: {response}", df, response, predictors, criterion, validation, seed, {"c": c, "gamma": gamma}, {"C": c, "Gamma": gamma})
595
+
596
+
597
+ def naive_bayes(
598
+ df: pd.DataFrame,
599
+ response: str,
600
+ predictors: Sequence[str] | None = None,
601
+ criterion: str = "classification",
602
+ validation: float = 20.0,
603
+ seed: int = 42,
604
+ ) -> AnalysisResult:
605
+ return _run_model("naive_bayes", f"Naive Bayes: {response}", df, response, predictors, criterion, validation, seed, {}, {})