-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_dataset.py
193 lines (173 loc) · 8.54 KB
/
create_dataset.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
from argparse import ArgumentParser
import os
import cvxpy as cp
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from scipy.special import logit, expit
from scipy.spatial import distance
from tqdm.auto import tqdm
import yaml
from typing import Callable, List, Optional, Union
def get_vector_with_similarity(vec, similarity, seed=137):
"""
Design inspired by https://stackoverflow.com/questions/52916699/create-random-vector-given-cosine-similarity
"""
if similarity < -1 or similarity > 1:
raise ValueError("Cosine similarity must be in [-1, 1].")
vec_norm = vec / np.linalg.norm(vec)
np.random.seed(seed)
rand_vec = np.random.multivariate_normal(np.zeros_like(vec_norm), np.eye(len(vec_norm)))
vec_perp = rand_vec - rand_vec.dot(vec_norm) * vec_norm
vec_perp = vec_perp / np.linalg.norm(vec_perp)
sine_sim = np.sqrt(1 - similarity ** 2)
final_vec = similarity * vec_norm + sine_sim * vec_perp # and it's still unit since sin^2 + cos^2 = 1
return final_vec
class SyntheticUpcodingDataset(object):
def __init__(
self,
plans: List[float],
n_features: int,
n_plan_features: int,
seed: Optional[int] = 42,
var: Optional[float] = 0.2,
target_dx_rate: Optional[float] = 0.05, # depreacted - kept for backward compatibility
plan_spread: Optional[float] = 0.4,
plan_mean_bias: Optional[float] = -0.6, # controls overlal dx rate
sharpness: Optional[float] = 1.,
confounding_param: Optional[float] = 1.,
ccv_rev_fn: Optional[Callable] = cp.log, #lambda x: cp.power(x, 1),
cvx_pen_fn: Optional[Callable] = cp.sum_squares,
):
self.plans = plans
self.n_plans = len(plans)
self.n_plan_features = n_plan_features
self.target_dx_rate = target_dx_rate
self.n_features = n_features
self.var = var
self.plan_spread = plan_spread
self.sharpness = sharpness
self.confounding_param = confounding_param
self.plan_mean_bias = plan_mean_bias
_ = self.get_parameters(seed)
self.ccv_rev_fn = ccv_rev_fn
self.cvx_pen_fn = cvx_pen_fn
def _reseed(self, seed):
if seed is not None:
self.seed = seed
np.random.seed(seed)
def get_parameters(self, seed: Optional[int] = None):
self._reseed(seed)
coeff = np.random.rand(self.n_features) # make this positive
self.coeff = coeff / np.linalg.norm(coeff) * self.sharpness
self.bias = None # logit(self.target_dx_rate) - self.coeff.sum()
return self.coeff, self.bias
def get_dx_rate_at_lambda(self, plan_lambda, d_opt_param):
d = cp.Variable(len(d_opt_param))
revenue_atom = self.ccv_rev_fn(d)
if revenue_atom.curvature == "CONVEX":
raise ValueError("Revenue function must be concave (strictly or not).")
penalty_atom = self.cvx_pen_fn(d - d_opt_param)
if penalty_atom.curvature != "CONVEX":
raise ValueError("Penalty function must be strictly convex.")
if plan_lambda < 0:
raise ValueError("Plan lambda must be non-negative.")
obj = cp.sum(revenue_atom - plan_lambda * cp.sum_squares(d - d_opt_param))
prob = cp.Problem(cp.Maximize(obj), [d >= 0, d <= 1])
prob.solve(solver=cp.CLARABEL)
return d.value, np.square(d.value - d_opt_param).sum()
def get_plan_embeddings(self):
plan_basis = np.random.randn(self.n_plan_features)
plan_embedding_seed = np.random.rand(self.n_plans, self.n_plan_features)
plan_embeddings = cp.Variable(plan_embedding_seed.shape)
obj = cp.sum_squares(plan_embedding_seed - plan_embeddings)
prob = cp.Problem(cp.Minimize(obj), [plan_embeddings @ plan_basis == np.log(self.plans) * np.ones(self.n_plans)])
prob.solve(solver=cp.CLARABEL)
return plan_embeddings.value, plan_embeddings @ plan_basis - np.log(self.plans)
def generate(self, n: Union[List[int], int], n_datasets: int, seed: Optional[int] = None):
if isinstance(n, list):
if len(n) != self.n_plans:
raise ValueError("If passing a list for `n`, must match the length of `self.plans`.")
else:
lengths = np.array(n, dtype=int)
else:
lengths = np.ones(self.n_plans, dtype=int) * n
self._reseed(seed)
plan_embeddings, _ = self.get_plan_embeddings()
plan_logs = np.log(self.plans)
plan_basis = self.plan_spread * (plan_logs - plan_logs.min()) / (plan_logs.max() - plan_logs.min()) + self.plan_mean_bias
v_p = get_vector_with_similarity(self.coeff, self.confounding_param)
plan_means = np.outer(v_p, plan_basis)
print("Plan basis:", plan_basis)
print("Range:", plan_basis.max() - plan_basis.min())
print("Empirical cosine sim.:", 1 - distance.cosine(self.coeff, v_p))
data_dict = {}
X = np.concatenate([self.var * np.random.randn(lengths[i], self.n_features) + plan_means[:, i] for i in list(range(len(self.plans))) * n_datasets], axis=0)
data_dict["t"] = np.concatenate([np.ones(lengths[i], dtype=int) * i for i in list(range(len(self.plans))) * n_datasets], axis=0)
data_dict["split"] = np.repeat(np.arange(n_datasets), lengths.sum())
X_proj = X @ self.coeff
self.bias = logit(self.target_dx_rate) - X_proj.mean() # target_dx_rate should be named "bias" really -- it doesn't do much
d_opt_param = expit(X_proj + self.bias)
data_dict["d*_param"] = d_opt_param
data_dict["d*"] = (np.random.rand(len(d_opt_param)) < d_opt_param).astype(int)
data_dict["d_obs"] = np.zeros(len(d_opt_param))
for i in tqdm(range(len(self.plans))):
d_param, loss = self.get_dx_rate_at_lambda(self.plans[i], d_opt_param)
d = (np.random.rand(len(d_param)) < d_param).astype(int) # separate random draws or no?
data_dict[f"d_{i}_param"] = d_param
data_dict[f"d_{i}"] = d
treatment_mask = (data_dict["t"] == i)
data_dict["d_obs"][treatment_mask] = data_dict[f"d_{i}"][treatment_mask]
df = pd.concat([
pd.DataFrame.from_records(X).add_prefix('x'),
pd.DataFrame.from_dict(data_dict),
], axis=1)
plan_df = pd.DataFrame.from_records(plan_embeddings).add_prefix('embed_dim_')
return df, plan_df
if __name__ == '__main__':
psr = ArgumentParser()
psr.add_argument("--config", type=str, required=True)
psr.add_argument("--dataset", type=str, default="synthetic", choices=["synthetic", "ffs"])
psr.add_argument("--n-per-plan", type=int, default=250)
psr.add_argument("--n-datasets", type=int, default=10)
psr.add_argument("--overwrite", action="store_true")
args = psr.parse_args()
with open(args.config, "r") as f:
cfg = yaml.safe_load(f)
save_path = os.path.join("./analytic", args.dataset, cfg["name"] + ".csv")
plan_save_path = os.path.join("./analytic", args.dataset, cfg["name"] + "_plan_embeds.csv")
if os.path.isfile(save_path) and not args.overwrite:
raise ValueError(save_path, "already exists")
print("CONFIG:", cfg)
if args.dataset == "synthetic":
dataset = SyntheticUpcodingDataset(
cfg["plans"],
cfg["n_features"],
cfg["n_plan_features"],
target_dx_rate=cfg["target_dx_rate"],
**cfg.get("kwargs", None),
)
df, plans = dataset.generate(args.n_per_plan, cfg["n_splits"])
else:
raise NotImplementedError()
d_cols = [c for c in df.columns if c.startswith("d") and not c.endswith("param")]
with pd.option_context('display.max_columns', 9999):
corrs = []
for split in range(args.n_datasets):
print(df.loc[df["split"] == split, d_cols].describe())
print("Conditional mean plan rankings:")
means = []
for i in range(len(plans)):
mean = df.loc[(df["split"] == split) & (df["t"] == i), "d_obs"].mean()
print("Gaming param.:", cfg["plans"][i], "\tMean observed Dx rate:", mean)
means.append(mean)
corr = spearmanr(-np.array(cfg["plans"]), means).statistic
print("Corr:", corr)
corrs.append(corr)
corrs = np.array(corrs)
print(corrs)
print("Correlations:", corrs.mean(), np.quantile(corrs, 0.25), np.quantile(corrs, 0.75))
df.to_csv(save_path)
print("CSV saved to:", save_path)
plans.to_csv(plan_save_path)
print("Plan embeddings saved to:", plan_save_path)