mostlyai-qa 1.0.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.
Files changed (39) hide show
  1. mostlyai_qa-1.0.0/LICENSE +201 -0
  2. mostlyai_qa-1.0.0/PKG-INFO +185 -0
  3. mostlyai_qa-1.0.0/README.md +158 -0
  4. mostlyai_qa-1.0.0/pyproject.toml +39 -0
  5. mostlyai_qa-1.0.0/src/mostlyai/__init__.py +13 -0
  6. mostlyai_qa-1.0.0/src/mostlyai/qa/__init__.py +25 -0
  7. mostlyai_qa-1.0.0/src/mostlyai/qa/accuracy.py +1305 -0
  8. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/__init__.py +44 -0
  9. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/1_Pooling/config.json +10 -0
  10. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/README.md +178 -0
  11. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/config.json +26 -0
  12. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/config_sentence_transformers.json +10 -0
  13. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/model.safetensors +0 -0
  14. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/modules.json +20 -0
  15. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/sentence_bert_config.json +4 -0
  16. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/special_tokens_map.json +37 -0
  17. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/tokenizer.json +30686 -0
  18. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/tokenizer_config.json +64 -0
  19. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/embedders/sentence-transformers/all-MiniLM-L6-v2/vocab.txt +30522 -0
  20. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/bootstrap-5.3.3.bundle.min.js +7 -0
  21. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/bootstrap-5.3.3.min.css +6 -0
  22. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/explainer.svg +9 -0
  23. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/head.html +301 -0
  24. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/info.svg +4 -0
  25. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/plotly-2.12.1.min.js +65 -0
  26. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/report_early_exit.html +26 -0
  27. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/html/report_template.html +425 -0
  28. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/tokenizers/transformers/gpt2/merges.txt +50001 -0
  29. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/tokenizers/transformers/gpt2/special_tokens_map.json +23 -0
  30. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/tokenizers/transformers/gpt2/tokenizer_config.json +22 -0
  31. mostlyai_qa-1.0.0/src/mostlyai/qa/assets/tokenizers/transformers/gpt2/vocab.json +50259 -0
  32. mostlyai_qa-1.0.0/src/mostlyai/qa/common.py +119 -0
  33. mostlyai_qa-1.0.0/src/mostlyai/qa/distances.py +125 -0
  34. mostlyai_qa-1.0.0/src/mostlyai/qa/filesystem.py +289 -0
  35. mostlyai_qa-1.0.0/src/mostlyai/qa/html_report.py +155 -0
  36. mostlyai_qa-1.0.0/src/mostlyai/qa/report.py +578 -0
  37. mostlyai_qa-1.0.0/src/mostlyai/qa/report_from_statistics.py +251 -0
  38. mostlyai_qa-1.0.0/src/mostlyai/qa/sampling.py +290 -0
  39. mostlyai_qa-1.0.0/src/mostlyai/qa/similarity.py +264 -0
