noweda 0.2.2__tar.gz → 0.2.3__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.
Files changed (55) hide show
  1. {noweda-0.2.2/noweda.egg-info → noweda-0.2.3}/PKG-INFO +7 -2
  2. {noweda-0.2.2 → noweda-0.2.3}/README.md +4 -1
  3. noweda-0.2.3/noweda/_version.py +1 -0
  4. {noweda-0.2.2 → noweda-0.2.3}/noweda/accessor.py +3 -1
  5. {noweda-0.2.2 → noweda-0.2.3}/noweda/visualization.py +436 -23
  6. {noweda-0.2.2 → noweda-0.2.3/noweda.egg-info}/PKG-INFO +7 -2
  7. {noweda-0.2.2 → noweda-0.2.3}/noweda.egg-info/requires.txt +2 -0
  8. {noweda-0.2.2 → noweda-0.2.3}/pyproject.toml +2 -2
  9. {noweda-0.2.2 → noweda-0.2.3}/tests/test_vizall_ml.py +123 -0
  10. noweda-0.2.2/noweda/_version.py +0 -1
  11. {noweda-0.2.2 → noweda-0.2.3}/LICENSE +0 -0
  12. {noweda-0.2.2 → noweda-0.2.3}/MANIFEST.in +0 -0
  13. {noweda-0.2.2 → noweda-0.2.3}/examples/sample.csv +0 -0
  14. {noweda-0.2.2 → noweda-0.2.3}/noweda/__init__.py +0 -0
  15. {noweda-0.2.2 → noweda-0.2.3}/noweda/cli.py +0 -0
  16. {noweda-0.2.2 → noweda-0.2.3}/noweda/core/__init__.py +0 -0
  17. {noweda-0.2.2 → noweda-0.2.3}/noweda/core/engine.py +0 -0
  18. {noweda-0.2.2 → noweda-0.2.3}/noweda/dtypes.py +0 -0
  19. {noweda-0.2.2 → noweda-0.2.3}/noweda/insights/__init__.py +0 -0
  20. {noweda-0.2.2 → noweda-0.2.3}/noweda/insights/generator.py +0 -0
  21. {noweda-0.2.2 → noweda-0.2.3}/noweda/io.py +0 -0
  22. {noweda-0.2.2 → noweda-0.2.3}/noweda/large.py +0 -0
  23. {noweda-0.2.2 → noweda-0.2.3}/noweda/ml_recommendations.py +0 -0
  24. {noweda-0.2.2 → noweda-0.2.3}/noweda/ml_tasks.py +0 -0
  25. {noweda-0.2.2 → noweda-0.2.3}/noweda/ml_utils.py +0 -0
  26. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/__init__.py +0 -0
  27. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/base.py +0 -0
  28. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/correlation.py +0 -0
  29. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/duplicates.py +0 -0
  30. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/encoding.py +0 -0
  31. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/missing.py +0 -0
  32. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/outliers.py +0 -0
  33. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/pii.py +0 -0
  34. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/schema.py +0 -0
  35. {noweda-0.2.2 → noweda-0.2.3}/noweda/plugins/stats.py +0 -0
  36. {noweda-0.2.2 → noweda-0.2.3}/noweda/report/__init__.py +0 -0
  37. {noweda-0.2.2 → noweda-0.2.3}/noweda/report/html.py +0 -0
  38. {noweda-0.2.2 → noweda-0.2.3}/noweda/report/json.py +0 -0
  39. {noweda-0.2.2 → noweda-0.2.3}/noweda/scoring/__init__.py +0 -0
  40. {noweda-0.2.2 → noweda-0.2.3}/noweda/scoring/scorer.py +0 -0
  41. {noweda-0.2.2 → noweda-0.2.3}/noweda/temporal_utils.py +0 -0
  42. {noweda-0.2.2 → noweda-0.2.3}/noweda/ui.py +0 -0
  43. {noweda-0.2.2 → noweda-0.2.3}/noweda.egg-info/SOURCES.txt +0 -0
  44. {noweda-0.2.2 → noweda-0.2.3}/noweda.egg-info/dependency_links.txt +0 -0
  45. {noweda-0.2.2 → noweda-0.2.3}/noweda.egg-info/entry_points.txt +0 -0
  46. {noweda-0.2.2 → noweda-0.2.3}/noweda.egg-info/top_level.txt +0 -0
  47. {noweda-0.2.2 → noweda-0.2.3}/setup.cfg +0 -0
  48. {noweda-0.2.2 → noweda-0.2.3}/setup.py +0 -0
  49. {noweda-0.2.2 → noweda-0.2.3}/tests/test_basic.py +0 -0
  50. {noweda-0.2.2 → noweda-0.2.3}/tests/test_formats.py +0 -0
  51. {noweda-0.2.2 → noweda-0.2.3}/tests/test_large_mode.py +0 -0
  52. {noweda-0.2.2 → noweda-0.2.3}/tests/test_ml_tasks.py +0 -0
  53. {noweda-0.2.2 → noweda-0.2.3}/tests/test_progress.py +0 -0
  54. {noweda-0.2.2 → noweda-0.2.3}/tests/test_regressions.py +0 -0
  55. {noweda-0.2.2 → noweda-0.2.3}/tests/test_release_014.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: noweda
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Automated EDA with insights, scoring, and security-aware detection — built as a native pandas extension.
5
5
  Author-email: Daniel Peng <danielpeng95@gmail.com>
6
6
  License: MIT
@@ -38,6 +38,7 @@ Requires-Dist: odfpy>=1.4.1; extra == "excel"
38
38
  Provides-Extra: viz
39
39
  Requires-Dist: matplotlib>=3.5; extra == "viz"
40
40
  Requires-Dist: scipy>=1.7; extra == "viz"
41
+ Requires-Dist: scikit-learn>=1.0; extra == "viz"
41
42
  Provides-Extra: ml
42
43
  Requires-Dist: statsmodels>=0.13; extra == "ml"
43
44
  Requires-Dist: scikit-learn>=1.0; extra == "ml"
@@ -46,6 +47,7 @@ Requires-Dist: pytest>=7; extra == "test"
46
47
  Requires-Dist: odfpy>=1.4.1; extra == "test"
47
48
  Requires-Dist: matplotlib>=3.5; extra == "test"
48
49
  Requires-Dist: scipy>=1.7; extra == "test"
50
+ Requires-Dist: scikit-learn>=1.0; extra == "test"
49
51
  Provides-Extra: hdf
50
52
  Requires-Dist: tables>=3.7; extra == "hdf"
51
53
  Provides-Extra: spss
@@ -203,6 +205,8 @@ missingness, outliers, feature scales, and applicable temporal plots. Supply the
203
205
  prediction target to add classification or regression diagnostics. NowEDA ranks
204
206
  useful features, excludes likely identifiers and detected PII, and describes
