p2predict 1.2.0__tar.gz → 1.3.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.
- {p2predict-1.2.0/src/p2predict.egg-info → p2predict-1.3.0}/PKG-INFO +2 -3
- {p2predict-1.2.0 → p2predict-1.3.0}/pyproject.toml +2 -3
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/mcp/server.py +72 -31
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/preprocessing.py +25 -5
- {p2predict-1.2.0 → p2predict-1.3.0/src/p2predict.egg-info}/PKG-INFO +2 -3
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_mcp.py +93 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_preprocessing.py +33 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/LICENSE +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/README.md +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/setup.cfg +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/__init__.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/__main__.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/cli/__init__.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/cli/predict.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/cli/train.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/cmdline_io.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/domain.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/explain.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/feature_selection.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/hpo_training.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/input_checks.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/intervals.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/json_output.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/mcp/__init__.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/mcp/__main__.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/mcp/conversions.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/mcp/registry.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/model_evals.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/model_utils.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/outliers.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/plotting.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/prepare_data.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/quality.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/trained_model_io.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/training.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/ui_console.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict/whatif.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict.egg-info/SOURCES.txt +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict.egg-info/dependency_links.txt +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict.egg-info/entry_points.txt +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict.egg-info/requires.txt +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/src/p2predict.egg-info/top_level.txt +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_benchmarks.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_cli.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_domain.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_explain.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_feature_selection.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_feature_selection_leakage.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_input_checks.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_intervals.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_io_and_evals.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_json_output.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_outliers.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_plotting.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_prepare_data.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_quality.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_training.py +0 -0
- {p2predict-1.2.0 → p2predict-1.3.0}/tests/test_whatif.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: p2predict
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.0
|
|
4
4
|
Summary: Parametric price benchmarking for engineering and procurement trade-offs. Agentic first, runs on your data, stays on your machine.
|
|
5
5
|
Author: Ahmed Khalil Hafsi
|
|
6
6
|
License-Expression: LicenseRef-PolyForm-Noncommercial-1.0.0-with-Internal-Use-Exception
|
|
@@ -16,14 +16,13 @@ Classifier: Intended Audience :: Financial and Insurance Industry
|
|
|
16
16
|
Classifier: Intended Audience :: Science/Research
|
|
17
17
|
Classifier: Operating System :: OS Independent
|
|
18
18
|
Classifier: Programming Language :: Python :: 3
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
20
19
|
Classifier: Programming Language :: Python :: 3.11
|
|
21
20
|
Classifier: Programming Language :: Python :: 3.12
|
|
22
21
|
Classifier: Programming Language :: Python :: 3.13
|
|
23
22
|
Classifier: Programming Language :: Python :: 3.14
|
|
24
23
|
Classifier: Topic :: Scientific/Engineering
|
|
25
24
|
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
26
|
-
Requires-Python: <3.15,>=3.
|
|
25
|
+
Requires-Python: <3.15,>=3.11
|
|
27
26
|
Description-Content-Type: text/markdown
|
|
28
27
|
License-File: LICENSE
|
|
29
28
|
Requires-Dist: click>=8.1
|
|
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "p2predict"
|
|
7
|
-
version = "1.
|
|
7
|
+
version = "1.3.0"
|
|
8
8
|
description = "Parametric price benchmarking for engineering and procurement trade-offs. Agentic first, runs on your data, stays on your machine."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "LicenseRef-PolyForm-Noncommercial-1.0.0-with-Internal-Use-Exception"
|
|
11
11
|
license-files = ["LICENSE"]
|
|
12
12
|
authors = [{name = "Ahmed Khalil Hafsi"}]
|
|
13
|
-
requires-python = ">=3.
|
|
13
|
+
requires-python = ">=3.11,<3.15"
|
|
14
14
|
keywords = [
|
|
15
15
|
"procurement",
|
|
16
16
|
"price-prediction",
|
|
@@ -30,7 +30,6 @@ classifiers = [
|
|
|
30
30
|
"Intended Audience :: Science/Research",
|
|
31
31
|
"Operating System :: OS Independent",
|
|
32
32
|
"Programming Language :: Python :: 3",
|
|
33
|
-
"Programming Language :: Python :: 3.10",
|
|
34
33
|
"Programming Language :: Python :: 3.11",
|
|
35
34
|
"Programming Language :: Python :: 3.12",
|
|
36
35
|
"Programming Language :: Python :: 3.13",
|
|
@@ -770,12 +770,20 @@ async def predict_from_csv(
|
|
|
770
770
|
|
|
771
771
|
def _prepare_training_data(
|
|
772
772
|
csv_path: str, target: str, outlier_policy: str, feature_outlier_policy: str,
|
|
773
|
+
features: list[str] | None = None, max_features: int = 6,
|
|
774
|
+
allow_leaky: bool = False,
|
|
773
775
|
) -> dict:
|
|
774
|
-
"""Load a training CSV and apply the outlier policies,
|
|
775
|
-
does. `propose_training_plan` runs the same steps so the
|
|
776
|
-
are the ones `train` will pick for the same arguments.
|
|
776
|
+
"""Load a training CSV, pick the specs and apply the outlier policies,
|
|
777
|
+
exactly as `train` does. `propose_training_plan` runs the same steps so the
|
|
778
|
+
specs it proposes are the ones `train` will pick for the same arguments.
|
|
779
|
+
|
|
780
|
+
The specs are chosen before the feature-outlier policy runs, and the
|
|
781
|
+
policy only looks at the chosen numeric specs. A leaky, ID-like or
|
|
782
|
+
unselected column never reaches the model, so its outliers must neither
|
|
783
|
+
be reported nor drop rows."""
|
|
777
784
|
import pandas as pd
|
|
778
785
|
|
|
786
|
+
from p2predict.feature_selection import choose_training_features
|
|
779
787
|
from p2predict.outliers import (
|
|
780
788
|
apply_feature_outlier_policy,
|
|
781
789
|
apply_outlier_policy,
|
|
@@ -798,27 +806,61 @@ def _prepare_training_data(
|
|
|
798
806
|
if data.empty:
|
|
799
807
|
raise ValueError(f"All rows have missing values in target '{target}'.")
|
|
800
808
|
|
|
801
|
-
data,
|
|
809
|
+
data, price_outliers = apply_outlier_policy(data, target, policy=outlier_policy)
|
|
802
810
|
|
|
803
|
-
|
|
804
|
-
|
|
811
|
+
choice = choose_training_features(
|
|
812
|
+
data, target, features, max_features=max_features, allow_leaky=allow_leaky,
|
|
813
|
+
)
|
|
814
|
+
numeric_specs = [
|
|
815
|
+
c for c in choice.selected if pd.api.types.is_numeric_dtype(data[c])
|
|
805
816
|
]
|
|
806
817
|
# Inspect BEFORE applying the policy, so the report describes the data
|
|
807
818
|
# the user actually handed us rather than the treated copy.
|
|
808
819
|
uncapped_data = data
|
|
809
|
-
feature_quality = describe_feature_outliers(data,
|
|
820
|
+
feature_quality = describe_feature_outliers(data, numeric_specs)
|
|
810
821
|
data, feature_outlier_summary = apply_feature_outlier_policy(
|
|
811
|
-
data,
|
|
822
|
+
data, numeric_specs, policy=feature_outlier_policy
|
|
812
823
|
)
|
|
813
824
|
feature_quality["policy_applied"] = feature_outlier_summary["applied"]
|
|
814
825
|
return {
|
|
815
826
|
"data": data,
|
|
816
827
|
"uncapped_data": uncapped_data,
|
|
817
828
|
"rows_loaded": rows_loaded,
|
|
829
|
+
"choice": choice,
|
|
818
830
|
"feature_quality": feature_quality,
|
|
831
|
+
"price_outliers": _price_outlier_block(price_outliers),
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def _price_outlier_block(summary: dict) -> dict:
|
|
836
|
+
"""JSON-safe form of `apply_outlier_policy`'s summary. Bounds are null when
|
|
837
|
+
the price column had no finite values to compute them from."""
|
|
838
|
+
def _bound(v):
|
|
839
|
+
return None if v is None or v != v else float(v)
|
|
840
|
+
|
|
841
|
+
return {
|
|
842
|
+
"n_outliers": int(summary["n_outliers"]),
|
|
843
|
+
"n_total": int(summary["n_total"]),
|
|
844
|
+
"lower": _bound(summary["lower"]),
|
|
845
|
+
"upper": _bound(summary["upper"]),
|
|
846
|
+
"policy": summary["policy"],
|
|
847
|
+
"policy_applied": summary["applied"],
|
|
819
848
|
}
|
|
820
849
|
|
|
821
850
|
|
|
851
|
+
def _price_outlier_warning(target: str, block: dict) -> str | None:
|
|
852
|
+
"""Plain-language warning for target outliers left in under 'warn'."""
|
|
853
|
+
if block["policy"] != "warn" or block["n_outliers"] == 0:
|
|
854
|
+
return None
|
|
855
|
+
return (
|
|
856
|
+
f"{block['n_outliers']} of {block['n_total']} rows have a '{target}' far "
|
|
857
|
+
f"outside the rest (outside {block['lower']:.4g} to {block['upper']:.4g}) "
|
|
858
|
+
"— often rush orders, spot buys or data-entry errors. They were kept. "
|
|
859
|
+
"Re-run with outlier_policy='drop' or 'winsorize' if they shouldn't "
|
|
860
|
+
"shape the model."
|
|
861
|
+
)
|
|
862
|
+
|
|
863
|
+
|
|
822
864
|
@mcp.tool()
|
|
823
865
|
async def propose_training_plan(
|
|
824
866
|
csv_path: str,
|
|
@@ -848,20 +890,19 @@ async def propose_training_plan(
|
|
|
848
890
|
def _do_plan() -> dict:
|
|
849
891
|
import pandas as pd
|
|
850
892
|
|
|
851
|
-
from p2predict.feature_selection import choose_training_features
|
|
852
|
-
from p2predict.outliers import describe_feature_outliers
|
|
853
893
|
from p2predict.training import resolve_log_target
|
|
854
894
|
|
|
895
|
+
# Same chooser as `train` and the CLI, on the same prepared data, so
|
|
896
|
+
# the plan's specs are exactly what training will use.
|
|
855
897
|
prepared = _prepare_training_data(
|
|
856
|
-
csv_path, target, outlier_policy, feature_outlier_policy
|
|
898
|
+
csv_path, target, outlier_policy, feature_outlier_policy,
|
|
899
|
+
max_features=max_features,
|
|
857
900
|
)
|
|
858
901
|
data = prepared["data"]
|
|
859
902
|
rows_loaded = prepared["rows_loaded"]
|
|
860
903
|
y = pd.to_numeric(data[target], errors="coerce").dropna()
|
|
861
904
|
|
|
862
|
-
|
|
863
|
-
# the plan's specs are exactly what training will use.
|
|
864
|
-
choice = choose_training_features(data, target, max_features=max_features)
|
|
905
|
+
choice = prepared["choice"]
|
|
865
906
|
selected = choice.selected
|
|
866
907
|
excluded = choice.excluded
|
|
867
908
|
leaky = [e for e in excluded if e["kind"] == "leakage"]
|
|
@@ -870,12 +911,8 @@ async def propose_training_plan(
|
|
|
870
911
|
# CLI reports this; before v1.2 the agent path did not, so an agent had
|
|
871
912
|
# no way to know a column needed handling and never set
|
|
872
913
|
# feature_outlier_policy. See research/feature_outlier_visibility.md.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
]
|
|
876
|
-
outlier_report = describe_feature_outliers(
|
|
877
|
-
prepared["uncapped_data"], numeric_specs
|
|
878
|
-
)
|
|
914
|
+
outlier_report = prepared["feature_quality"]
|
|
915
|
+
price_outliers = prepared["price_outliers"]
|
|
879
916
|
|
|
880
917
|
# Log-target recommendation.
|
|
881
918
|
_, auto_decision = resolve_log_target(y, mode="auto")
|
|
@@ -899,6 +936,7 @@ async def propose_training_plan(
|
|
|
899
936
|
)
|
|
900
937
|
for flagged in outlier_report["extreme_magnitude"]:
|
|
901
938
|
questions.append(flagged["say_to_user"])
|
|
939
|
+
price_warning = _price_outlier_warning(target, price_outliers)
|
|
902
940
|
|
|
903
941
|
plain_summary = (
|
|
904
942
|
f"I found {rows_loaded} rows. I can build a model that estimates "
|
|
@@ -922,6 +960,8 @@ async def propose_training_plan(
|
|
|
922
960
|
"log_target_auto_decision": auto_decision,
|
|
923
961
|
"rows_available": rows_loaded,
|
|
924
962
|
"feature_data_quality": outlier_report,
|
|
963
|
+
"price_outliers": price_outliers,
|
|
964
|
+
"warnings": [price_warning] if price_warning else [],
|
|
925
965
|
"questions_for_the_user": questions,
|
|
926
966
|
"to_proceed": (
|
|
927
967
|
"After the user confirms, call train(csv_path, target, "
|
|
@@ -985,10 +1025,7 @@ async def train(
|
|
|
985
1025
|
|
|
986
1026
|
def _do_train() -> dict:
|
|
987
1027
|
from p2predict import auto_train, Serialize_Trained_Model, save_model
|
|
988
|
-
from p2predict.feature_selection import
|
|
989
|
-
choose_training_features,
|
|
990
|
-
find_leaky_features,
|
|
991
|
-
)
|
|
1028
|
+
from p2predict.feature_selection import find_leaky_features
|
|
992
1029
|
from p2predict.intervals import compute_calibration_residuals
|
|
993
1030
|
from p2predict.model_evals import evaluate_model
|
|
994
1031
|
from p2predict.prepare_data import prepare_data
|
|
@@ -998,18 +1035,27 @@ async def train(
|
|
|
998
1035
|
start_training,
|
|
999
1036
|
)
|
|
1000
1037
|
|
|
1038
|
+
# Same chooser as the CLI and propose_training_plan: auto-selection
|
|
1039
|
+
# never picks a leakage, ID-like or single-value column.
|
|
1001
1040
|
prepared = _prepare_training_data(
|
|
1002
|
-
csv_path, target, outlier_policy, feature_outlier_policy
|
|
1041
|
+
csv_path, target, outlier_policy, feature_outlier_policy,
|
|
1042
|
+
features=features, max_features=max_features,
|
|
1043
|
+
allow_leaky=allow_leaky_features,
|
|
1003
1044
|
)
|
|
1004
1045
|
data = prepared["data"]
|
|
1005
1046
|
uncapped_data = prepared["uncapped_data"]
|
|
1006
1047
|
rows_loaded = prepared["rows_loaded"]
|
|
1007
1048
|
feature_quality = prepared["feature_quality"]
|
|
1049
|
+
price_outliers = prepared["price_outliers"]
|
|
1050
|
+
choice = prepared["choice"]
|
|
1008
1051
|
# Under winsorize the model learns and applies the caps itself, so
|
|
1009
1052
|
# training runs on the uncapped rows; see FeatureClipper.
|
|
1010
1053
|
winsorize_features = feature_outlier_policy == "winsorize"
|
|
1011
1054
|
|
|
1012
1055
|
warnings: list[str] = []
|
|
1056
|
+
price_warning = _price_outlier_warning(target, price_outliers)
|
|
1057
|
+
if price_warning:
|
|
1058
|
+
warnings.append(price_warning)
|
|
1013
1059
|
for flagged in feature_quality["extreme_magnitude"]:
|
|
1014
1060
|
warnings.append(
|
|
1015
1061
|
f"'{flagged['column']}' contains a value far outside the rest of "
|
|
@@ -1021,12 +1067,6 @@ async def train(
|
|
|
1021
1067
|
)
|
|
1022
1068
|
leaky = find_leaky_features(data, target)
|
|
1023
1069
|
|
|
1024
|
-
# Same chooser as the CLI and propose_training_plan: auto-selection
|
|
1025
|
-
# never picks a leakage, ID-like or single-value column.
|
|
1026
|
-
choice = choose_training_features(
|
|
1027
|
-
data, target, features, max_features=max_features,
|
|
1028
|
-
allow_leaky=allow_leaky_features,
|
|
1029
|
-
)
|
|
1030
1070
|
if choice.leaky_requested:
|
|
1031
1071
|
# Stop and ask rather than train a confidently-wrong model.
|
|
1032
1072
|
return {
|
|
@@ -1156,6 +1196,7 @@ async def train(
|
|
|
1156
1196
|
"calibration_size": calibration.get("n_calibration"),
|
|
1157
1197
|
"excluded_leaky_features": leaky,
|
|
1158
1198
|
"feature_data_quality": feature_quality,
|
|
1199
|
+
"price_outliers": price_outliers,
|
|
1159
1200
|
"warnings": warnings,
|
|
1160
1201
|
}
|
|
1161
1202
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
|
|
1
3
|
import numpy as np
|
|
2
4
|
from sklearn.base import BaseEstimator, TransformerMixin
|
|
3
5
|
from sklearn.compose import ColumnTransformer
|
|
@@ -21,6 +23,12 @@ _NAN_NATIVE = {"xgboost"}
|
|
|
21
23
|
# fixes in v0.9.x restored elsewhere.
|
|
22
24
|
_TARGET_ENCODER_FOLDS = 5
|
|
23
25
|
_TARGET_ENCODER_SEED = 0
|
|
26
|
+
# scikit-learn 1.9+ marks TargetEncoder.random_state as deprecated (its default
|
|
27
|
+
# becomes the string "deprecated") and wants the seed on a CV splitter instead.
|
|
28
|
+
_TARGET_ENCODER_TAKES_SPLITTER = (
|
|
29
|
+
inspect.signature(TargetEncoder.__init__).parameters["random_state"].default
|
|
30
|
+
== "deprecated"
|
|
31
|
+
)
|
|
24
32
|
|
|
25
33
|
|
|
26
34
|
class FeatureClipper(TransformerMixin, BaseEstimator):
|
|
@@ -75,9 +83,12 @@ class _AdaptiveTargetEncoder(TargetEncoder):
|
|
|
75
83
|
selection. ``transform`` is unaffected — it always uses the full-data
|
|
76
84
|
category means computed by ``fit``.
|
|
77
85
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
86
|
+
The fold shuffle is seeded so training is reproducible. scikit-learn
|
|
87
|
+
1.5–1.8 only accept an int ``cv``, so there the seed goes through the
|
|
88
|
+
encoder's own ``random_state``. scikit-learn 1.9 deprecated that argument
|
|
89
|
+
(removed in 1.11) and warns on every fit, so there we pass the same seeded
|
|
90
|
+
``KFold`` as ``cv`` instead. Both give identical folds: for a continuous
|
|
91
|
+
target ``TargetEncoder`` builds exactly that ``KFold`` from the int.
|
|
81
92
|
"""
|
|
82
93
|
|
|
83
94
|
def fit_transform(self, X, y=None, **fit_params):
|
|
@@ -85,7 +96,15 @@ class _AdaptiveTargetEncoder(TargetEncoder):
|
|
|
85
96
|
if n < 2:
|
|
86
97
|
# Nothing to cross-fit; fall back to the plain fit+transform.
|
|
87
98
|
return self.fit(X, y).transform(X)
|
|
88
|
-
|
|
99
|
+
n_splits = min(_TARGET_ENCODER_FOLDS, n)
|
|
100
|
+
if _TARGET_ENCODER_TAKES_SPLITTER:
|
|
101
|
+
from sklearn.model_selection import KFold
|
|
102
|
+
|
|
103
|
+
self.cv = KFold(
|
|
104
|
+
n_splits=n_splits, shuffle=True, random_state=_TARGET_ENCODER_SEED
|
|
105
|
+
)
|
|
106
|
+
else:
|
|
107
|
+
self.cv = n_splits
|
|
89
108
|
return super().fit_transform(X, y, **fit_params)
|
|
90
109
|
|
|
91
110
|
|
|
@@ -115,7 +134,8 @@ def _target_encoder():
|
|
|
115
134
|
("impute", SimpleImputer(strategy="most_frequent")),
|
|
116
135
|
("target", _AdaptiveTargetEncoder(
|
|
117
136
|
target_type="continuous", smooth="auto",
|
|
118
|
-
|
|
137
|
+
**({} if _TARGET_ENCODER_TAKES_SPLITTER
|
|
138
|
+
else {"random_state": _TARGET_ENCODER_SEED}))),
|
|
119
139
|
]
|
|
120
140
|
)
|
|
121
141
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: p2predict
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.0
|
|
4
4
|
Summary: Parametric price benchmarking for engineering and procurement trade-offs. Agentic first, runs on your data, stays on your machine.
|
|
5
5
|
Author: Ahmed Khalil Hafsi
|
|
6
6
|
License-Expression: LicenseRef-PolyForm-Noncommercial-1.0.0-with-Internal-Use-Exception
|
|
@@ -16,14 +16,13 @@ Classifier: Intended Audience :: Financial and Insurance Industry
|
|
|
16
16
|
Classifier: Intended Audience :: Science/Research
|
|
17
17
|
Classifier: Operating System :: OS Independent
|
|
18
18
|
Classifier: Programming Language :: Python :: 3
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
20
19
|
Classifier: Programming Language :: Python :: 3.11
|
|
21
20
|
Classifier: Programming Language :: Python :: 3.12
|
|
22
21
|
Classifier: Programming Language :: Python :: 3.13
|
|
23
22
|
Classifier: Programming Language :: Python :: 3.14
|
|
24
23
|
Classifier: Topic :: Scientific/Engineering
|
|
25
24
|
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
26
|
-
Requires-Python: <3.15,>=3.
|
|
25
|
+
Requires-Python: <3.15,>=3.11
|
|
27
26
|
Description-Content-Type: text/markdown
|
|
28
27
|
License-File: LICENSE
|
|
29
28
|
Requires-Dist: click>=8.1
|
|
@@ -972,3 +972,96 @@ async def test_train_winsorize_caps_apply_when_predicting(registry, tmp_path, sy
|
|
|
972
972
|
rows = pd.DataFrame({"Weight": [15.0, 15.0], "Wide_Range_Spec": [1e3, 3.6e31]})
|
|
973
973
|
low, absurd = model.predict(rows)
|
|
974
974
|
assert low == absurd
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
# ---------------------------------------------------------------------------
|
|
978
|
+
# Outlier scans cover only what the model trains on, and price outliers are
|
|
979
|
+
# reported back. A leaky, ID-like or unselected column never reaches the
|
|
980
|
+
# model, so its outliers must not be reported and must not drop rows.
|
|
981
|
+
# ---------------------------------------------------------------------------
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
def _price_spike_frame(synthetic_parts):
|
|
985
|
+
"""Synthetic data where the first five prices are far above the rest."""
|
|
986
|
+
df = synthetic_parts.copy()
|
|
987
|
+
df.loc[:4, "Price"] = df["Price"].max() * 50
|
|
988
|
+
return df
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
@pytest.mark.asyncio
|
|
992
|
+
async def test_leaky_column_outliers_are_not_reported_and_drop_no_rows(
|
|
993
|
+
registry, tmp_path, synthetic_parts
|
|
994
|
+
):
|
|
995
|
+
clean = _price_spike_frame(synthetic_parts)
|
|
996
|
+
leaky = clean.copy()
|
|
997
|
+
# A near-copy of the price: it carries the same five spikes as outliers.
|
|
998
|
+
leaky["Price_at_1k"] = leaky["Price"] * 0.5 + np.random.default_rng(0).normal(
|
|
999
|
+
0, 0.005, len(leaky)
|
|
1000
|
+
)
|
|
1001
|
+
clean_csv, leaky_csv = tmp_path / "clean.csv", tmp_path / "leaky.csv"
|
|
1002
|
+
clean.to_csv(clean_csv, index=False)
|
|
1003
|
+
leaky.to_csv(leaky_csv, index=False)
|
|
1004
|
+
|
|
1005
|
+
kwargs = dict(
|
|
1006
|
+
target="Price", outlier_policy="keep", feature_outlier_policy="drop",
|
|
1007
|
+
)
|
|
1008
|
+
trained = _parse(await mcp_server.train(
|
|
1009
|
+
csv_path=str(leaky_csv), algorithm="ridge", budget="fast", **kwargs,
|
|
1010
|
+
))
|
|
1011
|
+
baseline = _parse(await mcp_server.train(
|
|
1012
|
+
csv_path=str(clean_csv), algorithm="ridge", budget="fast", **kwargs,
|
|
1013
|
+
))
|
|
1014
|
+
plan = _parse(await mcp_server.propose_training_plan(
|
|
1015
|
+
csv_path=str(leaky_csv), **kwargs,
|
|
1016
|
+
))
|
|
1017
|
+
assert "error" not in trained and "error" not in baseline and "error" not in plan
|
|
1018
|
+
|
|
1019
|
+
assert "Price_at_1k" not in trained["features"]
|
|
1020
|
+
for quality in (trained["feature_data_quality"], plan["feature_data_quality"]):
|
|
1021
|
+
assert "Price_at_1k" not in quality["per_column"]
|
|
1022
|
+
assert all(e["column"] != "Price_at_1k" for e in quality["extreme_magnitude"])
|
|
1023
|
+
# The leaky column's spikes drop no rows: same rows as without the column.
|
|
1024
|
+
assert trained["rows_used"] == baseline["rows_used"]
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
@pytest.mark.asyncio
|
|
1028
|
+
async def test_price_outliers_are_reported_under_warn(
|
|
1029
|
+
registry, tmp_path, synthetic_parts
|
|
1030
|
+
):
|
|
1031
|
+
csv = tmp_path / "spikes.csv"
|
|
1032
|
+
_price_spike_frame(synthetic_parts).to_csv(csv, index=False)
|
|
1033
|
+
|
|
1034
|
+
trained = _parse(await mcp_server.train(
|
|
1035
|
+
csv_path=str(csv), target="Price", algorithm="ridge", budget="fast",
|
|
1036
|
+
))
|
|
1037
|
+
plan = _parse(await mcp_server.propose_training_plan(
|
|
1038
|
+
csv_path=str(csv), target="Price",
|
|
1039
|
+
))
|
|
1040
|
+
assert "error" not in trained and "error" not in plan
|
|
1041
|
+
|
|
1042
|
+
for result in (trained, plan):
|
|
1043
|
+
block = result["price_outliers"]
|
|
1044
|
+
assert block["n_outliers"] >= 5
|
|
1045
|
+
assert block["n_total"] == len(synthetic_parts)
|
|
1046
|
+
assert block["policy"] == "warn"
|
|
1047
|
+
assert block["policy_applied"] == "none"
|
|
1048
|
+
assert block["upper"] < synthetic_parts["Price"].max() * 50
|
|
1049
|
+
assert any(
|
|
1050
|
+
f"{block['n_outliers']} of {block['n_total']} rows" in w
|
|
1051
|
+
for w in result["warnings"]
|
|
1052
|
+
)
|
|
1053
|
+
# warn keeps the rows.
|
|
1054
|
+
assert trained["rows_used"] == trained["rows_loaded"]
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
@pytest.mark.asyncio
|
|
1058
|
+
async def test_no_price_outlier_warning_when_policy_is_not_warn(
|
|
1059
|
+
registry, tmp_path, synthetic_parts
|
|
1060
|
+
):
|
|
1061
|
+
csv = tmp_path / "spikes.csv"
|
|
1062
|
+
_price_spike_frame(synthetic_parts).to_csv(csv, index=False)
|
|
1063
|
+
plan = _parse(await mcp_server.propose_training_plan(
|
|
1064
|
+
csv_path=str(csv), target="Price", outlier_policy="drop",
|
|
1065
|
+
))
|
|
1066
|
+
assert plan["price_outliers"]["policy_applied"] == "drop"
|
|
1067
|
+
assert plan["warnings"] == []
|
|
@@ -121,3 +121,36 @@ def test_xgboost_preprocessor_preserves_numeric_nans():
|
|
|
121
121
|
out = pp.transform(with_nan)
|
|
122
122
|
assert np.isnan(out[0, 0]) # numeric NaN preserved
|
|
123
123
|
assert np.isfinite(out[0, 1]) # categorical encoded to a real value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_target_encoder_fit_raises_no_deprecation_warning(synthetic_parts):
|
|
127
|
+
# scikit-learn 1.9 deprecated TargetEncoder.random_state and warns on every
|
|
128
|
+
# fit that sets it. Users of the CLI saw that warning repeated during
|
|
129
|
+
# training; the encoder must seed its folds without triggering it.
|
|
130
|
+
import warnings
|
|
131
|
+
|
|
132
|
+
pp = build_preprocessor(["Weight"], ["Region"], model_family="xgboost")
|
|
133
|
+
with warnings.catch_warnings():
|
|
134
|
+
warnings.simplefilter("error", FutureWarning)
|
|
135
|
+
warnings.simplefilter("error", DeprecationWarning)
|
|
136
|
+
pp.fit_transform(synthetic_parts[["Weight", "Region"]], synthetic_parts["Price"])
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_target_encoder_folds_match_the_seeded_int_cv(synthetic_parts):
|
|
140
|
+
# The training encoding must not change: the seeded KFold we pass on newer
|
|
141
|
+
# scikit-learn gives the same out-of-fold values as the old int cv seeded
|
|
142
|
+
# through random_state.
|
|
143
|
+
import warnings
|
|
144
|
+
|
|
145
|
+
X = synthetic_parts[["Region"]]
|
|
146
|
+
y = synthetic_parts["Price"]
|
|
147
|
+
ours = _target_encoder(
|
|
148
|
+
build_preprocessor([], ["Region"], model_family="xgboost")
|
|
149
|
+
.fit(X, y).named_transformers_["cat"]
|
|
150
|
+
)
|
|
151
|
+
with warnings.catch_warnings():
|
|
152
|
+
warnings.simplefilter("ignore", FutureWarning)
|
|
153
|
+
reference = TargetEncoder(
|
|
154
|
+
target_type="continuous", smooth="auto", cv=5, random_state=0
|
|
155
|
+
).fit_transform(X, y)
|
|
156
|
+
assert np.allclose(ours.fit_transform(X, y), reference)
|
|
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
|
|
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
|