@@ -0,0 +1,201 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,185 @@
1
+ Metadata-Version: 2.1
2
+ Name: mostlyai-qa
3
+ Version: 1.0.0
4
+ Summary: Quality assurance for synthetic data
5
+ License: Apache License v2
6
+ Author: MOSTLY AI
7
+ Author-email: dev@mostly.ai
8
+ Requires-Python: >=3.10
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: Jinja2 (>=3.1.2)
15
+ Requires-Dist: fastcluster (>=1.2.6)
16
+ Requires-Dist: joblib (>=1.2.0)
17
+ Requires-Dist: numpy (>=1.26.3,<2.0.0)
18
+ Requires-Dist: pandas (>=2.2.0)
19
+ Requires-Dist: phik (>=0.12.4)
20
+ Requires-Dist: plotly (>=5.18.0)
21
+ Requires-Dist: pyarrow (>=16.0.0)
22
+ Requires-Dist: scikit-learn (>=1.4.0)
23
+ Requires-Dist: scipy (>=1.11.0)
24
+ Requires-Dist: sentence-transformers (>=3.1.0)
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Synthetic Data - Quality Assurance
28
+
29
+ Assess the fidelity and novelty of synthetic samples with respect to original samples:
30
+
31
+ 1. calculate a rich set of accuracy, similarity and distance metrics
32
+ 2. visualize statistics for easy comparison to training and holdout samples
33
+ 3. generate a standalone, easy-to-share, easy-to-read HTML summary report
34
+
35
+ ...all with a single line of Python code 💥.
36
+
37
+ ## Getting Started
38
+
39
+ ### Installation
40
+
41
+ ```bash
42
+ pip install -U mostlyai-qa
43
+ ```
44
+
45
+ ### Basic Usage
46
+
47
+ ```python
48
+ from mostlyai import qa
49
+
50
+ # analyze single-table data
51
+ report_path, metrics = qa.report(
52
+ syn_tgt_data = synthetic_df,
53
+ trn_tgt_data = training_df,
54
+ hol_tgt_data = holdout_df, # optional
55
+ )
56
+
57
+ # analyze sequential data
58
+ report_path, metrics = qa.report(
59
+ syn_tgt_data = synthetic_df,
60
+ trn_tgt_data = training_df,
61
+ hol_tgt_data = holdout_df, # optional
62
+ tgt_context_key = "user_id",
63
+ )
64
+
65
+ # analyze sequential data with context
66
+ report_path, metrics = qa.report(
67
+ syn_tgt_data = synthetic_df,
68
+ trn_tgt_data = training_df,
69
+ hol_tgt_data = holdout_df, # optional
70
+ syn_ctx_data = synthetic_context_df,
71
+ trn_ctx_data = training_context_df,
72
+ hol_ctx_data = holdout_context_df, # optional
73
+ ctx_primary_key = "id",
74
+ tgt_context_key = "user_id",
75
+ )
76
+ ```
77
+
78
+ ### Syntax
79
+
80
+ ```python
81
+ def report(
82
+ *,
83
+ syn_tgt_data: pd.DataFrame,
84
+ trn_tgt_data: pd.DataFrame,
85
+ hol_tgt_data: pd.DataFrame | None = None,
86
+ syn_ctx_data: pd.DataFrame | None = None,
87
+ trn_ctx_data: pd.DataFrame | None = None,
88
+ hol_ctx_data: pd.DataFrame | None = None,
89
+ ctx_primary_key: str | None = None,
90
+ tgt_context_key: str | None = None,
91
+ report_path: str | Path | None = "model-report.html",
92
+ report_title: str = "Model Report",
93
+ report_subtitle: str = "",
94
+ report_credits: str = REPORT_CREDITS,
95
+ report_extra_info: str = "",
96
+ max_sample_size_accuracy: int = MAX_SAMPLE_SIZE_ACCURACY,
97
+ max_sample_size_embeddings: int = MAX_SAMPLE_SIZE_EMBEDDINGS,
98
+ statistics_path: str | Path | None = None,
99
+ on_progress: ProgressCallback | None = None,
100
+ ) -> tuple[Path, dict | None]:
101
+ """
102
+ Generate HTML report and metrics for comparing synthetic and original data samples.
103
+
104
+ Args:
105
+ syn_tgt_data: Synthetic samples
106
+ trn_tgt_data: Training samples
107
+ hol_tgt_data: Holdout samples
108
+ syn_ctx_data: Synthetic context samples
109
+ trn_ctx_data: Training context samples
110
+ hol_ctx_data: Holdout context samples
111
+ ctx_primary_key: Column within the context data that contains the primary key
112
+ tgt_context_key: Column within the target data that contains the key to link to the context
113
+ report_path: Path of where to store the HTML report
114
+ report_title: Title of the HTML report
115
+ report_subtitle: Subtitle of the HTML report
116
+ report_credits: Credits of the HTML report
117
+ report_extra_info: Extra details to be included to the HTML report
118
+ max_sample_size_accuracy: Max sample size for accuracy
119
+ max_sample_size_embeddings: Max sample size for embeddings (similarity & distances)
120
+ statistics_path: Path of where to store the statistics to be used by `report_from_statistics`
121
+ on_progress: A custom progress callback
122
+ Returns:
123
+ 1. Path to the HTML report
124
+ 2. Dictionary of calculated metrics:
125
+ - `accuracy`: # Accuracy is defined as (100% - Total Variation Distance), for each distribution, and then averaged across.
126
+ - `overall`: Overall accuracy of synthetic data, i.e. average across univariate, bivariate and coherence.
127
+ - `univariate`: Average accuracy of discretized univariate distributions.
128
+ - `bivariate`: Average accuracy of discretized bivariate distributions.
129
+ - `coherence`: Average accuracy of discretized coherence distributions. Only applicable for sequential data.
130
+ - `overall_max`: Expected overall accuracy of a same-sized holdout. Serves as reference for `overall`.
131
+ - `univariate_max`: Expected univariate accuracy of a same-sized holdout. Serves as reference for `univariate`.
132
+ - `bivariate_max`: Expected bivariate accuracy of a same-sized holdout. Serves as reference for `bivariate`.
133
+ - `coherence_max`: Expected coherence accuracy of a same-sized holdout. Serves as reference for `coherence`.
134
+ - `similarity`: # All similarity metrics are calculated within an embedding space.
135
+ - `cosine_similarity_training_synthetic`: Cosine similarity between training and synthetic centroids.
136
+ - `cosine_similarity_training_holdout`: Cosine similarity between training and holdout centroids. Serves as reference for `cosine_similarity_training_synthetic`.
137
+ - `discriminator_auc_training_synthetic`: Cross-validated AUC of a discriminative model to distinguish between training and synthetic samples.
138
+ - `discriminator_auc_training_holdout`: Cross-validated AUC of a discriminative model to distinguish between training and holdout samples. Serves as reference for `discriminator_auc_training_synthetic`.
139
+ - `distances`: # All distance metrics are calculated within an embedding space. An equal number of training and holdout samples is considered.
140
+ - `ims_training`: Share of synthetic samples that are identical to a training sample.
141
+ - `ims_holdout`: Share of synthetic samples that are identical to a holdout sample. Serves as reference for `ims_training`.
142
+ - `dcr_training`: Average L2 nearest-neighbor distance between synthetic and training samples.
143
+ - `dcr_holdout`: Average L2 nearest-neighbor distance between synthetic and holdout samples. Serves as reference for `dcr_training`.
144
+ - `dcr_share`: Share of synthetic samples that are closer to a training sample than to a holdout sample. This shall not be significantly larger than 50\%.
145
+ """
146
+ ```
147
+
148
+ ## Metrics
149
+
150
+ We calculate three sets of metrics to compare synthetic data with the original data.
151
+
152
+ ### Accuracy
153
+
154
+ We calculate discretized marginal distributions for all columns, to then calculate the L1 distance between the synthetic and the original training data.
155
+ The reported accuracy is then expressed as 100% minus the total variational distance (TVD), which is half the L1 distance between the two distributions.
156
+ We then average across these accuracies to get a single accuracy score. The higher the score, the better the synthetic data.
157
+
158
+ 1. **Univariate Accuracy**: We measure the accuracy for the univariate distributions for all target columns.
159
+ 2. **Bivariate Accuracy**: We measure the accuracy for all pair-wise distributions for target columns, as well as for target columns with respect to the context columns.
160
+ 3. **Coherence Accuracy**: We measure the accuracy for the auto-correlation for all target columns. Only applicable for sequential data.
161
+
162
+ An overall accuracy score is then calculated as the average of these aggregate-level scores.
163
+
164
+ ### Similarity
165
+
166
+ We embed all records into an embedding space, to calculate two metrics:
167
+
168
+ 1. **Cosing Similarity**: We calculate the cosine similarity between the centroids of the synthetic and the original training data. This is then compared to the cosine similarity between the centroids of the original training and holdout data. The higher the score, the better the synthetic data.
169
+ 2. **Discriminator AUC**: We train a binary classifier to check whether one can distinguish between synthetic and original training data based on their embeddings. This is again compared to the same metric for the original training and holdout data. A score close to 50% indicates, that synthetic samples are indistinguishable from original samples.
170
+
171
+ ### Distances
172
+
173
+ We again embed all records into an embedding space, to then measure individual-level L2 distances between samples. For each synthetic sample, we calculate the distance to the nearest original sample (DCR). We once do this with respect to original training records, and once with respect to holdout records, and then compare these DCRs to each other. For privacy-safe synthetic data we expect to see that synthetic data is just as close to original training data, as it is to original holdout data.
174
+
175
+ ## Sample HTML Report
176
+
177
+ ![Metrics](./docs/screenshots/metrics.png)
178
+ ![Accuracy Univariates](./docs/screenshots/accuracy_univariates.png)
179
+ ![Accuracy Bivariates](./docs/screenshots/accuracy_bivariates.png)
180
+ ![Accuracy Coherence](./docs/screenshots/accuracy_coherence.png)
181
+ ![Similarity](./docs/screenshots/similarity.png)
182
+ ![Distances](./docs/screenshots/distances.png)
183
+
184
+ See the [examples](./examples/) directory for further examples.
185
+
@@ -0,0 +1,158 @@
1
+ # Synthetic Data - Quality Assurance
2
+
3
+ Assess the fidelity and novelty of synthetic samples with respect to original samples:
4
+
5
+ 1. calculate a rich set of accuracy, similarity and distance metrics
6
+ 2. visualize statistics for easy comparison to training and holdout samples
7
+ 3. generate a standalone, easy-to-share, easy-to-read HTML summary report
8
+
9
+ ...all with a single line of Python code 💥.
10
+
11
+ ## Getting Started
12
+
13
+ ### Installation
14
+
15
+ ```bash
16
+ pip install -U mostlyai-qa
17
+ ```
18
+
19
+ ### Basic Usage
20
+
21
+ ```python
22
+ from mostlyai import qa
23
+
24
+ # analyze single-table data
25
+ report_path, metrics = qa.report(
26
+ syn_tgt_data = synthetic_df,
27
+ trn_tgt_data = training_df,
28
+ hol_tgt_data = holdout_df, # optional
29
+ )
30
+
31
+ # analyze sequential data
32
+ report_path, metrics = qa.report(
33
+ syn_tgt_data = synthetic_df,
34
+ trn_tgt_data = training_df,
35
+ hol_tgt_data = holdout_df, # optional
36
+ tgt_context_key = "user_id",
37
+ )
38
+
39
+ # analyze sequential data with context
40
+ report_path, metrics = qa.report(
41
+ syn_tgt_data = synthetic_df,
42
+ trn_tgt_data = training_df,
43
+ hol_tgt_data = holdout_df, # optional
44
+ syn_ctx_data = synthetic_context_df,
45
+ trn_ctx_data = training_context_df,
46
+ hol_ctx_data = holdout_context_df, # optional
47
+ ctx_primary_key = "id",
48
+ tgt_context_key = "user_id",
49
+ )
50
+ ```
51
+
52
+ ### Syntax
53
+
54
+ ```python
55
+ def report(
56
+ *,
57
+ syn_tgt_data: pd.DataFrame,
58
+ trn_tgt_data: pd.DataFrame,
59
+ hol_tgt_data: pd.DataFrame | None = None,
60
+ syn_ctx_data: pd.DataFrame | None = None,
61
+ trn_ctx_data: pd.DataFrame | None = None,
62
+ hol_ctx_data: pd.DataFrame | None = None,
63
+ ctx_primary_key: str | None = None,
64
+ tgt_context_key: str | None = None,
65
+ report_path: str | Path | None = "model-report.html",
66
+ report_title: str = "Model Report",
67
+ report_subtitle: str = "",
68
+ report_credits: str = REPORT_CREDITS,
69
+ report_extra_info: str = "",
70
+ max_sample_size_accuracy: int = MAX_SAMPLE_SIZE_ACCURACY,
71
+ max_sample_size_embeddings: int = MAX_SAMPLE_SIZE_EMBEDDINGS,
72
+ statistics_path: str | Path | None = None,
73
+ on_progress: ProgressCallback | None = None,
74
+ ) -> tuple[Path, dict | None]:
75
+ """
76
+ Generate HTML report and metrics for comparing synthetic and original data samples.
77
+
78
+ Args:
79
+ syn_tgt_data: Synthetic samples
80
+ trn_tgt_data: Training samples
81
+ hol_tgt_data: Holdout samples
82
+ syn_ctx_data: Synthetic context samples
83
+ trn_ctx_data: Training context samples
84
+ hol_ctx_data: Holdout context samples
85
+ ctx_primary_key: Column within the context data that contains the primary key
86
+ tgt_context_key: Column within the target data that contains the key to link to the context
87
+ report_path: Path of where to store the HTML report
88
+ report_title: Title of the HTML report
89
+ report_subtitle: Subtitle of the HTML report
90
+ report_credits: Credits of the HTML report
91
+ report_extra_info: Extra details to be included to the HTML report
92
+ max_sample_size_accuracy: Max sample size for accuracy
93
+ max_sample_size_embeddings: Max sample size for embeddings (similarity & distances)
94
+ statistics_path: Path of where to store the statistics to be used by `report_from_statistics`
95
+ on_progress: A custom progress callback
96
+ Returns:
97
+ 1. Path to the HTML report
98
+ 2. Dictionary of calculated metrics:
99
+ - `accuracy`: # Accuracy is defined as (100% - Total Variation Distance), for each distribution, and then averaged across.
100
+ - `overall`: Overall accuracy of synthetic data, i.e. average across univariate, bivariate and coherence.
101
+ - `univariate`: Average accuracy of discretized univariate distributions.
102
+ - `bivariate`: Average accuracy of discretized bivariate distributions.
103
+ - `coherence`: Average accuracy of discretized coherence distributions. Only applicable for sequential data.
104
+ - `overall_max`: Expected overall accuracy of a same-sized holdout. Serves as reference for `overall`.
105
+ - `univariate_max`: Expected univariate accuracy of a same-sized holdout. Serves as reference for `univariate`.
106
+ - `bivariate_max`: Expected bivariate accuracy of a same-sized holdout. Serves as reference for `bivariate`.
107
+ - `coherence_max`: Expected coherence accuracy of a same-sized holdout. Serves as reference for `coherence`.
108
+ - `similarity`: # All similarity metrics are calculated within an embedding space.
109
+ - `cosine_similarity_training_synthetic`: Cosine similarity between training and synthetic centroids.
110
+ - `cosine_similarity_training_holdout`: Cosine similarity between training and holdout centroids. Serves as reference for `cosine_similarity_training_synthetic`.
111
+ - `discriminator_auc_training_synthetic`: Cross-validated AUC of a discriminative model to distinguish between training and synthetic samples.
112
+ - `discriminator_auc_training_holdout`: Cross-validated AUC of a discriminative model to distinguish between training and holdout samples. Serves as reference for `discriminator_auc_training_synthetic`.
113
+ - `distances`: # All distance metrics are calculated within an embedding space. An equal number of training and holdout samples is considered.
114
+ - `ims_training`: Share of synthetic samples that are identical to a training sample.
115
+ - `ims_holdout`: Share of synthetic samples that are identical to a holdout sample. Serves as reference for `ims_training`.
116
+ - `dcr_training`: Average L2 nearest-neighbor distance between synthetic and training samples.
117
+ - `dcr_holdout`: Average L2 nearest-neighbor distance between synthetic and holdout samples. Serves as reference for `dcr_training`.
118
+ - `dcr_share`: Share of synthetic samples that are closer to a training sample than to a holdout sample. This shall not be significantly larger than 50\%.
119
+ """
120
+ ```
121
+
122
+ ## Metrics
123
+
124
+ We calculate three sets of metrics to compare synthetic data with the original data.
125
+
126
+ ### Accuracy
127
+
128
+ We calculate discretized marginal distributions for all columns, to then calculate the L1 distance between the synthetic and the original training data.
129
+ The reported accuracy is then expressed as 100% minus the total variational distance (TVD), which is half the L1 distance between the two distributions.
130
+ We then average across these accuracies to get a single accuracy score. The higher the score, the better the synthetic data.
131
+
132
+ 1. **Univariate Accuracy**: We measure the accuracy for the univariate distributions for all target columns.
133
+ 2. **Bivariate Accuracy**: We measure the accuracy for all pair-wise distributions for target columns, as well as for target columns with respect to the context columns.
134
+ 3. **Coherence Accuracy**: We measure the accuracy for the auto-correlation for all target columns. Only applicable for sequential data.
135
+
136
+ An overall accuracy score is then calculated as the average of these aggregate-level scores.
137
+
138
+ ### Similarity
139
+
140
+ We embed all records into an embedding space, to calculate two metrics:
141
+
142
+ 1. **Cosing Similarity**: We calculate the cosine similarity between the centroids of the synthetic and the original training data. This is then compared to the cosine similarity between the centroids of the original training and holdout data. The higher the score, the better the synthetic data.
143
+ 2. **Discriminator AUC**: We train a binary classifier to check whether one can distinguish between synthetic and original training data based on their embeddings. This is again compared to the same metric for the original training and holdout data. A score close to 50% indicates, that synthetic samples are indistinguishable from original samples.
144
+
145
+ ### Distances
146
+
147
+ We again embed all records into an embedding space, to then measure individual-level L2 distances between samples. For each synthetic sample, we calculate the distance to the nearest original sample (DCR). We once do this with respect to original training records, and once with respect to holdout records, and then compare these DCRs to each other. For privacy-safe synthetic data we expect to see that synthetic data is just as close to original training data, as it is to original holdout data.
148
+
149
+ ## Sample HTML Report
150
+
151
+ ![Metrics](./docs/screenshots/metrics.png)
152
+ ![Accuracy Univariates](./docs/screenshots/accuracy_univariates.png)
153
+ ![Accuracy Bivariates](./docs/screenshots/accuracy_bivariates.png)
154
+ ![Accuracy Coherence](./docs/screenshots/accuracy_coherence.png)
155
+ ![Similarity](./docs/screenshots/similarity.png)
156
+ ![Distances](./docs/screenshots/distances.png)
157
+
158
+ See the [examples](./examples/) directory for further examples.
@@ -0,0 +1,39 @@
1
+ [tool.poetry]
2
+ name = "mostlyai-qa"
3
+ version = "1.0.0"
4
+ description = "Quality assurance for synthetic data"
5
+ readme = "README.md"
6
+ license = "Apache License v2"
7
+ authors = ["MOSTLY AI <dev@mostly.ai>"]
8
+ packages = [
9
+ { include = "mostlyai", from = "src" }
10
+ ]
11
+
12
+ [tool.poetry.dependencies]
13
+ python = ">=3.10"
14
+ numpy = ">=1.26.3,<2.0.0"
15
+ scipy = ">=1.11.0"
16
+ pandas = ">=2.2.0"
17
+ pyarrow = ">=16.0.0"
18
+ plotly = ">=5.18.0"
19
+ phik = ">=0.12.4"
20
+ fastcluster = ">=1.2.6"
21
+ joblib = ">=1.2.0"
22
+ Jinja2 = ">=3.1.2"
23
+ scikit-learn = ">=1.4.0"
24
+ sentence-transformers = ">=3.1.0"
25
+
26
+ [tool.poetry.group.dev.dependencies]
27
+ ruff = "0.7.0"
28
+ pytest = ">=7.1.2"
29
+ pre-commit = ">=3.2.0"
30
+ twine = "^5.1.1"
31
+
32
+
33
+ [tool.ruff]
34
+ target-version = "py310"
35
+ line-length = 120
36
+
37
+ [build-system]
38
+ requires = ["poetry-core>=1.0.0"]
39
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,13 @@
1
+ # Copyright 2024 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
@@ -0,0 +1,25 @@
1
+ # Copyright 2024 MOSTLY AI
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+
17
+ import pandas as pd
18
+
19
+ from mostlyai.qa.report import report
20
+ from mostlyai.qa.report_from_statistics import report_from_statistics
21
+
22
+ __all__ = ["report", "report_from_statistics"]
23
+
24
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
25
+ pd.set_option("future.no_silent_downcasting", True)