205
207
  model-family signals without claiming that a chart proves the best model.
208
+ Where applicable, it fits bounded visual baselines for linear regression,
209
+ logistic probability, linear and nonlinear SVM boundaries, and K-Means.
206
210
 
207
211
  ```python
208
212
  df.eda.vizall() # General and unsupervised structure
@@ -212,6 +216,7 @@ visuals = df.eda.vizall(
212
216
  max_plots=15,
213
217
  )
214
218
  print(visuals["model_signals"])
219
+ print(visuals["diagnostic_models"])
215
220
 
216
221
  df.eda.vizall(sample=5_000) # Optional bounded sample
217
222
  ```
@@ -284,7 +289,7 @@ df = eda.read("data.csv", dtype={"customer_id": str})
284
289
  | Parquet, Feather, ORC | Included with `pip install noweda` |
285
290
  | HDF5 | `pip install "noweda[hdf]"` |
286
291
  | SPSS | `pip install "noweda[spss]"` |
287
- | Charts and KDE overlays | `pip install "noweda[viz]"` |
292
+ | Charts, KDE overlays, and fitted visual diagnostics | `pip install "noweda[viz]"` |
288
293
  | Stationarity and seasonality dependencies | `pip install "noweda[ml]"` |
289
294
  | All optional analysis and format dependencies | `pip install "noweda[full]"` |
290
295
 
@@ -139,6 +139,8 @@ missingness, outliers, feature scales, and applicable temporal plots. Supply the
139
139
  prediction target to add classification or regression diagnostics. NowEDA ranks
140
140
  useful features, excludes likely identifiers and detected PII, and describes
141
141
  model-family signals without claiming that a chart proves the best model.
142
+ Where applicable, it fits bounded visual baselines for linear regression,
143
+ logistic probability, linear and nonlinear SVM boundaries, and K-Means.
142
144
 
143
145
  ```python
144
146
  df.eda.vizall() # General and unsupervised structure
@@ -148,6 +150,7 @@ visuals = df.eda.vizall(
148
150
  max_plots=15,
149
151
  )
150
152
  print(visuals["model_signals"])
153
+ print(visuals["diagnostic_models"])
151
154
 
152
155
  df.eda.vizall(sample=5_000) # Optional bounded sample
153
156
  ```
@@ -220,7 +223,7 @@ df = eda.read("data.csv", dtype={"customer_id": str})
220
223
  | Parquet, Feather, ORC | Included with `pip install noweda` |
221
224
  | HDF5 | `pip install "noweda[hdf]"` |
222
225
  | SPSS | `pip install "noweda[spss]"` |
223
- | Charts and KDE overlays | `pip install "noweda[viz]"` |
226
+ | Charts, KDE overlays, and fitted visual diagnostics | `pip install "noweda[viz]"` |
224
227
  | Stationarity and seasonality dependencies | `pip install "noweda[ml]"` |
225
228
  | All optional analysis and format dependencies | `pip install "noweda[full]"` |
226
229
 
@@ -0,0 +1 @@
1
+ __version__ = "0.2.3"
@@ -732,7 +732,9 @@ class NowEDAAccessor:
732
732
  ``vizall()`` selects a bounded set of general diagnostics. Supplying a
733
733
  target adds supervised feature-versus-target charts while preserving
734
734
  the existing workflow. The returned dictionary-like result contains
735
- the figures, ranked evidence, selected features, and scope metadata.
735
+ the figures, ranked evidence, selected features, fitted diagnostic
736
+ baselines, and scope metadata. These bounded visual fits are examples
737
+ for comparison rather than final model recommendations.
736
738
 
737
739
  Parameters
738
740
  ----------
