syndat 0.0.2__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.
- syndat-0.0.2/LICENSE +21 -0
- syndat-0.0.2/PKG-INFO +11 -0
- syndat-0.0.2/README.md +44 -0
- syndat-0.0.2/setup.cfg +4 -0
- syndat-0.0.2/setup.py +26 -0
- syndat-0.0.2/syndat/__init__.py +0 -0
- syndat-0.0.2/syndat/domain.py +35 -0
- syndat-0.0.2/syndat/quality.py +82 -0
- syndat-0.0.2/syndat/visualization.py +83 -0
- syndat-0.0.2/syndat.egg-info/PKG-INFO +11 -0
- syndat-0.0.2/syndat.egg-info/SOURCES.txt +12 -0
- syndat-0.0.2/syndat.egg-info/dependency_links.txt +1 -0
- syndat-0.0.2/syndat.egg-info/top_level.txt +1 -0
- syndat-0.0.2/tests/test_jsd.py +18 -0
syndat-0.0.2/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Fraunhofer SCAI Bioinformatics Department
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
syndat-0.0.2/PKG-INFO
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: syndat
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: A library for evaluation & visualization of synthetic data.
|
|
5
|
+
Home-page: https://github.com/SCAI-BIO/syndat
|
|
6
|
+
Author: Tim Adams
|
|
7
|
+
Author-email: tim.adams@scai.fraunhofer.de
|
|
8
|
+
License: CC BY-NC-ND 4.0.
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
|
|
11
|
+
A library for evaluation & visualization of synthetic data.
|
syndat-0.0.2/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Syndat
|
|
2
|
+
Synthetic data quality evaluation & visualization
|
|
3
|
+
|
|
4
|
+
# Installation
|
|
5
|
+
|
|
6
|
+
Install via pip:
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install syndat
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
# Usage
|
|
13
|
+
|
|
14
|
+
## Quality metrics
|
|
15
|
+
|
|
16
|
+
Compute data quality metrics by comparing real and synthetic data in terms of their separation complexity,
|
|
17
|
+
distribution similarity or pairwise feature correlations:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import pandas as pd
|
|
21
|
+
from syndat import quality
|
|
22
|
+
|
|
23
|
+
real = pd.read_csv("real.csv")
|
|
24
|
+
synthetic = pd.read_csv("synthetic.csv")
|
|
25
|
+
|
|
26
|
+
jsd = quality.get_jsd(real, synthetic)
|
|
27
|
+
auc = quality.get_auc(real, synthetic)
|
|
28
|
+
norm = quality.get_correlation_quotient(real, synthetic)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Visualization
|
|
32
|
+
|
|
33
|
+
Visualize real vs. synthetic data distributions and summary statistics for each feature:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import pandas as pd
|
|
37
|
+
from syndat import visualization
|
|
38
|
+
|
|
39
|
+
real = pd.read_csv("real.csv")
|
|
40
|
+
synthetic = pd.read_csv("synthetic.csv")
|
|
41
|
+
|
|
42
|
+
visualization.plot_distributions(real, synthetic, store_destination="results/plots")
|
|
43
|
+
```
|
|
44
|
+
|
syndat-0.0.2/setup.cfg
ADDED
syndat-0.0.2/setup.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from setuptools import setup
|
|
5
|
+
|
|
6
|
+
DESCRIPTION = 'A library for evaluation & visualization of synthetic data.'
|
|
7
|
+
|
|
8
|
+
here = os.path.abspath(os.path.dirname(__file__))
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
|
|
12
|
+
long_description = '\n' + f.read()
|
|
13
|
+
except FileNotFoundError:
|
|
14
|
+
long_description = DESCRIPTION
|
|
15
|
+
|
|
16
|
+
setup(
|
|
17
|
+
name='syndat',
|
|
18
|
+
version='v0.0.2',
|
|
19
|
+
packages=['syndat'],
|
|
20
|
+
url='https://github.com/SCAI-BIO/syndat',
|
|
21
|
+
license='CC BY-NC-ND 4.0.',
|
|
22
|
+
author='Tim Adams',
|
|
23
|
+
author_email='tim.adams@scai.fraunhofer.de',
|
|
24
|
+
description=DESCRIPTION,
|
|
25
|
+
long_description=DESCRIPTION,
|
|
26
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ColumnType:
|
|
5
|
+
def __init__(self, name, datatype, options, minval, maxval):
|
|
6
|
+
self.name = name
|
|
7
|
+
self.datatype = datatype
|
|
8
|
+
self.options = options
|
|
9
|
+
self.minval = minval
|
|
10
|
+
self.maxval = maxval
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ColumnConstraint:
|
|
14
|
+
def __init__(self, name, minval, maxval, category):
|
|
15
|
+
self.name = name
|
|
16
|
+
self.minval = minval
|
|
17
|
+
self.maxval = maxval
|
|
18
|
+
self.category = category
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OutlierPredictionMode(Enum):
|
|
22
|
+
isolationForest = "isolation_forest"
|
|
23
|
+
local_outlier_factor = "local_outlier_factor"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NaNHandlingStrategy(Enum):
|
|
27
|
+
accept_inbalance = "accept_inbalance"
|
|
28
|
+
sample_random = "sample_random"
|
|
29
|
+
sample_closest = "sample_closest"
|
|
30
|
+
encode_nan = "encode_nan"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AggregationMethod(Enum):
|
|
34
|
+
AVERAGE = "average"
|
|
35
|
+
MEDIAN = "median"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import pandas
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
import scipy.spatial.distance
|
|
5
|
+
|
|
6
|
+
from sklearn import ensemble, neighbors
|
|
7
|
+
from sklearn.model_selection import cross_val_score
|
|
8
|
+
|
|
9
|
+
from syndat.domain import OutlierPredictionMode, AggregationMethod
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_auc(real: pandas.DataFrame, synthetic: pandas.DataFrame, n_folds=10):
|
|
13
|
+
x = pd.concat([real, synthetic])
|
|
14
|
+
y = np.concatenate((np.zeros(real.shape[0]), np.ones(synthetic.shape[0])), axis=None)
|
|
15
|
+
rfc = ensemble.RandomForestClassifier()
|
|
16
|
+
return np.average(cross_val_score(rfc, x, y, cv=n_folds, scoring='roc_auc'))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_jsd(real: pandas.DataFrame, synthetic: pandas.DataFrame, aggregate_results: bool = True,
|
|
20
|
+
aggregation_method: AggregationMethod = AggregationMethod.AVERAGE):
|
|
21
|
+
# load datasets & remove id column
|
|
22
|
+
jsd_dict = {}
|
|
23
|
+
for col in real:
|
|
24
|
+
# delete empty cells
|
|
25
|
+
real_wo_missing = real[col].dropna()
|
|
26
|
+
# binning
|
|
27
|
+
if np.sum(real[col].values) % 1 == 0 and np.sum(synthetic[col].values) % 1 == 0:
|
|
28
|
+
# categorical column
|
|
29
|
+
real_binned = np.bincount(real[col])
|
|
30
|
+
virtual_binned = np.bincount(synthetic[col])
|
|
31
|
+
else:
|
|
32
|
+
# get optimal amount of bins
|
|
33
|
+
n_bins = np.histogram_bin_edges(real_wo_missing, bins='auto')
|
|
34
|
+
real_binned = np.bincount(np.digitize(real_wo_missing, n_bins))
|
|
35
|
+
virtual_binned = np.bincount(np.digitize(synthetic[col], n_bins))
|
|
36
|
+
# one array might be shorter here then the other, e.g. if real patients contain the categorical
|
|
37
|
+
# encoding 0-3, but virtual patients only contain 0-2
|
|
38
|
+
# in this case -> fill missing bin with zero
|
|
39
|
+
if len(real_binned) != len(virtual_binned):
|
|
40
|
+
padding_size = np.abs(len(real_binned) - len(virtual_binned))
|
|
41
|
+
if len(real_binned) > len(virtual_binned):
|
|
42
|
+
virtual_binned = np.pad(virtual_binned, (0, padding_size))
|
|
43
|
+
else:
|
|
44
|
+
real_binned = np.pad(real_binned, (0, padding_size))
|
|
45
|
+
# compute jsd
|
|
46
|
+
jsd = scipy.spatial.distance.jensenshannon(real_binned, virtual_binned)
|
|
47
|
+
jsd_dict[col] = jsd
|
|
48
|
+
if aggregate_results and aggregation_method == AggregationMethod.AVERAGE:
|
|
49
|
+
return np.mean(np.array(list(jsd_dict.values())))
|
|
50
|
+
elif aggregate_results and aggregation_method == AggregationMethod.MEDIAN:
|
|
51
|
+
return np.median(np.array(list(jsd_dict.values())))
|
|
52
|
+
else:
|
|
53
|
+
return jsd_dict
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_correlation_quotient(real: pandas.DataFrame, synthetic: pandas.DataFrame):
|
|
57
|
+
corr_real = real.corr()
|
|
58
|
+
corr_synthetic = synthetic.corr()
|
|
59
|
+
norm_diff = np.linalg.norm(corr_real - corr_synthetic)
|
|
60
|
+
norm_real = np.linalg.norm(corr_real)
|
|
61
|
+
norm_quotient = norm_diff / norm_real
|
|
62
|
+
return norm_quotient
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_outliers(synthetic: pd.DataFrame, mode: OutlierPredictionMode = OutlierPredictionMode.isolationForest,
|
|
66
|
+
anomaly_score: bool = False):
|
|
67
|
+
if mode == OutlierPredictionMode.isolationForest:
|
|
68
|
+
model = ensemble.IsolationForest(random_state=42)
|
|
69
|
+
return outlier_predictions(model, anomaly_score, x=synthetic)
|
|
70
|
+
elif mode == OutlierPredictionMode.local_outlier_factor:
|
|
71
|
+
model = neighbors.LocalOutlierFactor(n_neighbors=2)
|
|
72
|
+
return outlier_predictions(model, anomaly_score, x=synthetic)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def outlier_predictions(model, anomaly_score, x):
|
|
76
|
+
if anomaly_score:
|
|
77
|
+
model.fit(x)
|
|
78
|
+
return model.score_samples(X=x) * -1
|
|
79
|
+
else:
|
|
80
|
+
predictions = model.fit_predict(X=x)
|
|
81
|
+
outliers_idx = np.array(np.where(predictions == -1))[0]
|
|
82
|
+
return outliers_idx
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import pandas
|
|
2
|
+
import matplotlib
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
import plotly.graph_objects as go
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import seaborn as sns
|
|
8
|
+
from pandas.plotting import table
|
|
9
|
+
|
|
10
|
+
from sklearn.manifold import TSNE
|
|
11
|
+
from syndat.quality import get_outliers
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def get_tsne_plot_data(real: pandas.DataFrame, synthetic: pandas.DataFrame):
|
|
15
|
+
x = pandas.concat([real, synthetic])
|
|
16
|
+
perplexity = 30
|
|
17
|
+
if real.shape[1] < 30:
|
|
18
|
+
perplexity = real.shape[1] - 1
|
|
19
|
+
tsne = TSNE(n_components=2, perplexity=perplexity, random_state=42)
|
|
20
|
+
tsne_result = tsne.fit_transform(x)
|
|
21
|
+
border = real.shape[0]
|
|
22
|
+
x_real = tsne_result[:border, 0]
|
|
23
|
+
y_real = tsne_result[:border, 1]
|
|
24
|
+
x_virtual = tsne_result[border:, 0]
|
|
25
|
+
y_virtual = tsne_result[border:, 1]
|
|
26
|
+
return x_real, y_real, x_virtual, y_virtual
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def show_outlier_plot(real: pandas.DataFrame, synthetic: pandas.DataFrame):
|
|
30
|
+
trace_real, trace_virtual = get_tsne_plot_data(real, synthetic)
|
|
31
|
+
fig = go.Figure()
|
|
32
|
+
fig.add_trace(go.Scatter(x=trace_real["x"], y=trace_real["y"], mode="markers", name='real'))
|
|
33
|
+
fig.add_trace(go.Scatter(x=trace_virtual['x'], y=trace_virtual['y'], mode="markers", name='synthetic'))
|
|
34
|
+
# Add outlier markings for virtual patients
|
|
35
|
+
outliers = get_outliers(synthetic)
|
|
36
|
+
for outlier in outliers:
|
|
37
|
+
x0 = trace_virtual['x'][outlier] - 0.5
|
|
38
|
+
y0 = trace_virtual['y'][outlier] - 0.5
|
|
39
|
+
x1 = trace_virtual['x'][outlier] + 0.5
|
|
40
|
+
y1 = trace_virtual['y'][outlier] + 0.5
|
|
41
|
+
fig.add_shape(type="circle", xref="x", yref="y", x0=x0, y0=y0, x1=x1, y1=y1, line_color="LightSeaGreen")
|
|
42
|
+
# display
|
|
43
|
+
fig.show()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def plot_distributions(real: pandas.DataFrame, synthetic: pandas.DataFrame, store_destination: str):
|
|
47
|
+
for column_name in real.columns:
|
|
48
|
+
matplotlib.use('Agg')
|
|
49
|
+
real_col = real[column_name].to_numpy()
|
|
50
|
+
virtual_col = synthetic[column_name].to_numpy()
|
|
51
|
+
plt.figure()
|
|
52
|
+
plt.title(column_name)
|
|
53
|
+
patient_types = np.concatenate([np.zeros(real_col.size), np.ones(virtual_col.size)])
|
|
54
|
+
df = pd.DataFrame(data={"type": np.where(patient_types == 0, "real", "synthetic"),
|
|
55
|
+
"value": np.concatenate([real_col, virtual_col])})
|
|
56
|
+
if real_col.dtype == str or real_col.dtype == object:
|
|
57
|
+
ax = sns.countplot(data=df, x="value", hue="type", order=df['value'].value_counts().index)
|
|
58
|
+
elif np.sum(real_col) % 1 == 0 and np.max(real_col) < 10:
|
|
59
|
+
ax = sns.countplot(data=df, x="value", hue="type")
|
|
60
|
+
else:
|
|
61
|
+
df = pd.DataFrame(data={"real": real_col, "synthetic": virtual_col})
|
|
62
|
+
ax = sns.violinplot(data=df)
|
|
63
|
+
# remove y-labels as they are redundant with the table headers
|
|
64
|
+
ax.set_xticks([])
|
|
65
|
+
table(ax, df.describe().round(2), loc='bottom', colLoc='center', bbox=[0, -0.55, 1, 0.5],
|
|
66
|
+
colWidths=[.5, .5])
|
|
67
|
+
fig = ax.get_figure()
|
|
68
|
+
matplotlib.pyplot.close()
|
|
69
|
+
fig.savefig(store_destination + "/" + column_name + '.png', bbox_inches="tight")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def plot_correlations(real: pandas.DataFrame, synthetic: pandas.DataFrame, store_destination: str):
|
|
73
|
+
names = ["real_corr", "syntehtic_corr"]
|
|
74
|
+
for idx, patient_type in enumerate([real, synthetic]):
|
|
75
|
+
plt.figure()
|
|
76
|
+
plt.title("Correlation")
|
|
77
|
+
ax = sns.heatmap(patient_type.corr())
|
|
78
|
+
fig = ax.get_figure()
|
|
79
|
+
fig.savefig(store_destination + "/" + names[idx] + '.png', bbox_inches="tight")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: syndat
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: A library for evaluation & visualization of synthetic data.
|
|
5
|
+
Home-page: https://github.com/SCAI-BIO/syndat
|
|
6
|
+
Author: Tim Adams
|
|
7
|
+
Author-email: tim.adams@scai.fraunhofer.de
|
|
8
|
+
License: CC BY-NC-ND 4.0.
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
|
|
11
|
+
A library for evaluation & visualization of synthetic data.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
setup.py
|
|
4
|
+
syndat/__init__.py
|
|
5
|
+
syndat/domain.py
|
|
6
|
+
syndat/quality.py
|
|
7
|
+
syndat/visualization.py
|
|
8
|
+
syndat.egg-info/PKG-INFO
|
|
9
|
+
syndat.egg-info/SOURCES.txt
|
|
10
|
+
syndat.egg-info/dependency_links.txt
|
|
11
|
+
syndat.egg-info/top_level.txt
|
|
12
|
+
tests/test_jsd.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
syndat
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from unittest import TestCase
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from syndat.quality import get_jsd
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Test(TestCase):
|
|
10
|
+
|
|
11
|
+
TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))
|
|
12
|
+
|
|
13
|
+
real = pd.read_csv(os.path.join(TEST_DIR_PATH, "resources", 'real.csv'))
|
|
14
|
+
synthetic = pd.read_csv(os.path.join(TEST_DIR_PATH, "resources", 'synthetic.csv'))
|
|
15
|
+
|
|
16
|
+
def test_get_jsd_avg(self):
|
|
17
|
+
jsd = get_jsd(self.real, self.synthetic)
|
|
18
|
+
self.assertEqual(0.1602252096223203, jsd)
|