proxyml 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.
- proxyml/__init__.py +27 -0
- proxyml/client.py +190 -0
- proxyml/schema.py +59 -0
- proxyml-0.1.0.dist-info/METADATA +329 -0
- proxyml-0.1.0.dist-info/RECORD +8 -0
- proxyml-0.1.0.dist-info/WHEEL +5 -0
- proxyml-0.1.0.dist-info/licenses/LICENSE +183 -0
- proxyml-0.1.0.dist-info/top_level.txt +1 -0
proxyml/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from proxyml.client import (
|
|
2
|
+
put_schema,
|
|
3
|
+
synthesize_data,
|
|
4
|
+
train_surrogate,
|
|
5
|
+
predict,
|
|
6
|
+
find_counterfactual,
|
|
7
|
+
interpret_counterfactual,
|
|
8
|
+
)
|
|
9
|
+
from proxyml.schema import (
|
|
10
|
+
get_schema,
|
|
11
|
+
gen_continuous_schema,
|
|
12
|
+
gen_categorical_schema,
|
|
13
|
+
gen_discrete_schema,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"put_schema",
|
|
18
|
+
"synthesize_data",
|
|
19
|
+
"train_surrogate",
|
|
20
|
+
"predict",
|
|
21
|
+
"find_counterfactual",
|
|
22
|
+
"interpret_counterfactual",
|
|
23
|
+
"get_schema",
|
|
24
|
+
"gen_continuous_schema",
|
|
25
|
+
"gen_categorical_schema",
|
|
26
|
+
"gen_discrete_schema",
|
|
27
|
+
]
|
proxyml/client.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
logger = logging.getLogger(__name__)
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
import os
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from pandas.api.types import is_float_dtype, is_integer_dtype
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
PROXYML_BASE_URL = os.getenv("PROXYML_BASE_URL", "https://api.proxyml.ai/api/v1")
|
|
12
|
+
|
|
13
|
+
_BOOL_STRINGS = {"true", "false"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _headers() -> dict:
|
|
17
|
+
api_key = os.getenv("PROXYML_API_KEY", "")
|
|
18
|
+
if not api_key:
|
|
19
|
+
raise EnvironmentError(
|
|
20
|
+
"PROXYML_API_KEY is not set. "
|
|
21
|
+
"Set the environment variable before using the SDK."
|
|
22
|
+
)
|
|
23
|
+
return {
|
|
24
|
+
'Content-Type': 'application/json',
|
|
25
|
+
'X-API-KEY': api_key,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def post(endpoint: str, payload: dict) -> requests.models.Response:
|
|
30
|
+
r = requests.post(
|
|
31
|
+
url=f'{PROXYML_BASE_URL}{endpoint}',
|
|
32
|
+
json=payload,
|
|
33
|
+
headers=_headers()
|
|
34
|
+
)
|
|
35
|
+
return r
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def put(endpoint: str, payload: dict) -> requests.models.Response:
|
|
39
|
+
r = requests.put(
|
|
40
|
+
url=f'{PROXYML_BASE_URL}{endpoint}',
|
|
41
|
+
json=payload,
|
|
42
|
+
headers=_headers()
|
|
43
|
+
)
|
|
44
|
+
return r
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def put_schema(schema: dict):
|
|
48
|
+
r = put(endpoint='/schema', payload=schema)
|
|
49
|
+
if r.status_code == 200:
|
|
50
|
+
logger.info("Schema uploaded successfully")
|
|
51
|
+
return r.json()
|
|
52
|
+
logger.error(
|
|
53
|
+
"Schema upload failed with status %s: %s",
|
|
54
|
+
r.status_code,
|
|
55
|
+
r.text
|
|
56
|
+
)
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _cast_column(series: pd.Series, ftype: str) -> pd.Series:
|
|
61
|
+
if ftype in ("continuous",):
|
|
62
|
+
return series.astype(float)
|
|
63
|
+
if ftype in ("count", "numeric_ordinal"):
|
|
64
|
+
return series.astype(int)
|
|
65
|
+
if ftype in ("categorical", "categorical_ordinal"):
|
|
66
|
+
# convert "true"/"false" strings back to booleans when appropriate
|
|
67
|
+
unique = {str(v).lower() for v in series.dropna().unique()}
|
|
68
|
+
if unique <= _BOOL_STRINGS:
|
|
69
|
+
return series.map({"true": True, "false": False, True: True, False: False})
|
|
70
|
+
return series
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def synthesize_data(num_points: int = 100, sample: list | None = None, as_df: bool = True):
|
|
74
|
+
if sample is None:
|
|
75
|
+
r = post(endpoint='/synthesize/neighbors', payload={'n': num_points})
|
|
76
|
+
else:
|
|
77
|
+
r = post(endpoint='/synthesize/blended', payload={'n': num_points, 'instance': [col.item() for col in sample]})
|
|
78
|
+
if r.status_code == 200:
|
|
79
|
+
payload = r.json()
|
|
80
|
+
if as_df:
|
|
81
|
+
df = pd.DataFrame(payload['samples'], columns=payload['feature_names'])
|
|
82
|
+
for col, ftype in zip(payload['feature_names'], payload['feature_types']):
|
|
83
|
+
df[col] = _cast_column(df[col], ftype)
|
|
84
|
+
return df
|
|
85
|
+
return payload
|
|
86
|
+
logger.error(
|
|
87
|
+
"Data synthesis failed with status %s: %s",
|
|
88
|
+
r.status_code,
|
|
89
|
+
r.text
|
|
90
|
+
)
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def train_surrogate(
|
|
95
|
+
samples: list,
|
|
96
|
+
predictions: list,
|
|
97
|
+
feature_names: list[str] | None,
|
|
98
|
+
task: str = 'auto',
|
|
99
|
+
test_size: float = 0.2
|
|
100
|
+
):
|
|
101
|
+
r = post(endpoint='/surrogate/train', payload={'samples': samples, 'predictions': predictions, 'feature_names': feature_names, 'task': task, 'test_size': test_size})
|
|
102
|
+
if r.status_code == 200:
|
|
103
|
+
return r.json()
|
|
104
|
+
logger.error(
|
|
105
|
+
"Surrogate training failed with status %s: %s",
|
|
106
|
+
r.status_code,
|
|
107
|
+
r.text
|
|
108
|
+
)
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def predict(samples: list, version: int | None): # Defaults to latest version if not specified
|
|
113
|
+
payload = {'inputs': samples}
|
|
114
|
+
if version: # Also rejects version 0 (versions start at 1)
|
|
115
|
+
payload['version'] = version
|
|
116
|
+
r = post(endpoint='/surrogate/predict', payload=payload)
|
|
117
|
+
if r.status_code == 200:
|
|
118
|
+
return r.json()
|
|
119
|
+
logger.error(
|
|
120
|
+
"Surrogate prediction failed with status %s: %s",
|
|
121
|
+
r.status_code,
|
|
122
|
+
r.text
|
|
123
|
+
)
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def find_counterfactual(sample, target, n_neighbors: int = 10000, perturbation_scale: float = 0.1, version: int | None = None, as_df: bool = True):
|
|
128
|
+
payload = {
|
|
129
|
+
'instance': sample,
|
|
130
|
+
'target_label': target,
|
|
131
|
+
'n_neighbors': n_neighbors,
|
|
132
|
+
'perturbation_scale': perturbation_scale,
|
|
133
|
+
}
|
|
134
|
+
if version: # Also rejects version 0 (versions start at 1)
|
|
135
|
+
payload['version'] = version
|
|
136
|
+
r = post(endpoint='/explain/counterfactual', payload=payload)
|
|
137
|
+
if r.status_code == 200:
|
|
138
|
+
payload = r.json()
|
|
139
|
+
if as_df:
|
|
140
|
+
if payload['counterfactual'] is None:
|
|
141
|
+
print(f"No counterfactual found: {payload.get('warning')}")
|
|
142
|
+
return None
|
|
143
|
+
df = pd.DataFrame([payload['counterfactual']], columns=payload['feature_names'])
|
|
144
|
+
for col, ftype in zip(payload['feature_names'], payload['feature_types']):
|
|
145
|
+
df[col] = _cast_column(df[col], ftype)
|
|
146
|
+
return df
|
|
147
|
+
return payload
|
|
148
|
+
logger.error(
|
|
149
|
+
"Counterfactual failed with status %s: %s",
|
|
150
|
+
r.status_code,
|
|
151
|
+
r.text
|
|
152
|
+
)
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def interpret_counterfactual(
|
|
157
|
+
sample: dict,
|
|
158
|
+
counterfactual: dict,
|
|
159
|
+
prediction_changed: bool,
|
|
160
|
+
exclude_from_diff: list[str] | None
|
|
161
|
+
) -> str:
|
|
162
|
+
if not exclude_from_diff:
|
|
163
|
+
exclude_from_diff = list()
|
|
164
|
+
diffs = {
|
|
165
|
+
k: (sample[k], counterfactual[k])
|
|
166
|
+
for k in sample
|
|
167
|
+
if sample[k] != counterfactual[k]
|
|
168
|
+
and k not in exclude_from_diff
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if not diffs:
|
|
172
|
+
return "No meaningful differences found between sample and counterfactual."
|
|
173
|
+
|
|
174
|
+
changes = ", ".join(
|
|
175
|
+
f"{feature} from {original} to {cf_value}"
|
|
176
|
+
for feature, (original, cf_value) in diffs.items()
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
if prediction_changed:
|
|
180
|
+
return (
|
|
181
|
+
f"Changing {changes} may result in a different prediction. "
|
|
182
|
+
f"Note: this is based on a surrogate model and should be treated as approximate."
|
|
183
|
+
)
|
|
184
|
+
else:
|
|
185
|
+
return (
|
|
186
|
+
f"A counterfactual was found suggesting {changes}, however "
|
|
187
|
+
f"the original model's prediction did not change. "
|
|
188
|
+
f"This may indicate the surrogate model does not fully capture "
|
|
189
|
+
f"the original model's decision boundary in this region."
|
|
190
|
+
)
|
proxyml/schema.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
logger = logging.getLogger(__name__)
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from pandas.api.types import is_float_dtype, is_integer_dtype
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def gen_continuous_schema(s: pd.Series, name: str | None = None) -> dict:
|
|
11
|
+
return {
|
|
12
|
+
'type': 'continuous',
|
|
13
|
+
'name': name or s.name,
|
|
14
|
+
'mean': np.nanmean(s).item(),
|
|
15
|
+
'std': np.nanstd(s).item(),
|
|
16
|
+
'min': np.nanmin(s).item(),
|
|
17
|
+
'max': np.nanmax(s).item()
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def gen_categorical_schema(s: pd.Series, name: str | None = None) -> dict:
|
|
22
|
+
counts = s.value_counts(normalize=True)
|
|
23
|
+
return {
|
|
24
|
+
'type': 'categorical',
|
|
25
|
+
'name': name or s.name,
|
|
26
|
+
'valid_categories': counts.to_dict()
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def gen_discrete_schema(s: pd.Series, name: str | None = None) -> dict:
|
|
31
|
+
return {
|
|
32
|
+
'type': 'count',
|
|
33
|
+
'name': name or s.name,
|
|
34
|
+
'lambda': np.nanmean(s).item(),
|
|
35
|
+
'max': np.nanmax(s).item()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_schema(df: pd.DataFrame, immutable_cols: list[str] | None) -> dict:
|
|
40
|
+
schema = {
|
|
41
|
+
'features': list(),
|
|
42
|
+
'_note': (
|
|
43
|
+
'Auto-generated schema. Review and adjust types as needed. '
|
|
44
|
+
'Integer columns default to count type - consider categorical_ordinal '
|
|
45
|
+
'for ordered categories like ratings or class labels.'
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
for col in df.columns:
|
|
49
|
+
if is_float_dtype(df[col]):
|
|
50
|
+
col_schema = gen_continuous_schema(df[col])
|
|
51
|
+
elif df[col].dtype == bool:
|
|
52
|
+
col_schema = gen_categorical_schema(df[col])
|
|
53
|
+
elif is_integer_dtype(df[col]):
|
|
54
|
+
col_schema = gen_discrete_schema(df[col])
|
|
55
|
+
else:
|
|
56
|
+
col_schema = gen_categorical_schema(df[col])
|
|
57
|
+
col_schema['immutable'] = immutable_cols is not None and col in immutable_cols
|
|
58
|
+
schema['features'].append(col_schema)
|
|
59
|
+
return schema
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: proxyml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for calling the ProxyML API
|
|
5
|
+
Author-email: ProxyML <contact@proxyml.ai>
|
|
6
|
+
License: Apache License
|
|
7
|
+
Version 2.0, January 2004
|
|
8
|
+
http://www.apache.org/licenses/
|
|
9
|
+
|
|
10
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
11
|
+
|
|
12
|
+
1. Definitions.
|
|
13
|
+
|
|
14
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
15
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
16
|
+
|
|
17
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
18
|
+
the copyright owner that is granting the License.
|
|
19
|
+
|
|
20
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
21
|
+
other entities that control, are controlled by, or are under common
|
|
22
|
+
control with that entity. For the purposes of this definition,
|
|
23
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
24
|
+
direction or management of such entity, whether by contract or
|
|
25
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
26
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
27
|
+
|
|
28
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
29
|
+
exercising permissions granted by this License.
|
|
30
|
+
|
|
31
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
32
|
+
including but not limited to software source code, documentation
|
|
33
|
+
source, and configuration files.
|
|
34
|
+
|
|
35
|
+
"Object" form shall mean any form resulting from mechanical
|
|
36
|
+
transformation or translation of a Source form, including but
|
|
37
|
+
not limited to compiled object code, generated documentation,
|
|
38
|
+
and conversions to other media types.
|
|
39
|
+
|
|
40
|
+
"Work" shall mean the work of authorship made available under
|
|
41
|
+
the License, as indicated by a copyright notice that is included in
|
|
42
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
43
|
+
|
|
44
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
45
|
+
form, that is based on (or derived from) the Work and for which the
|
|
46
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
47
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
48
|
+
of this License, Derivative Works shall not include works that remain
|
|
49
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
50
|
+
the Work and Derivative Works thereof.
|
|
51
|
+
|
|
52
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
53
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
54
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
55
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
56
|
+
or written communication sent to the Licensor or its representatives,
|
|
57
|
+
including but not limited to communication on electronic mailing lists,
|
|
58
|
+
source code control systems, and issue tracking systems that are managed
|
|
59
|
+
by, or on behalf of, the Licensor for the purpose of developing and
|
|
60
|
+
discussing the Work, but excluding communication that is conspicuously
|
|
61
|
+
marked or designated in writing by the copyright owner as "Not a
|
|
62
|
+
Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
65
|
+
whom a Contribution has been received by the Licensor and included
|
|
66
|
+
within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a cross-claim
|
|
85
|
+
or counterclaim in a lawsuit) alleging that the Work or any other
|
|
86
|
+
Contribution incorporated within the Work constitutes patent or
|
|
87
|
+
contributory patent infringement, then any patent licenses granted to
|
|
88
|
+
You under this License for that Work shall terminate as of the date
|
|
89
|
+
such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
97
|
+
Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, You must include a readable copy of the
|
|
110
|
+
attribution notices contained within such NOTICE file, in
|
|
111
|
+
at least one of the following places: within a NOTICE text
|
|
112
|
+
file distributed as part of the Derivative Works; within
|
|
113
|
+
the Source form or documentation, if provided along with the
|
|
114
|
+
Derivative Works; or, within a display generated by the
|
|
115
|
+
Derivative Works, if and wherever such third-party notices
|
|
116
|
+
normally appear. The contents of the NOTICE file are for
|
|
117
|
+
informational purposes only and do not modify the License.
|
|
118
|
+
You may add Your own attribution notices within Derivative
|
|
119
|
+
Works that You distribute, alongside or in addition to the
|
|
120
|
+
NOTICE text from the Work, provided that such additional
|
|
121
|
+
attribution notices cannot be construed as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own license statement for Your modifications and
|
|
124
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
125
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
126
|
+
Contribution and such Derivative Works.
|
|
127
|
+
|
|
128
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
129
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
130
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
131
|
+
this License, without any additional terms or conditions.
|
|
132
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
133
|
+
the terms of any separate license agreement you may have executed
|
|
134
|
+
with Licensor regarding such Contributions.
|
|
135
|
+
|
|
136
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
137
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
138
|
+
except as required for reasonable and customary use in describing the
|
|
139
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
140
|
+
|
|
141
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
142
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
143
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
144
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
145
|
+
implied, including, without limitation, any conditions of TITLE,
|
|
146
|
+
NONINFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
|
|
147
|
+
PURPOSE. You are solely responsible for determining the
|
|
148
|
+
appropriateness of using or reproducing the Work and assume any
|
|
149
|
+
risks associated with Your exercise of permissions under this License.
|
|
150
|
+
|
|
151
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
152
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
153
|
+
unless required by applicable law (such as deliberate and grossly
|
|
154
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
155
|
+
liable to You for damages, including any direct, indirect, special,
|
|
156
|
+
incidental, or exemplary damages of any character arising as a
|
|
157
|
+
result of this License or out of the use or inability to use the
|
|
158
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
159
|
+
work stoppage, computer failure or malfunction, or all other
|
|
160
|
+
commercial damages or losses), even if such Contributor has been
|
|
161
|
+
advised of the possibility of such damages.
|
|
162
|
+
|
|
163
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
164
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
165
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
166
|
+
or other liability obligations and/or rights consistent with this
|
|
167
|
+
License. However, in accepting such obligations, You may charge only
|
|
168
|
+
on Your own behalf and on Your sole responsibility, not on behalf of
|
|
169
|
+
any other Contributor, and only if You agree to indemnify, defend,
|
|
170
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
171
|
+
or claims asserted against, such Contributor by reason of your
|
|
172
|
+
accepting any warranty or additional liability.
|
|
173
|
+
|
|
174
|
+
END OF TERMS AND CONDITIONS
|
|
175
|
+
|
|
176
|
+
Copyright 2026 ProxyML
|
|
177
|
+
|
|
178
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
179
|
+
you may not use this file except in compliance with the License.
|
|
180
|
+
You may obtain a copy of the License at
|
|
181
|
+
|
|
182
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
183
|
+
|
|
184
|
+
Unless required by applicable law or agreed to in writing, software
|
|
185
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
186
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
187
|
+
See the License for the specific language governing permissions and
|
|
188
|
+
limitations under the License.
|
|
189
|
+
|
|
190
|
+
Project-URL: Homepage, https://proxyml.ai
|
|
191
|
+
Project-URL: Documentation, https://github.com/proxyml/proxyml-sdk-python/blob/main/docs/quickstart.md
|
|
192
|
+
Project-URL: Repository, https://github.com/proxyml/proxyml-sdk-python
|
|
193
|
+
Project-URL: Bug Tracker, https://github.com/proxyml/proxyml-sdk-python/issues
|
|
194
|
+
Keywords: machine learning,api,sdk
|
|
195
|
+
Classifier: Development Status :: 3 - Alpha
|
|
196
|
+
Classifier: Intended Audience :: Developers
|
|
197
|
+
Classifier: Intended Audience :: Science/Research
|
|
198
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
199
|
+
Classifier: Programming Language :: Python :: 3
|
|
200
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
201
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
202
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
203
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
204
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
205
|
+
Requires-Python: >=3.10
|
|
206
|
+
Description-Content-Type: text/markdown
|
|
207
|
+
License-File: LICENSE
|
|
208
|
+
Requires-Dist: requests>=2.28
|
|
209
|
+
Requires-Dist: numpy>=1.23
|
|
210
|
+
Requires-Dist: pandas>=1.5
|
|
211
|
+
Provides-Extra: dev
|
|
212
|
+
Requires-Dist: build; extra == "dev"
|
|
213
|
+
Requires-Dist: twine; extra == "dev"
|
|
214
|
+
Requires-Dist: pytest; extra == "dev"
|
|
215
|
+
Requires-Dist: black; extra == "dev"
|
|
216
|
+
Requires-Dist: ruff; extra == "dev"
|
|
217
|
+
Dynamic: license-file
|
|
218
|
+
|
|
219
|
+
# proxyml
|
|
220
|
+
|
|
221
|
+
Python SDK for the [ProxyML API](https://proxyml.ai).
|
|
222
|
+
|
|
223
|
+
> **Status:** Early access — server endpoints coming soon.
|
|
224
|
+
> [Request early access](mailto:contact@proxyml.ai) or star this repo to follow progress.
|
|
225
|
+
|
|
226
|
+
## Why ProxyML?
|
|
227
|
+
|
|
228
|
+
Most explainability tools require sending your data to a third-party server.
|
|
229
|
+
ProxyML never sees your training data. You generate synthetic data locally,
|
|
230
|
+
score it with your own model, and only the surrogate model and summary
|
|
231
|
+
statistics are uploaded — your data stays yours.
|
|
232
|
+
|
|
233
|
+
## Installation
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
pip install proxyml
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Setup
|
|
240
|
+
|
|
241
|
+
ProxyML requires an API key. Set it as an environment variable before importing the package:
|
|
242
|
+
|
|
243
|
+
```bash
|
|
244
|
+
export PROXYML_API_KEY="your-api-key"
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Optionally override the base URL (defaults to `https://api.proxyml.ai/api/v1`):
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
export PROXYML_BASE_URL="https://api.proxyml.ai/api/v1"
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
## Quick Start
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
import pandas as pd
|
|
257
|
+
import proxyml
|
|
258
|
+
from proxyml import get_schema
|
|
259
|
+
|
|
260
|
+
# 1. Load your dataset and generate a schema
|
|
261
|
+
df = pd.read_csv("data.csv")
|
|
262
|
+
schema = get_schema(df, immutable_cols=["age", "gender"])
|
|
263
|
+
|
|
264
|
+
# 2. Upload the schema
|
|
265
|
+
proxyml.put_schema(schema)
|
|
266
|
+
|
|
267
|
+
# 3. Generate synthetic training data
|
|
268
|
+
synth_df = proxyml.synthesize_data(num_points=500)
|
|
269
|
+
|
|
270
|
+
# 4. Score synthetic data with your black-box model
|
|
271
|
+
predictions = my_model.predict(synth_df.values.tolist())
|
|
272
|
+
|
|
273
|
+
# 5. Train a surrogate model
|
|
274
|
+
proxyml.train_surrogate(
|
|
275
|
+
samples=synth_df.values.tolist(),
|
|
276
|
+
predictions=predictions,
|
|
277
|
+
feature_names=list(synth_df.columns),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
# 6. Find a counterfactual explanation
|
|
281
|
+
sample = df.iloc[0].tolist()
|
|
282
|
+
cf = proxyml.find_counterfactual(sample=sample, target=1, version=None)
|
|
283
|
+
|
|
284
|
+
if cf is not None:
|
|
285
|
+
original = synth_df.iloc[0].to_dict()
|
|
286
|
+
cf_dict = cf.iloc[0].to_dict()
|
|
287
|
+
current_pred = my_model.predict([sample])[0]
|
|
288
|
+
cf_pred = my_model.predict([cf.values.tolist()[0]])[0]
|
|
289
|
+
|
|
290
|
+
explanation = proxyml.interpret_counterfactual(
|
|
291
|
+
sample=original,
|
|
292
|
+
counterfactual=cf_dict,
|
|
293
|
+
prediction_changed=(current_pred != cf_pred),
|
|
294
|
+
)
|
|
295
|
+
print(explanation)
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
See [`docs/quickstart.md`](docs/quickstart.md) for a full walkthrough and [`docs/api.md`](docs/api.md) for complete API reference.
|
|
299
|
+
|
|
300
|
+
## Core Concepts
|
|
301
|
+
|
|
302
|
+
**Surrogate model** — A fast, interpretable model trained to approximate your black-box model's behavior on synthetic data. Once trained, it can be queried directly via the ProxyML API.
|
|
303
|
+
|
|
304
|
+
**Counterfactual explanation** — Given a prediction, a counterfactual is the minimal change to input features that would produce a different prediction. It answers: *"What would have to be different for the outcome to change?"*
|
|
305
|
+
|
|
306
|
+
**Schema** — Describes the statistical properties of each feature (type, range, distribution). Used to generate realistic synthetic data and constrain counterfactual search.
|
|
307
|
+
|
|
308
|
+
## API Reference
|
|
309
|
+
|
|
310
|
+
| Function | Description |
|
|
311
|
+
|---|---|
|
|
312
|
+
| `get_schema(df, immutable_cols)` | Generate a schema dict from a DataFrame |
|
|
313
|
+
| `put_schema(schema)` | Upload a schema to the API |
|
|
314
|
+
| `synthesize_data(num_points, sample, as_df)` | Generate synthetic data points |
|
|
315
|
+
| `train_surrogate(samples, predictions, feature_names, task, test_size)` | Train a surrogate model |
|
|
316
|
+
| `predict(samples, version)` | Score samples with the surrogate model |
|
|
317
|
+
| `find_counterfactual(sample, target, ...)` | Find a counterfactual for a given sample |
|
|
318
|
+
| `interpret_counterfactual(sample, counterfactual, ...)` | Generate a human-readable explanation |
|
|
319
|
+
|
|
320
|
+
Full documentation: [`docs/api.md`](docs/api.md)
|
|
321
|
+
|
|
322
|
+
## Examples
|
|
323
|
+
|
|
324
|
+
- [`examples/basic_usage.py`](examples/basic_usage.py) — Schema upload, data synthesis, surrogate training
|
|
325
|
+
- [`examples/counterfactual_example.py`](examples/counterfactual_example.py) — Counterfactual search and interpretation
|
|
326
|
+
|
|
327
|
+
## License
|
|
328
|
+
|
|
329
|
+
Apache 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
proxyml/__init__.py,sha256=XXZvFE6KjzY08LKiJ7vzRz0MprGATZc0xuGKXHTA4m0,541
|
|
2
|
+
proxyml/client.py,sha256=iT65zgaB5zGlvSBqv7eMx_flSa_R9s2nLZxOGmd16NA,8717
|
|
3
|
+
proxyml/schema.py,sha256=GWfcw0tYHSvGlDLWzfov5RZMk9wFEXbMKU4G-R9iEbA,2077
|
|
4
|
+
proxyml-0.1.0.dist-info/licenses/LICENSE,sha256=g3kg6VH6Fi9-VhRB0ZYTPsVKUAMx7D9UsoZMJ_KZtko,10196
|
|
5
|
+
proxyml-0.1.0.dist-info/METADATA,sha256=XJZH-jlgmHVI8YQujDWuYlE9SHpXLE9rr6JClnotP8c,16872
|
|
6
|
+
proxyml-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
proxyml-0.1.0.dist-info/top_level.txt,sha256=aZJqLvh74AOsYI5zvINna2cq8hW6wCiF2dCSt8QAkQ8,8
|
|
8
|
+
proxyml-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of developing and
|
|
55
|
+
discussing the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or designated in writing by the copyright owner as "Not a
|
|
57
|
+
Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and included
|
|
61
|
+
within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or any other
|
|
81
|
+
Contribution incorporated within the Work constitutes patent or
|
|
82
|
+
contributory patent infringement, then any patent licenses granted to
|
|
83
|
+
You under this License for that Work shall terminate as of the date
|
|
84
|
+
such litigation is filed.
|
|
85
|
+
|
|
86
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
87
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
88
|
+
modifications, and in Source or Object form, provided that You
|
|
89
|
+
meet the following conditions:
|
|
90
|
+
|
|
91
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
92
|
+
Works a copy of this License; and
|
|
93
|
+
|
|
94
|
+
(b) You must cause any modified files to carry prominent notices
|
|
95
|
+
stating that You changed the files; and
|
|
96
|
+
|
|
97
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
98
|
+
that You distribute, all copyright, patent, trademark, and
|
|
99
|
+
attribution notices from the Source form of the Work,
|
|
100
|
+
excluding those notices that do not pertain to any part of
|
|
101
|
+
the Derivative Works; and
|
|
102
|
+
|
|
103
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
104
|
+
distribution, You must include a readable copy of the
|
|
105
|
+
attribution notices contained within such NOTICE file, in
|
|
106
|
+
at least one of the following places: within a NOTICE text
|
|
107
|
+
file distributed as part of the Derivative Works; within
|
|
108
|
+
the Source form or documentation, if provided along with the
|
|
109
|
+
Derivative Works; or, within a display generated by the
|
|
110
|
+
Derivative Works, if and wherever such third-party notices
|
|
111
|
+
normally appear. The contents of the NOTICE file are for
|
|
112
|
+
informational purposes only and do not modify the License.
|
|
113
|
+
You may add Your own attribution notices within Derivative
|
|
114
|
+
Works that You distribute, alongside or in addition to the
|
|
115
|
+
NOTICE text from the Work, provided that such additional
|
|
116
|
+
attribution notices cannot be construed as modifying the License.
|
|
117
|
+
|
|
118
|
+
You may add Your own license statement for Your modifications and
|
|
119
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
120
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
121
|
+
Contribution and such Derivative Works.
|
|
122
|
+
|
|
123
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
124
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
125
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
126
|
+
this License, without any additional terms or conditions.
|
|
127
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
128
|
+
the terms of any separate license agreement you may have executed
|
|
129
|
+
with Licensor regarding such Contributions.
|
|
130
|
+
|
|
131
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
132
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
133
|
+
except as required for reasonable and customary use in describing the
|
|
134
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
137
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
138
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
139
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
140
|
+
implied, including, without limitation, any conditions of TITLE,
|
|
141
|
+
NONINFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
|
|
142
|
+
PURPOSE. You are solely responsible for determining the
|
|
143
|
+
appropriateness of using or reproducing the Work and assume any
|
|
144
|
+
risks associated with Your exercise of permissions under this License.
|
|
145
|
+
|
|
146
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
147
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
148
|
+
unless required by applicable law (such as deliberate and grossly
|
|
149
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
150
|
+
liable to You for damages, including any direct, indirect, special,
|
|
151
|
+
incidental, or exemplary damages of any character arising as a
|
|
152
|
+
result of this License or out of the use or inability to use the
|
|
153
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
154
|
+
work stoppage, computer failure or malfunction, or all other
|
|
155
|
+
commercial damages or losses), even if such Contributor has been
|
|
156
|
+
advised of the possibility of such damages.
|
|
157
|
+
|
|
158
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
159
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
160
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
161
|
+
or other liability obligations and/or rights consistent with this
|
|
162
|
+
License. However, in accepting such obligations, You may charge only
|
|
163
|
+
on Your own behalf and on Your sole responsibility, not on behalf of
|
|
164
|
+
any other Contributor, and only if You agree to indemnify, defend,
|
|
165
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
166
|
+
or claims asserted against, such Contributor by reason of your
|
|
167
|
+
accepting any warranty or additional liability.
|
|
168
|
+
|
|
169
|
+
END OF TERMS AND CONDITIONS
|
|
170
|
+
|
|
171
|
+
Copyright 2026 ProxyML
|
|
172
|
+
|
|
173
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
174
|
+
you may not use this file except in compliance with the License.
|
|
175
|
+
You may obtain a copy of the License at
|
|
176
|
+
|
|
177
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
178
|
+
|
|
179
|
+
Unless required by applicable law or agreed to in writing, software
|
|
180
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
181
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
182
|
+
See the License for the specific language governing permissions and
|
|
183
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
proxyml
|