@@ -1,8 +1,8 @@
1
1
  """Ranked, ML-aware visual diagnostics used by ``DataFrame.eda.vizall``.
2
2
 
3
- The analysis in this module is deliberately model-free. It describes visible
4
- structure that can inform which model families to validate; it never selects a
5
- winning estimator without fitting and evaluation.
3
+ Most analysis is descriptive. Small, disposable diagnostic estimators may be
4
+ fitted to draw regression, classification-boundary, and clustering overlays.
5
+ They are visual baselines, not persisted models or final model selection.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
@@ -70,7 +70,8 @@ def _is_identifier(column: Any, series: pd.Series, role: Optional[str]) -> bool:
70
70
 
71
71
 
72
72
  def _correlation_ratio(categories: pd.Series, values: pd.Series) -> float:
73
- pairs = pd.DataFrame({"category": categories, "value": values}).dropna()
73
+ pairs = pd.DataFrame({"category": categories, "value": values})
74
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
74
75
  if len(pairs) < 3 or pairs["category"].nunique() < 2:
75
76
  return 0.0
76
77
  numeric = pd.to_numeric(pairs["value"], errors="coerce")
@@ -88,7 +89,8 @@ def _correlation_ratio(categories: pd.Series, values: pd.Series) -> float:
88
89
 
89
90
 
90
91
  def _rank_correlation(left: pd.Series, right: pd.Series) -> float:
91
- pairs = pd.DataFrame({"left": left, "right": right}).dropna()
92
+ pairs = pd.DataFrame({"left": left, "right": right})
93
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
92
94
  if len(pairs) < 3 or pairs["left"].nunique() < 2 or pairs["right"].nunique() < 2:
93
95
  return 0.0
94
96
  value = pairs["left"].rank(method="average").corr(
@@ -122,7 +124,8 @@ def _association(feature: pd.Series, target: pd.Series, problem_type: str) -> fl
122
124
 
123
125
 
124
126
  def _numeric_shape(feature: pd.Series, target: pd.Series, problem_type: str) -> Optional[str]:
125
- pairs = pd.DataFrame({"feature": feature, "target": target}).dropna()
127
+ pairs = pd.DataFrame({"feature": feature, "target": target})
128
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
126
129
  if len(pairs) < 30 or pairs["feature"].nunique() < 5:
127
130
  return None
128
131
  try:
@@ -152,7 +155,10 @@ def _numeric_shape(feature: pd.Series, target: pd.Series, problem_type: str) ->
152
155
  grouped = working.groupby("_bin", observed=True)
153
156
  x_values = grouped["feature"].mean().to_numpy(dtype=float)
154
157
  rates = grouped["_event"].mean().to_numpy(dtype=float)
155
- if len(rates) < 4 or float(np.nanmax(rates) - np.nanmin(rates)) < 0.15:
158
+ # Rare binary outcomes can carry a useful curved signal even when the
159
+ # absolute event-rate spread is modest. A 10-point spread is large enough
160
+ # to flag for visual validation without treating small bin noise as shape.
161
+ if len(rates) < 4 or float(np.nanmax(rates) - np.nanmin(rates)) < 0.10:
156
162
  return None
157
163
  logits = np.log(np.clip(rates, 0.01, 0.99) / (1 - np.clip(rates, 0.01, 0.99)))
158
164
  coefficients = np.polyfit(x_values, logits, 1)
@@ -183,6 +189,9 @@ def build_visual_diagnostics(
183
189
  if target is not None:
184
190
  target_position = _column_position(df, target)
185
191
  target_series = df.iloc[:, target_position]
192
+ if pd.api.types.is_numeric_dtype(target_series.dtype):
193
+ target_series = pd.to_numeric(target_series, errors="coerce")
194
+ target_series = target_series.replace([np.inf, -np.inf], np.nan)
186
195
  if target_series.dropna().empty:
187
196
  raise ValueError("Target column {!r} has no observed values.".format(target))
188
197
  problem_type, target_reason = _infer_supervised_type(target_series)
@@ -227,17 +236,22 @@ def build_visual_diagnostics(
227
236
  ranked_categorical = [item["column"] for item in associations if item["kind"] == "categorical"]
228
237
  observations = []
229
238
  model_signals = []
239
+ shapes = {}
230
240
 
231
241
  target_summary = None
232
242
  if target_series is not None:
243
+ target_observed = target_series
244
+ if pd.api.types.is_numeric_dtype(target_series.dtype):
245
+ target_observed = pd.to_numeric(target_series, errors="coerce")
246
+ target_observed = target_observed.replace([np.inf, -np.inf], np.nan)
233
247
  target_summary = {
234
- "observed": int(target_series.notna().sum()),
235
- "missing": int(target_series.isna().sum()),
236
- "missing_rate": float(target_series.isna().mean()),
248
+ "observed": int(target_observed.notna().sum()),
249
+ "missing": int(target_observed.isna().sum()),
250
+ "missing_rate": float(target_observed.isna().mean()),
237
251
  "inference_reason": target_reason,
238
252
  }
239
253
  if problem_type == "classification":
240
- counts = target_series.value_counts(dropna=True)
254
+ counts = target_observed.value_counts(dropna=True)
241
255
  counts = counts[counts > 0]
242
256
  target_summary["class_counts"] = {
243
257
  _label(label): int(count) for label, count in counts.items()
@@ -252,9 +266,9 @@ def build_visual_diagnostics(
252
266
  )
253
267
  else:
254
268
  target_summary.update({
255
- "mean": float(target_series.mean()),
256
- "median": float(target_series.median()),
257
- "skewness": float(target_series.skew()) if len(target_series.dropna()) >= 3 else None,
269
+ "mean": float(target_observed.mean()),
270
+ "median": float(target_observed.median()),
271
+ "skewness": float(target_observed.skew()) if len(target_observed.dropna()) >= 3 else None,
258
272
  })
259
273
 
260
274
  if associations:
@@ -282,8 +296,7 @@ def build_visual_diagnostics(
282
296
  "Possible target leakage: {} has a near-deterministic univariate association; verify when it becomes available."
283
297
  .format(", ".join(_label(column) for column in leakage_candidates[:3]))
284
298
  )
285
- shapes = {}
286
- for column in ranked_numeric[:5]:
299
+ for column in ranked_numeric[:10]:
287
300
  score = next(
288
301
  item["score"] for item in associations if item["column"] == column
289
302
  )
@@ -317,10 +330,13 @@ def build_visual_diagnostics(
317
330
  model_signals.append(
318
331
  "Compare linear and nonlinear regressors with validation; residual behavior and predictive metrics decide the final model."
319
332
  )
333
+ else:
334
+ leakage_candidates = []
320
335
 
321
336
  numeric_scales = {}
322
337
  for column in numeric:
323
- values = pd.to_numeric(df[column], errors="coerce").dropna()
338
+ values = pd.to_numeric(df[column], errors="coerce")
339
+ values = values.replace([np.inf, -np.inf], np.nan).dropna()
324
340
  if len(values) >= 2:
325
341
  numeric_scales[column] = float(values.std())
326
342
  finite_scales = [value for value in numeric_scales.values() if value > 0 and np.isfinite(value)]
@@ -338,9 +354,12 @@ def build_visual_diagnostics(
338
354
  "categorical_features": ranked_categorical,
339
355
  "datetime_features": datetime,
340
356
  "excluded_features": excluded,
357
+ "leakage_candidates": leakage_candidates,
358
+ "feature_shapes": shapes,
341
359
  "numeric_scales": numeric_scales,
342
360
  "observations": observations,
343
361
  "model_signals": model_signals,
362
+ "diagnostic_models": [],
344
363
  }
345
364
 
346
365
 
@@ -374,6 +393,346 @@ def _finish_grid(plt, fig, axes, columns: int, rows: int, count: int, title: str
374
393
  plt.show()
375
394
 
376
395
 
396
+ def _sklearn_tools():
397
+ """Load optional estimator tools only when model overlays are applicable."""
398
+ try:
399
+ from sklearn.cluster import KMeans
400
+ from sklearn.decomposition import PCA
401
+ from sklearn.linear_model import LinearRegression, LogisticRegression
402
+ from sklearn.metrics import balanced_accuracy_score, r2_score, silhouette_score
403
+ from sklearn.model_selection import train_test_split
404
+ from sklearn.pipeline import make_pipeline
405
+ from sklearn.preprocessing import StandardScaler
406
+ from sklearn.svm import SVC
407
+ except ImportError:
408
+ return None
409
+ return {
410
+ "KMeans": KMeans,
411
+ "PCA": PCA,
412
+ "LinearRegression": LinearRegression,
413
+ "LogisticRegression": LogisticRegression,
414
+ "balanced_accuracy_score": balanced_accuracy_score,
415
+ "r2_score": r2_score,
416
+ "silhouette_score": silhouette_score,
417
+ "train_test_split": train_test_split,
418
+ "make_pipeline": make_pipeline,
419
+ "StandardScaler": StandardScaler,
420
+ "SVC": SVC,
421
+ }
422
+
423
+
424
+ def _bounded_classification_sample(frame: pd.DataFrame, limit: int) -> pd.DataFrame:
425
+ """Return a deterministic bounded sample while retaining small classes."""
426
+ frame = frame.reset_index(drop=True)
427
+ if len(frame) <= limit:
428
+ return frame
429
+ rng = np.random.RandomState(42)
430
+ selected = []
431
+ for indices in frame.groupby("target", sort=False).groups.values():
432
+ positions = np.asarray(list(indices), dtype=int)
433
+ amount = min(
434
+ len(positions),
435
+ max(10, int(round(limit * len(positions) / len(frame)))),
436
+ )
437
+ selected.extend(rng.choice(positions, size=amount, replace=False).tolist())
438
+ if len(selected) > limit:
439
+ selected = rng.choice(np.asarray(selected), size=limit, replace=False).tolist()
440
+ elif len(selected) < limit:
441
+ remaining = np.setdiff1d(np.arange(len(frame)), np.asarray(selected), assume_unique=False)
442
+ extra = rng.choice(remaining, size=min(limit - len(selected), len(remaining)), replace=False)
443
+ selected.extend(extra.tolist())
444
+ return frame.iloc[sorted(selected)].reset_index(drop=True)
445
+
446
+
447
+ def _model_numeric_features(diagnostics: dict) -> list:
448
+ blocked = set(diagnostics.get("leakage_candidates", []))
449
+ return [
450
+ column for column in diagnostics.get("numeric_features", [])
451
+ if column not in blocked
452
+ ]
453
+
454
+
455
+ def _boundary_features(diagnostics: dict, model_numeric: list) -> list:
456
+ """Prefer a detected nonlinear feature in the two-dimensional projection."""
457
+ nonlinear = [
458
+ column for column, shape in diagnostics.get("feature_shapes", {}).items()
459
+ if shape == "nonlinear" and column in model_numeric
460
+ ]
461
+ if not nonlinear:
462
+ return model_numeric[:2]
463
+ if len(nonlinear) >= 2:
464
+ return nonlinear[:2]
465
+ curved = nonlinear[0]
466
+ companion = next((column for column in model_numeric if column != curved), None)
467
+ return [companion, curved] if companion is not None else [curved]
468
+
469
+
470
+ def _regression_diagnostic(plt, df, target, feature, tools):
471
+ pairs = pd.DataFrame({"feature": df[feature], "target": df[target]})
472
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
473
+ if len(pairs) < 40 or pairs["feature"].nunique() < 5:
474
+ return None
475
+ if len(pairs) > 3_000:
476
+ pairs = pairs.sample(n=3_000, random_state=42)
477
+ train, validation = tools["train_test_split"](
478
+ pairs, test_size=0.25, random_state=42
479
+ )
480
+ model = tools["LinearRegression"]()
481
+ model.fit(train[["feature"]], train["target"])
482
+ predicted = model.predict(validation[["feature"]])
483
+ score = float(tools["r2_score"](validation["target"], predicted))
484
+
485
+ fig, axes = plt.subplots(1, 2, figsize=(12, 4.6))
486
+ display = pairs.sample(n=min(1_200, len(pairs)), random_state=42)
487
+ axes[0].scatter(display["feature"], display["target"], alpha=0.32, s=14, color="#4C72B0")
488
+ x_values = np.linspace(float(pairs["feature"].min()), float(pairs["feature"].max()), 150)
489
+ axes[0].plot(x_values, model.predict(pd.DataFrame({"feature": x_values})),
490
+ color="#E24A33", linewidth=2.5, label="linear regression")
491
+ axes[0].set_xlabel(_label(feature))
492
+ axes[0].set_ylabel(_label(target))
493
+ axes[0].set_title("Observed relationship and fitted line")
494
+ axes[0].legend()
495
+ residuals = validation["target"].to_numpy() - predicted
496
+ axes[1].scatter(predicted, residuals, alpha=0.38, s=16, color="#55A868")
497
+ axes[1].axhline(0, color="#E24A33", linewidth=2)
498
+ axes[1].set_xlabel("Predicted {}".format(_label(target)))
499
+ axes[1].set_ylabel("Residual")
500
+ axes[1].set_title("Validation residuals")
501
+ fig.suptitle(
502
+ "Linear regression diagnostic · {} · validation R² {:.2f}".format(
503
+ _label(feature), score
504
+ ),
505
+ fontsize=14,
506
+ fontweight="bold",
507
+ )
508
+ fig.tight_layout()
509
+ plt.show()
510
+ record = {
511
+ "model": "linear_regression",
512
+ "features": [feature],
513
+ "rows": int(len(pairs)),
514
+ "validation_metric": "r2",
515
+ "validation_score": round(score, 4),
516
+ "scope": "diagnostic train/validation fit",
517
+ }
518
+ return fig, record
519
+
520
+
521
+ def _logistic_diagnostic(plt, df, target, feature, tools):
522
+ pairs = pd.DataFrame({"feature": df[feature], "target": df[target]})
523
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
524
+ if pairs["target"].nunique() != 2 or pairs["feature"].nunique() < 5:
525
+ return None
526
+ pairs = _bounded_classification_sample(pairs, 3_000)
527
+ codes, labels = pd.factorize(pairs["target"], sort=False)
528
+ if np.bincount(codes).min() < 5:
529
+ return None
530
+ train_x, valid_x, train_y, valid_y = tools["train_test_split"](
531
+ pairs[["feature"]], codes, test_size=0.25, random_state=42, stratify=codes
532
+ )
533
+ model = tools["make_pipeline"](
534
+ tools["StandardScaler"](), tools["LogisticRegression"](max_iter=500)
535
+ )
536
+ model.fit(train_x, train_y)
537
+ score = float(tools["balanced_accuracy_score"](valid_y, model.predict(valid_x)))
538
+ lower, upper = pairs["feature"].quantile([0.01, 0.99])
539
+ if not np.isfinite(lower) or not np.isfinite(upper) or lower == upper:
540
+ return None
541
+ x_values = np.linspace(float(lower), float(upper), 250)
542
+ probabilities = model.predict_proba(pd.DataFrame({"feature": x_values}))[:, 1]
543
+
544
+ fig, ax = plt.subplots(figsize=(9, 5))
545
+ rng = np.random.RandomState(42)
546
+ display = pairs.sample(n=min(1_200, len(pairs)), random_state=42)
547
+ display_codes = pd.Categorical(display["target"], categories=labels).codes
548
+ ax.scatter(display["feature"], display_codes + rng.normal(0, 0.018, len(display)),
549
+ alpha=0.24, s=13, color="#4C72B0", label="observed classes")
550
+ ax.plot(x_values, probabilities, color="#F5A623", linewidth=3, label="logistic probability")
551
+ try:
552
+ bins = pd.qcut(pairs["feature"], q=min(10, pairs["feature"].nunique()), duplicates="drop")
553
+ working = pairs.assign(_event=(pairs["target"] == labels[1]).astype(float), _bin=bins)
554
+ grouped = working.groupby("_bin", observed=True)
555
+ ax.plot(grouped["feature"].mean(), grouped["_event"].mean(), color="#55A868",
556
+ marker="o", linewidth=2, label="binned observed rate")
557
+ except (TypeError, ValueError):
558
+ pass
559
+ ax.set_xlabel(_label(feature))
560
+ ax.set_ylabel("Probability of {}".format(_label(labels[1])))
561
+ ax.set_ylim(-0.08, 1.08)
562
+ ax.set_title(
563
+ "Logistic diagnostic · validation balanced accuracy {:.2f}\n"
564
+ "One-feature visual baseline; final models may use more features".format(score)
565
+ )
566
+ ax.legend()
567
+ fig.tight_layout()
568
+ plt.show()
569
+ record = {
570
+ "model": "logistic_regression",
571
+ "features": [feature],
572
+ "rows": int(len(pairs)),
573
+ "validation_metric": "balanced_accuracy",
574
+ "validation_score": round(score, 4),
575
+ "scope": "one-feature diagnostic train/validation fit",
576
+ }
577
+ return fig, record
578
+
579
+
580
+ def _svm_diagnostic(plt, df, target, features, tools):
581
+ left, right = features[:2]
582
+ pairs = pd.DataFrame({"left": df[left], "right": df[right], "target": df[target]})
583
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
584
+ classes = pairs["target"].nunique()
585
+ if classes < 2 or classes > 6 or pairs["left"].nunique() < 4 or pairs["right"].nunique() < 4:
586
+ return None
587
+ pairs = _bounded_classification_sample(pairs, 2_000)
588
+ codes, labels = pd.factorize(pairs["target"], sort=False)
589
+ if np.bincount(codes).min() < 5:
590
+ return None
591
+ train_x, valid_x, train_y, valid_y = tools["train_test_split"](
592
+ pairs[["left", "right"]], codes, test_size=0.25,
593
+ random_state=42, stratify=codes,
594
+ )
595
+ lower_left, upper_left = pairs["left"].quantile([0.01, 0.99])
596
+ lower_right, upper_right = pairs["right"].quantile([0.01, 0.99])
597
+ if lower_left == upper_left or lower_right == upper_right:
598
+ return None
599
+ x_grid, y_grid = np.meshgrid(
600
+ np.linspace(float(lower_left), float(upper_left), 90),
601
+ np.linspace(float(lower_right), float(upper_right), 90),
602
+ )
603
+ grid = pd.DataFrame({"left": x_grid.ravel(), "right": y_grid.ravel()})
604
+ models = (
605
+ ("linear_svm", "Linear SVM", tools["SVC"](kernel="linear", class_weight="balanced")),
606
+ ("rbf_svm", "Nonlinear RBF-SVM", tools["SVC"](kernel="rbf", class_weight="balanced")),
607
+ )
608
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5))
609
+ records = []
610
+ # Keep extreme values in the fitted diagnostic, but zoom the visual panel
611
+ # to the central 98% so a handful of showcase outliers cannot flatten the
612
+ # decision surface and hide its shape.
613
+ display = pairs.loc[
614
+ pairs["left"].between(lower_left, upper_left)
615
+ & pairs["right"].between(lower_right, upper_right)
616
+ ]
617
+ display = display.sample(n=min(800, len(display)), random_state=42)
618
+ display_codes = pd.Categorical(display["target"], categories=labels).codes
619
+ for ax, (key, title, estimator) in zip(axes, models):
620
+ model = tools["make_pipeline"](tools["StandardScaler"](), estimator)
621
+ model.fit(train_x, train_y)
622
+ score = float(tools["balanced_accuracy_score"](valid_y, model.predict(valid_x)))
623
+ surface = model.predict(grid).reshape(x_grid.shape)
624
+ ax.contourf(x_grid, y_grid, surface, levels=np.arange(classes + 1) - 0.5,
625
+ cmap="Pastel1", alpha=0.72)
626
+ for code, label in enumerate(labels):
627
+ class_rows = display.iloc[np.flatnonzero(display_codes == code)]
628
+ ax.scatter(
629
+ class_rows["left"], class_rows["right"],
630
+ color=plt.cm.tab10(code % 10),
631
+ alpha=0.82,
632
+ s=30 if code else 20,
633
+ edgecolors="white",
634
+ linewidths=0.35,
635
+ label=_label(label),
636
+ zorder=3 + code,
637
+ )
638
+ ax.set_xlabel(_label(left))
639
+ ax.set_ylabel(_label(right))
640
+ ax.set_xlim(float(lower_left), float(upper_left))
641
+ ax.set_ylim(float(lower_right), float(upper_right))
642
+ ax.set_title("{} · balanced accuracy {:.2f}".format(title, score))
643
+ ax.legend(fontsize=8, title=_label(target))
644
+ records.append({
645
+ "model": key,
646
+ "features": [left, right],
647
+ "rows": int(len(pairs)),
648
+ "validation_metric": "balanced_accuracy",
649
+ "validation_score": round(score, 4),
650
+ "scope": "two-feature diagnostic train/validation fit",
651
+ })
652
+ fig.suptitle(
653
+ "Two-feature decision boundaries · diagnostic projection only",
654
+ fontsize=14,
655
+ fontweight="bold",
656
+ )
657
+ fig.tight_layout()
658
+ plt.show()
659
+ return fig, records
660
+
661
+
662
+ def _clustering_diagnostic(plt, df, diagnostics, tools):
663
+ candidates = [
664
+ column for column in diagnostics.get("numeric_features", [])
665
+ if df[column].nunique(dropna=True) >= 10
666
+ and not any(token in _label(column).lower() for token in ("fraud", "churn", "status"))
667
+ ]
668
+ if len(candidates) < 2:
669
+ return None
670
+ candidate_frame = df[candidates[:12]].replace([np.inf, -np.inf], np.nan)
671
+ correlations = candidate_frame.corr().abs().fillna(0)
672
+ connectivity = (correlations.sum() - 1).sort_values(ascending=False)
673
+ selected = []
674
+ for column in connectivity.index:
675
+ if all(correlations.loc[column, existing] < 0.96 for existing in selected):
676
+ selected.append(column)
677
+ if len(selected) == 6:
678
+ break
679
+ if len(selected) < 2:
680
+ return None
681
+ working = candidate_frame[selected].copy()
682
+ working = working.fillna(working.median(numeric_only=True)).dropna(axis=1)
683
+ if working.shape[1] < 2 or len(working) < 50:
684
+ return None
685
+ if len(working) > 3_000:
686
+ working = working.sample(n=3_000, random_state=42)
687
+ scaled = tools["StandardScaler"]().fit_transform(working)
688
+ projection = tools["PCA"](n_components=2, random_state=42).fit_transform(scaled)
689
+ scores = {}
690
+ fitted = {}
691
+ upper_k = min(6, len(working) - 1)
692
+ for clusters in range(2, upper_k + 1):
693
+ model = tools["KMeans"](n_clusters=clusters, n_init=10, random_state=42)
694
+ labels = model.fit_predict(scaled)
695
+ score = float(tools["silhouette_score"](
696
+ scaled, labels, sample_size=min(1_000, len(working)), random_state=42
697
+ ))
698
+ scores[clusters] = score
699
+ fitted[clusters] = labels
700
+ if not scores:
701
+ return None
702
+ best_k = max(scores, key=scores.get)
703
+ labels = fitted[best_k]
704
+ fig, axes = plt.subplots(1, 2, figsize=(12, 4.8))
705
+ axes[0].scatter(projection[:, 0], projection[:, 1], c=labels, cmap="tab10",
706
+ alpha=0.55, s=16)
707
+ axes[0].set_xlabel("PCA component 1")
708
+ axes[0].set_ylabel("PCA component 2")
709
+ axes[0].set_title("K-Means preview · k={}".format(best_k))
710
+ axes[1].plot(list(scores), list(scores.values()), marker="o", color="#4C72B0", linewidth=2)
711
+ axes[1].axvline(best_k, color="#E24A33", linestyle="--", label="best displayed k")
712
+ axes[1].set_xlabel("Number of clusters (k)")
713
+ axes[1].set_ylabel("Silhouette score")
714
+ axes[1].set_title("Cluster separation across k")
715
+ axes[1].legend()
716
+ fig.suptitle(
717
+ "Exploratory clustering diagnostic · scaled sample · validate business meaning",
718
+ fontsize=14,
719
+ fontweight="bold",
720
+ )
721
+ fig.tight_layout()
722
+ plt.show()
723
+ record = {
724
+ "model": "kmeans_pca_preview",
725
+ "features": list(working.columns),
726
+ "rows": int(len(working)),
727
+ "best_k": int(best_k),
728
+ "validation_metric": "silhouette",
729
+ "validation_score": round(scores[best_k], 4),
730
+ "scores_by_k": {int(key): round(value, 4) for key, value in scores.items()},
731
+ "scope": "exploratory unsupervised sample",
732
+ }
733
+ return fig, record
734
+
735
+
377
736
  def render_vizall(
378
737
  df: pd.DataFrame,
379
738
  report: dict,
@@ -393,6 +752,7 @@ def render_vizall(
393
752
  ) from None
394
753
 
395
754
  diagnostics = build_visual_diagnostics(df, report, target=target)
755
+ diagnostic_tools = _sklearn_tools()
396
756
  budget = _PlotBudget(max_plots)
397
757
  figures = []
398
758
  plot_titles = []
@@ -417,6 +777,8 @@ def render_vizall(
417
777
  if target_series is not None and budget.take(1):
418
778
  fig, ax = plt.subplots(figsize=(8, 4.5))
419
779
  observed = target_series.dropna()
780
+ if pd.api.types.is_numeric_dtype(observed.dtype):
781
+ observed = observed.replace([np.inf, -np.inf], np.nan).dropna()
420
782
  if problem_type == "classification":
421
783
  counts = observed.value_counts()
422
784
  counts = counts[counts > 0]
@@ -447,7 +809,8 @@ def render_vizall(
447
809
  fig, axes, grid_columns, grid_rows = _grid(plt, count)
448
810
  for index, column in enumerate(columns_to_plot):
449
811
  ax = axes[index // grid_columns][index % grid_columns]
450
- pairs = pd.DataFrame({"feature": df[column], "target": target_series}).dropna()
812
+ pairs = pd.DataFrame({"feature": df[column], "target": target_series})
813
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
451
814
  if problem_type == "classification":
452
815
  level_counts = pairs["target"].value_counts()
453
816
  levels = list(level_counts[level_counts > 0].head(8).index)
@@ -493,7 +856,8 @@ def render_vizall(
493
856
  fig, axes, grid_columns, grid_rows = _grid(plt, count)
494
857
  for index, column in enumerate(columns_to_plot):
495
858
  ax = axes[index // grid_columns][index % grid_columns]
496
- pairs = pd.DataFrame({"feature": df[column], "target": target_series}).dropna()
859
+ pairs = pd.DataFrame({"feature": df[column], "target": target_series})
860
+ pairs = pairs.replace([np.inf, -np.inf], np.nan).dropna()
497
861
  top_levels = list(pairs["feature"].value_counts().head(12).index)
498
862
  pairs = pairs[pairs["feature"].isin(top_levels)]
499
863
  if problem_type == "classification":
@@ -513,6 +877,52 @@ def render_vizall(
513
877
  _finish_grid(plt, fig, axes, grid_columns, grid_rows, count, title)
514
878
  register(fig, count, title, columns_to_plot)
515
879
 
880
+ # Small diagnostic estimators make model shape visible. They use bounded,
881
+ # deterministic samples and are deliberately labeled as visual baselines.
882
+ model_numeric = _model_numeric_features(diagnostics)
883
+ if diagnostic_tools is None and ((target_series is not None and model_numeric) or target is None):
884
+ diagnostics["observations"].append(
885
+ "Fitted model overlays require scikit-learn; install noweda[viz] or noweda[ml]."
886
+ )
887
+ elif target_series is not None and problem_type == "regression":
888
+ if budget.remaining >= 2 and model_numeric:
889
+ rendered = _regression_diagnostic(
890
+ plt, df, target, model_numeric[0], diagnostic_tools
891
+ )
892
+ if rendered is not None:
893
+ fig, record = rendered
894
+ budget.take(2)
895
+ diagnostics["diagnostic_models"].append(record)
896
+ register(fig, 2, "Linear regression fit and residuals", model_numeric[:1])
897
+ elif target_series is not None and problem_type == "classification":
898
+ classes = target_series.nunique(dropna=True)
899
+ if classes == 2 and budget.remaining >= 1 and model_numeric:
900
+ rendered = _logistic_diagnostic(
901
+ plt, df, target, model_numeric[0], diagnostic_tools
902
+ )
903
+ if rendered is not None:
904
+ fig, record = rendered
905
+ budget.take(1)
906
+ diagnostics["diagnostic_models"].append(record)
907
+ register(fig, 1, "Logistic probability curve", model_numeric[:1])
908
+ boundary_features = _boundary_features(diagnostics, model_numeric)
909
+ if budget.remaining >= 2 and len(boundary_features) >= 2:
910
+ rendered = _svm_diagnostic(
911
+ plt, df, target, boundary_features, diagnostic_tools
912
+ )
913
+ if rendered is not None:
914
+ fig, records = rendered
915
+ budget.take(2)
916
+ diagnostics["diagnostic_models"].extend(records)
917
+ register(fig, 2, "Linear and nonlinear SVM boundaries", boundary_features)
918
+ elif target_series is None and budget.remaining >= 2 and diagnostic_tools is not None:
919
+ rendered = _clustering_diagnostic(plt, df, diagnostics, diagnostic_tools)
920
+ if rendered is not None:
921
+ fig, record = rendered
922
+ budget.take(2)
923
+ diagnostics["diagnostic_models"].append(record)
924
+ register(fig, 2, "PCA and K-Means cluster diagnostic", record["features"])
925
+
516
926
  results = report.get("results", {})
517
927
  missing_columns = [column for column in numeric + categorical + datetime if df[column].isna().any()]
518
928
  if missing_columns and budget.take(1):
@@ -560,7 +970,8 @@ def render_vizall(
560
970
  fig, axes, grid_columns, grid_rows = _grid(plt, count)
561
971
  for index, column in enumerate(columns_to_plot):
562
972
  ax = axes[index // grid_columns][index % grid_columns]
563
- values = df[column].dropna()
973
+ values = pd.to_numeric(df[column], errors="coerce")
974
+ values = values.replace([np.inf, -np.inf], np.nan).dropna()
564
975
  ax.hist(values, bins=30, color="#4C72B0", alpha=0.75, edgecolor="white")
565
976
  ax.set_title(_label(column))
566
977
  ax.set_ylabel("Rows")
@@ -637,7 +1048,7 @@ def render_vizall(
637
1048
  points = pd.DataFrame({
638
1049
  "left": df[left].reset_index(drop=True),
639
1050
  "right": df[right].reset_index(drop=True),
640
- }).dropna()
1051
+ }).replace([np.inf, -np.inf], np.nan).dropna()
641
1052
  if len(points) > 2000:
642
1053
  points = points.sample(n=2000, random_state=42)
643
1054
  ax.scatter(points["left"], points["right"], alpha=0.35, s=14, color="#4C72B0")
@@ -683,8 +1094,10 @@ def render_vizall(
683
1094
  if datetime and numeric and budget.take(1):
684
1095
  date_column = datetime[0]
685
1096
  value_column = target if target is not None and problem_type == "regression" else numeric[0]
686
- points = pd.DataFrame({"date": pd.to_datetime(df[date_column], errors="coerce"),
687
- "value": df[value_column]}).dropna().sort_values("date")
1097
+ points = pd.DataFrame({
1098
+ "date": pd.to_datetime(df[date_column], errors="coerce"),
1099
+ "value": df[value_column],
1100
+ }).replace([np.inf, -np.inf], np.nan).dropna().sort_values("date")
688
1101
  if not points.empty:
689
1102
  fig, ax = plt.subplots(figsize=(11, 4))
690
1103
  ax.plot(points["date"], points["value"], color="#4C72B0", linewidth=1)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: noweda
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Automated EDA with insights, scoring, and security-aware detection — built as a native pandas extension.
5
5
  Author-email: Daniel Peng <danielpeng95@gmail.com>
6
6
  License: MIT
@@ -38,6 +38,7 @@ Requires-Dist: odfpy>=1.4.1; extra == "excel"
38
38
  Provides-Extra: viz
39
39
  Requires-Dist: matplotlib>=3.5; extra == "viz"
40
40
  Requires-Dist: scipy>=1.7; extra == "viz"
41
+ Requires-Dist: scikit-learn>=1.0; extra == "viz"
41
42
  Provides-Extra: ml
42
43
  Requires-Dist: statsmodels>=0.13; extra == "ml"
43
44
  Requires-Dist: scikit-learn>=1.0; extra == "ml"
@@ -46,6 +47,7 @@ Requires-Dist: pytest>=7; extra == "test"
46
47
  Requires-Dist: odfpy>=1.4.1; extra == "test"
47
48
  Requires-Dist: matplotlib>=3.5; extra == "test"
48
49
  Requires-Dist: scipy>=1.7; extra == "test"
50
+ Requires-Dist: scikit-learn>=1.0; extra == "test"
49
51
  Provides-Extra: hdf
50
52
  Requires-Dist: tables>=3.7; extra == "hdf"
51
53
  Provides-Extra: spss
@@ -203,6 +205,8 @@ missingness, outliers, feature scales, and applicable temporal plots. Supply the
203
205
  prediction target to add classification or regression diagnostics. NowEDA ranks
204
206
  useful features, excludes likely identifiers and detected PII, and describes
205
207
  model-family signals without claiming that a chart proves the best model.
208
+ Where applicable, it fits bounded visual baselines for linear regression,
209
+ logistic probability, linear and nonlinear SVM boundaries, and K-Means.
206
210
 
207
211
  ```python
208
212
  df.eda.vizall() # General and unsupervised structure
@@ -212,6 +216,7 @@ visuals = df.eda.vizall(
212
216
  max_plots=15,
213
217
  )
214
218
  print(visuals["model_signals"])
219
+ print(visuals["diagnostic_models"])
215
220
 
216
221
  df.eda.vizall(sample=5_000) # Optional bounded sample
217
222
  ```
@@ -284,7 +289,7 @@ df = eda.read("data.csv", dtype={"customer_id": str})
284
289
  | Parquet, Feather, ORC | Included with `pip install noweda` |
285
290
  | HDF5 | `pip install "noweda[hdf]"` |
286
291
  | SPSS | `pip install "noweda[spss]"` |
287
- | Charts and KDE overlays | `pip install "noweda[viz]"` |
292
+ | Charts, KDE overlays, and fitted visual diagnostics | `pip install "noweda[viz]"` |
288
293
  | Stationarity and seasonality dependencies | `pip install "noweda[ml]"` |
289
294
  | All optional analysis and format dependencies | `pip install "noweda[full]"` |
290
295
 
@@ -37,7 +37,9 @@ pytest>=7
37
37
  odfpy>=1.4.1
38
38
  matplotlib>=3.5
39
39
  scipy>=1.7
40
+ scikit-learn>=1.0
40
41
 
41
42
  [viz]
42
43
  matplotlib>=3.5
43
44
  scipy>=1.7
45
+ scikit-learn>=1.0
@@ -34,9 +34,9 @@ dependencies = [
34
34
 
35
35
  [project.optional-dependencies]
36
36
  excel = ["xlrd>=2.0.1", "pyxlsb>=1.0.10", "odfpy>=1.4.1"]
37
- viz = ["matplotlib>=3.5", "scipy>=1.7"]
37
+ viz = ["matplotlib>=3.5", "scipy>=1.7", "scikit-learn>=1.0"]
38
38
  ml = ["statsmodels>=0.13", "scikit-learn>=1.0"]
39
- test = ["pytest>=7", "odfpy>=1.4.1", "matplotlib>=3.5", "scipy>=1.7"]
39
+ test = ["pytest>=7", "odfpy>=1.4.1", "matplotlib>=3.5", "scipy>=1.7", "scikit-learn>=1.0"]
40
40
  hdf = ["tables>=3.7"] # .h5, .hdf5
41
41
  spss = ["pyreadstat>=1.1"] # .sav, .zsav
42
42
  full = [
@@ -1,6 +1,9 @@
1
+ import warnings
2
+
1
3
  import numpy as np
2
4
  import pandas as pd
3
5
  import pytest
6
+ import noweda # noqa: F401 # Register the pandas accessors for isolated runs.
4
7
 
5
8
 
6
9
  pytest.importorskip("matplotlib")
@@ -46,6 +49,77 @@ def test_vizall_returns_ranked_classification_diagnostics():
46
49
  assert len(result["figures"]) <= result["plots_generated"]
47
50
 
48
51
 
52
+ def test_vizall_fits_logistic_and_svm_visual_baselines():
53
+ pytest.importorskip("sklearn")
54
+ frame = _classification_frame(rows=360)
55
+
56
+ result = frame.eda.vizall(target="fraud_flag", max_plots=10)
57
+
58
+ models = {item["model"] for item in result["diagnostic_models"]}
59
+ assert {"logistic_regression", "linear_svm", "rbf_svm"} <= models
60
+ assert "Logistic probability curve" in result["plot_titles"]
61
+ assert "Linear and nonlinear SVM boundaries" in result["plot_titles"]
62
+ assert all("validation_score" in item for item in result["diagnostic_models"])
63
+
64
+
65
+ def test_vizall_prefers_nonlinear_feature_for_svm_boundary():
66
+ pytest.importorskip("sklearn")
67
+ rng = np.random.RandomState(17)
68
+ rows = 2_000
69
+ linear = rng.normal(size=rows)
70
+ curved = rng.normal(size=rows)
71
+ target = ((linear ** 2 + curved ** 2) > 2.0).astype(int)
72
+ frame = pd.DataFrame({
73
+ "linear_feature": linear,
74
+ "curved_feature": curved,
75
+ "target": target,
76
+ })
77
+
78
+ result = frame.eda.vizall(target="target", max_plots=10)
79
+
80
+ assert "nonlinear" in result["feature_shapes"].values()
81
+ svm_models = [
82
+ item for item in result["diagnostic_models"]
83
+ if item["model"] in {"linear_svm", "rbf_svm"}
84
+ ]
85
+ assert svm_models
86
+ assert all(
87
+ any(result["feature_shapes"].get(feature) == "nonlinear" for feature in item["features"])
88
+ for item in svm_models
89
+ )
90
+
91
+
92
+ def test_vizall_fitted_diagnostics_ignore_nonfinite_rows():
93
+ pytest.importorskip("sklearn")
94
+ frame = _classification_frame(rows=400)
95
+ frame.loc[0, "linear_signal"] = np.inf
96
+ frame.loc[1, "curved_signal"] = -np.inf
97
+
98
+ with warnings.catch_warnings():
99
+ warnings.simplefilter("ignore", RuntimeWarning)
100
+ result = frame.eda.vizall(target="fraud_flag", max_plots=10)
101
+
102
+ assert result["diagnostic_models"]
103
+ assert all(np.isfinite(item["validation_score"]) for item in result["diagnostic_models"])
104
+
105
+
106
+ def test_vizall_regression_ignores_nonfinite_target_rows():
107
+ pytest.importorskip("sklearn")
108
+ rng = np.random.RandomState(23)
109
+ feature = np.linspace(-3, 3, 300)
110
+ target = 2.5 * feature + rng.normal(scale=2.0, size=len(feature))
111
+ target[[0, 1]] = [np.inf, -np.inf]
112
+ frame = pd.DataFrame({"feature": feature, "target": target})
113
+
114
+ with warnings.catch_warnings():
115
+ warnings.simplefilter("ignore", RuntimeWarning)
116
+ result = frame.eda.vizall(target="target", max_plots=5)
117
+
118
+ assert result["target_summary"]["observed"] == 298
119
+ assert result["diagnostic_models"][0]["model"] == "linear_regression"
120
+ assert np.isfinite(result["diagnostic_models"][0]["validation_score"])
121
+
122
+
49
123
  def test_vizall_returns_regression_relationships_and_signals():
50
124
  rng = np.random.RandomState(11)
51
125
  feature = np.linspace(-3, 3, 240)
@@ -61,9 +135,35 @@ def test_vizall_returns_regression_relationships_and_signals():
61
135
  assert "Regression target distribution" in result["plot_titles"]
62
136
  assert result["associations"][0]["column"] == "feature"
63
137
  assert any("linear regression" in signal for signal in result["model_signals"])
138
+ assert result["diagnostic_models"][0]["model"] == "linear_regression"
139
+ assert "Linear regression fit and residuals" in result["plot_titles"]
64
140
  assert result["plots_generated"] <= 5
65
141
 
66
142
 
143
+ def test_vizall_adds_exploratory_kmeans_projection_without_target():
144
+ pytest.importorskip("sklearn")
145
+ rng = np.random.RandomState(21)
146
+ rows = []
147
+ for center in [(-4, -4), (0, 4), (4, -2)]:
148
+ cloud = rng.normal(loc=center, scale=0.45, size=(100, 2))
149
+ rows.append(cloud)
150
+ points = np.vstack(rows)
151
+ frame = pd.DataFrame({
152
+ "feature_one": points[:, 0],
153
+ "feature_two": points[:, 1],
154
+ "feature_three": points[:, 0] + rng.normal(scale=0.2, size=len(points)),
155
+ })
156
+
157
+ result = frame.eda.vizall(max_plots=2)
158
+
159
+ assert result["plot_titles"] == ["PCA and K-Means cluster diagnostic"]
160
+ assert result["plots_generated"] == 2
161
+ diagnostic = result["diagnostic_models"][0]
162
+ assert diagnostic["model"] == "kmeans_pca_preview"
163
+ assert diagnostic["validation_metric"] == "silhouette"
164
+ assert 2 <= diagnostic["best_k"] <= 6
165
+
166
+
67
167
  def test_vizall_plot_budget_counts_panels_not_only_figures():
68
168
  frame = _classification_frame()
69
169
 
@@ -150,6 +250,29 @@ def test_vizall_flags_near_deterministic_features_as_possible_leakage():
150
250
  assert any("Possible target leakage" in signal for signal in result["model_signals"])
151
251
 
152
252
 
253
+ def test_vizall_excludes_leakage_from_fitted_diagnostics():
254
+ pytest.importorskip("sklearn")
255
+ rng = np.random.RandomState(4)
256
+ signal_one = rng.normal(size=300)
257
+ signal_two = rng.normal(size=300)
258
+ target = (signal_one + 0.4 * signal_two > 0).astype(int)
259
+ frame = pd.DataFrame({
260
+ "target_probability": target.astype(float),
261
+ "signal_one": signal_one,
262
+ "signal_two": signal_two,
263
+ "target": target,
264
+ })
265
+
266
+ result = frame.eda.vizall(target="target", max_plots=10)
267
+
268
+ assert "target_probability" in result["leakage_candidates"]
269
+ assert result["diagnostic_models"]
270
+ assert all(
271
+ "target_probability" not in item["features"]
272
+ for item in result["diagnostic_models"]
273
+ )
274
+
275
+
153
276
  def test_vizall_ignores_unused_target_categories_for_imbalance():
154
277
  labels = pd.Categorical(["a", "b"] * 40, categories=["a", "b", "unused"])
155
278
  frame = pd.DataFrame({"feature": np.arange(80), "target": labels})
@@ -1 +0,0 @@
1
- __version__ = "0.2.2"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes