-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmape.py
74 lines (59 loc) · 2.94 KB
/
mape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import numpy as np
import pandas as pd
def calculateMAPE(synthetic_pop, true_pop):
# Both populations should have exact same columns in exact same order
assert list(synthetic_pop.columns) == list(true_pop.columns)
ape_vals_all = []
ape_vals_ind = []
total_bins = 0
for col in synthetic_pop.columns:
# Get bin frequencies for each column
synthetic_freqs = synthetic_pop[col].value_counts().to_dict()
true_freqs = true_pop[col].value_counts().to_dict()
# Calculate squared error for each bin; keep track of mean frequencies
pe_vals = []
for col_bin in list(true_freqs.keys()):
# There may not be counts of certain bins in the synthetic population
if col_bin in synthetic_freqs.keys():
pe = (true_freqs[col_bin] - synthetic_freqs[col_bin]) / true_freqs[col_bin]
else:
pe = (true_freqs[col_bin] - 0) / true_freqs[col_bin]
pe_vals.append(np.absolute(pe))
ape_vals_all.append(np.sum(pe_vals))
ape_vals_ind.append(np.sum(pe_vals) / len(true_freqs.keys())*100)
total_bins += len(true_freqs.keys())
print(f"{col} MAPE: {np.sum(pe_vals) / len(true_freqs.keys())*100}")
# Reduce to mean for all variables
mape = np.sum(ape_vals_all) / total_bins * 100
print(f"Univariate (marginal) MAPE: {mape}, Total Bins: {total_bins}")
return ape_vals_ind
# def calculateBivariateMAPE(synthetic_pop, true_pop):
# # Both populations should have exact same columns in exact same order
# assert list(synthetic_pop.columns) == list(true_pop.columns)
# ape_vals = []
# used_combos = []
# total_bins = 0
# # Create contingency table for every combination of 2 variables
# for col_1 in list(synthetic_pop.columns):
# for col_2 in list(synthetic_pop.columns):
# # Don't do contingency of the same column on itself or repeat tables
# if col_1 == col_2:
# continue
# elif [col_2,col_1] in used_combos or [col_1,col_2] in used_combos:
# continue
# else:
# ct_synth = pd.crosstab(synthetic_pop[col_1], synthetic_pop[col_2], margins=False)
# ct_true = pd.crosstab(true_pop[col_1], true_pop[col_2], margins=False)
# used_combos.append([col_1, col_2])
# # Calculate MPE on the contingency table
# z = np.absolute((ct_true - ct_synth)/ct_true).values
# # There may not be counts of certain bins in the synthetic population
# nan_indices = np.argwhere(np.isnan(z))
# nan_indices = [tuple(idx) for idx in nan_indices]
# for idx in nan_indices:
# z[idx] = 1.0
# ape_vals.append(np.sum(z))
# total_bins += z.shape[0]*z.shape[1]
# mape = np.sum(ape_vals) / total_bins
# print(f"Bivariate (joint) MAPE: {mape}, Total Bins: {total_bins}")
# return mape