in private_model_inversion.py [0:0]
def run_inversion(args, data, test_data, weights):
regression = (args.dataset == "iwpc" or args.dataset == "synth")
# Train model:
model = models.get_model(args.model)
logging.info(f"Training model {args.model}")
model.train(data, l2=args.l2, weights=weights)
if args.dataset == "uciadult":
target_attribute = (24, 25) # [not married, married]
elif args.dataset == "iwpc":
#target_attribute = (2, 7) # CYP2C9 genotype
target_attribute = (11, 13) # VKORC1 genotype
elif args.dataset == "synth":
target_attribute = (0, 2)
else:
raise NotImplementedError("Dataset not yet implemented.")
if args.inverter == "fredrikson14":
def invert(private_model, noise_scale=None):
return fredrikson14_inverter(
data, target_attribute, private_model, weights)
invert_fn = invert
elif args.inverter == "whitebox":
inverter = WhiteboxInverter(
data, target_attribute, type(model), weights, args.l2)
def invert(private_model, noise_scale=None):
return inverter.predict(private_model, gamma=noise_scale)
invert_fn = invert
results = {}
theta = model.get_params()
for noise_scale in args.noise_scales:
logging.info(f"Running inversion for noise scale {noise_scale}.")
all_predictions = []
train_accs = []
test_accs = []
for trial in range(args.trials):
# Add noise:
theta_priv = theta + torch.randn_like(theta) * noise_scale
model.set_params(theta_priv)
# Check train and test predictions:
train_acc = eval_model(model, data, regression)
test_acc = eval_model(model, test_data, regression)
if regression:
logging.info(f"MSE Train {train_acc:.3f}, MSE Test {test_acc:.3f}.")
else:
logging.info(f"Acc Train {train_acc:.3f}, Acc Test {test_acc:.3f}.")
predictions = invert_fn(model, noise_scale=noise_scale)
acc = compute_metrics(data, predictions, target_attribute)
logging.info(f"Private inversion accuracy {acc:.4f}")
all_predictions.append(predictions.tolist())
train_accs.append(train_acc)
test_accs.append(test_acc)
results[noise_scale] = {
"predictions" : all_predictions,
"train_acc" : train_accs,
"test_acc" : test_accs,
}
results["target"] = features_to_category(
data["features"][:, range(*target_attribute)]).tolist()
return results