code stringlengths 17 6.64M |
|---|
def block(x, c):
filters_in = x.get_shape()[(- 1)]
m = (4 if c['bottleneck'] else 1)
filters_out = (m * c['block_filters_internal'])
shortcut = x
c['conv_filters_out'] = c['block_filters_internal']
if c['bottleneck']:
with tf.variable_scope('a'):
c['ksize'] = 1
... |
def bn(x, c):
x_shape = x.get_shape()
params_shape = x_shape[(- 1):]
if c['use_bias']:
bias = _get_variable('bias', params_shape, initializer=tf.zeros_initializer)
return (x + bias)
axis = list(range((len(x_shape) - 1)))
beta = _get_variable('beta', params_shape, initializer=tf.zer... |
def fc(x, c):
num_units_in = x.get_shape()[1]
num_units_out = c['fc_units_out']
weights_initializer = tf.truncated_normal_initializer(stddev=FC_WEIGHT_STDDEV)
weights = _get_variable('weights', shape=[num_units_in, num_units_out], initializer=weights_initializer, weight_decay=FC_WEIGHT_STDDEV)
bia... |
def _get_variable(name, shape, initializer, weight_decay=0.0, dtype='float', trainable=True):
'A little wrapper around tf.get_variable to do weight decay and add to'
'resnet collection'
if (weight_decay > 0):
regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
else:
regularize... |
def conv(x, c):
ksize = c['ksize']
stride = c['stride']
filters_out = c['conv_filters_out']
filters_in = x.get_shape()[(- 1)]
shape = [ksize, ksize, filters_in, filters_out]
initializer = tf.truncated_normal_initializer(stddev=CONV_WEIGHT_STDDEV)
weights = _get_variable('weights', shape=sh... |
def _max_pool(x, ksize=3, stride=2):
return tf.nn.max_pool(x, ksize=[1, ksize, ksize, 1], strides=[1, stride, stride, 1], padding='SAME')
|
def read_cifar10(filename_queue):
'Reads and parses examples from CIFAR10 data files.\n\n Recommendation: if you want N-way read parallelism, call this function\n N times. This will give you N independent Readers reading different\n files & positions within those files, which will give better mixing of\n exa... |
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle):
'Construct a queued batch of images and labels.\n\n Args:\n image: 3-D Tensor of [height, width, 3] of type.float32.\n label: 1-D Tensor of type.int32\n min_queue_examples: int32, minimum number of samples to ret... |
def distorted_inputs(data_dir, batch_size):
'Construct distorted input for CIFAR training using the Reader ops.\n\n Args:\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.\... |
def inputs(eval_data, data_dir, batch_size):
'Construct input for CIFAR evaluation using the Reader ops.\n\n Args:\n eval_data: bool, indicating if one should use the train or eval data set.\n data_dir: Path to the CIFAR-10 data directory.\n batch_size: Number of images per batch.\n\n Returns:\n ima... |
def maybe_download_and_extract():
"Download and extract the tarball from Alex's website."
dest_directory = FLAGS.data_dir
if (not os.path.exists(dest_directory)):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[(- 1)]
filepath = os.path.join(dest_directory, filename)
if (not... |
def main(argv=None):
maybe_download_and_extract()
(images_train, labels_train) = distorted_inputs(FLAGS.data_dir, FLAGS.batch_size)
(images_val, labels_val) = inputs(True, FLAGS.data_dir, FLAGS.batch_size)
is_training = tf.placeholder('bool', [], name='is_training')
(images, labels) = tf.cond(is_t... |
def generate_prompt(data_point):
if data_point['input']:
return f''' # noqa: E501
{data_point['instruction']}
### input:
{data_point['input']}
### Response:
{data_point['output']}'''
else:
return f'''Below is an instruction that describes a task. Write a response that appropriately completes... |
def generate_and_tokenize_prompt(data_point):
full_prompt = generate_prompt(data_point)
tokenized_full_prompt = tokenize(full_prompt)
user_prompt = generate_prompt({**data_point, 'output': ''})
tokenized_user_prompt = tokenize(user_prompt, add_eos_token=False)
user_prompt_len = len(tokenized_user_... |
def tokenize(prompt, add_eos_token=True):
cutoff_len = 256
result = tokenizer(prompt, truncation=True, max_length=cutoff_len, padding=False, return_tensors=None)
if ((result['input_ids'][(- 1)] != tokenizer.eos_token_id) and (len(result['input_ids']) < cutoff_len) and add_eos_token):
result['input... |
def main(load_8bit: bool=False, base_model: str='', lora_weights: str='tloen/alpaca-lora-7b', share_gradio: bool=True):
assert base_model, "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
tokenizer = LlamaTokenizer.from_pretrained(base_model)
if (device == 'cuda'):
... |
def generate_prompt(instruction, input=None):
if input:
return f'''Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. # noqa: E501
### Instruction:
{instruction}
### Input:
{input}
### Response:
... |
def train(base_model: str='', data_path: str='yahma/alpaca-cleaned', output_dir: str='/common/users/jj635/llama/mycheckpoint/', batch_size: int=128, micro_batch_size: int=4, num_epochs: int=3, learning_rate: float=0.0003, cutoff_len: int=256, val_set_size: int=0, lora_r: int=8, lora_alpha: int=16, lora_dropout: float... |
def generate_prompt(data_point):
if data_point['input']:
return f''' # noqa: E501
{data_point['instruction']}
### input:
{data_point['input']}
### Response:
{data_point['output']}'''
else:
return f'''Below is an instruction that describes a task. Write a response that appropriately completes... |
def generate_prompt(data_point):
if data_point['input']:
return f''' # noqa: E501
{data_point['instruction']}
### input:
{data_point['input']}
### Response:
{data_point['output']}'''
else:
return f'''Below is an instruction that describes a task. Write a response that appropriately completes... |
def generate_and_tokenize_prompt(data_point):
full_prompt = generate_prompt(data_point)
tokenized_full_prompt = tokenize(full_prompt)
user_prompt = generate_prompt({**data_point, 'output': ''})
tokenized_user_prompt = tokenize(user_prompt, add_eos_token=False)
user_prompt_len = len(tokenized_user_... |
def tokenize(prompt, add_eos_token=True):
cutoff_len = 256
result = tokenizer(prompt, truncation=True, max_length=cutoff_len, padding=False, return_tensors=None)
if ((result['input_ids'][(- 1)] != tokenizer.eos_token_id) and (len(result['input_ids']) < cutoff_len) and add_eos_token):
result['input... |
def permute(w):
return w.view(n_heads, ((dim // n_heads) // 2), 2, dim).transpose(1, 2).reshape(dim, dim)
|
def unpermute(w):
return w.view(n_heads, 2, ((dim // n_heads) // 2), dim).transpose(1, 2).reshape(dim, dim)
|
def translate_state_dict_key(k):
k = k.replace('base_model.model.', '')
if (k == 'model.embed_tokens.weight'):
return 'tok_embeddings.weight'
elif (k == 'model.norm.weight'):
return 'norm.weight'
elif (k == 'lm_head.weight'):
return 'output.weight'
elif k.startswith('model.... |
def main(load_8bit: bool=False, base_model: str='', lora_weights: str='tloen/alpaca-lora-7b', share_gradio: bool=True):
assert base_model, "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
tokenizer = LlamaTokenizer.from_pretrained(base_model)
if (device == 'cuda'):
... |
def generate_prompt(instruction, input=None):
if input:
return f'''Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. # noqa: E501
### Instruction:
{instruction}
### Input:
{input}
### Response:
... |
def train(base_model: str='', data_path: str='yahma/alpaca-cleaned', output_dir: str='/common/users/jj635/llama/mycheckpoint/', batch_size: int=128, micro_batch_size: int=4, num_epochs: int=3, learning_rate: float=0.0003, cutoff_len: int=256, val_set_size: int=0, lora_r: int=8, lora_alpha: int=16, lora_dropout: float... |
def generate_prompt(data_point):
if data_point['input']:
return f''' # noqa: E501
{data_point['instruction']}
### input:
{data_point['input']}
### Response:
{data_point['output']}'''
else:
return f'''Below is an instruction that describes a task. Write a response that appropriately completes... |
class CelebA(data.Dataset):
'Dataset class for the CelebA dataset.'
def __init__(self, image_dir, attr_path, selected_attrs, transform, mode):
'Initialize and preprocess the CelebA dataset.'
self.image_dir = image_dir
self.attr_path = attr_path
self.selected_attrs = selected_a... |
def get_loader(batch_size, image_dir, attr_path, selected_attrs, crop_size=178, image_size=128, dataset='CelebA', mode='train', num_workers=16):
'Build and return a data loader.'
transform = []
if (mode == 'train'):
transform.append(T.RandomHorizontalFlip())
transform.append(T.CenterCrop(crop_... |
class EncoderBlock(nn.Module):
def __init__(self, channel_in, channel_out):
super(EncoderBlock, self).__init__()
self.conv = nn.Conv2d(in_channels=channel_in, out_channels=channel_out, kernel_size=5, padding=2, stride=2, bias=False)
self.bn = nn.BatchNorm2d(num_features=channel_out, momen... |
class DecoderBlock(nn.Module):
def __init__(self, channel_in, channel_out):
super(DecoderBlock, self).__init__()
self.conv = nn.ConvTranspose2d(channel_in, channel_out, kernel_size=5, padding=2, stride=2, output_padding=1, bias=False)
self.bn = nn.BatchNorm2d(channel_out, momentum=0.9)
... |
class Encoder(nn.Module):
def __init__(self, channel_in=3, z_size=128):
super(Encoder, self).__init__()
self.size = channel_in
layers_list = []
for i in range(3):
if (i == 0):
layers_list.append(EncoderBlock(channel_in=self.size, channel_out=64))
... |
class Decoder(nn.Module):
def __init__(self, z_size, size):
super(Decoder, self).__init__()
self.fc = nn.Sequential(nn.Linear(in_features=z_size, out_features=((8 * 8) * size), bias=False), nn.BatchNorm1d(num_features=((8 * 8) * size), momentum=0.9), nn.ReLU(True))
self.size = size
... |
class Discriminator(nn.Module):
def __init__(self, channel_in=3, recon_level=3):
super(Discriminator, self).__init__()
self.size = channel_in
self.recon_levl = recon_level
self.conv = nn.ModuleList()
self.conv.append(nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, ... |
class VaeGan(nn.Module):
def __init__(self, z_size=128, recon_level=3):
super(VaeGan, self).__init__()
self.z_size = z_size
self.encoder = Encoder(z_size=self.z_size)
self.decoder = Decoder(z_size=self.z_size, size=self.encoder.size)
self.discriminator = Discriminator(chan... |
def adult_benchmark():
data = Dataset.load('../data/adult.csv', '../data/adult-domain.json')
projections = [('occupation', 'race', 'capital-loss'), ('occupation', 'sex', 'native-country'), ('marital-status', 'relationship', 'income>50K'), ('age', 'education-num', 'sex'), ('workclass', 'education-num', 'occupa... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = 'adult'
params['engines'] = ['MD', 'RDA']
params['iters'] = 10000
params['epsilon'] = 1.0... |
class Negated(matrix.EkteloMatrix):
def __init__(self, Q):
self.Q = Q
self.shape = Q.shape
self.dtype = np.float64
@property
def matrix(self):
return (1 - self.Q.dense_matrix())
def _matvec(self, x):
return (x.sum() - self.Q.dot(x))
def _transpose(self):... |
def max_sum_ve(factors, domain=None, elim=None):
' run max-product variable elimination on the factors\n return the most likely assignment as a dictionary where\n keys are attributes\n values are elements of the domain\n '
if (domain is None):
domain = reduce(Domain.merge, [F.domai... |
def answer_workload(workload, data):
ans = [W.dot(data.project(cl).datavector()) for (cl, W) in workload]
return np.concatenate(ans)
|
def DualQuery(data, workload, eps=1.0, delta=0.001, seed=0):
prng = np.random.RandomState(seed)
total = data.df.shape[0]
domain = data.domain
answers = (answer_workload(workload, data) / total)
nu = 2.0
s = 50
T = 2
while (((((2 * nu) * (T - 1)) / total) * np.sqrt((((((2 * s) * (T - 1)... |
def log_likelihood(answers, cache):
nu = 2.0
Qsize = sum((W.shape[0] for (_, W) in workload))
logQ = (np.zeros(Qsize) - np.log(Qsize))
ans = 0
for (idx, a) in cache:
probas = logQ[idx]
logQ = (logQ - (nu * (answers - a)))
logQ = (logQ - logsumexp(logQ))
ans += np.su... |
def marginal_loss(marginals, workload, cache):
answers = []
for (proj, W) in workload:
for cl in marginals:
if (set(proj) <= set(cl)):
mu = marginals[cl].project(proj)
x = mu.values.flatten()
answers.append(W.dot(x))
break
... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = 'adult'
params['iters'] = 10000
params['epsilon'] = 1.0
params['seed'] = 0
return par... |
def get_measurements(domain, workload):
lookup = {}
for attr in domain:
n = domain.size(attr)
lookup[attr] = Identity(n)
lookup['age'] = EkteloMatrix(np.load('prefix-85.npy'))
lookup['fnlwgt'] = EkteloMatrix(np.load('prefix-100.npy'))
lookup['capital-gain'] = EkteloMatrix(np.load('... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = 'adult'
params['iters'] = 10000
params['epsilon'] = 1.0
params['seed'] = 0
return par... |
class ProductDist():
' factored representation of data from MWEM paper '
def __init__(self, factors, domain, total):
'\n :param factors: a list of contingency tables, \n defined over disjoint subsets of attributes\n :param domain: the domain object\n :param total: ... |
class FactoredMultiplicativeWeights():
def __init__(self, domain, iters=100):
self.domain = domain
self.iters = iters
def infer(self, measurements, total):
self.multWeightsFast(measurements, total)
return self.model
def multWeightsFast(self, measurements, total):
... |
def _cluster(measurement_cache):
'\n Cluster the measurements into disjoint subsets by finding the connected \n components of the graph implied by the measurement projections\n '
k = len(measurement_cache)
G = sparse.dok_matrix((k, k))
for (i, (_, _, _, p)) in enumerate(measurement_cache):
... |
def average_error(workload, data, est):
errors = []
for (ax, W) in workload:
x = data.project(ax).datavector()
xest = est.project(ax).datavector()
ans = W.dot((x - xest))
err = (np.linalg.norm(W.dot((x - xest)), 1) / np.linalg.norm(W.dot(x), 1))
errors.append(err)
r... |
def worst_approximated(data, est, workload, eps, prng=None):
if (prng == None):
prng = np.random
errors = np.array([])
for (ax, W) in workload:
x = data.project(ax).datavector()
xest = est.project(ax).datavector()
W = matrix.Identity(x.size)
errors = np.append(error... |
def mwem(workload, data, eps, engine, iters=10, prng=None, out=None):
eps1 = (eps / (2.0 * iters))
total = data.df.shape[0]
measurements = []
est = engine.infer(measurements, total)
for i in range(iters):
(ax, Q) = worst_approximated(data, est, workload, eps1, prng)
proj = data.pro... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = 'adult'
params['engine'] = 'PGM'
params['iters'] = 1000
params['rounds'] = None
param... |
class Identity(sparse.linalg.LinearOperator):
def __init__(self, n):
self.shape = (n, n)
self.dtype = np.float64
def _matmat(self, X):
return X
def __matmul__(self, X):
return X
def _transpose(self):
return self
def _adjoint(self):
return self
|
def powerset(iterable):
"Returns powerset of set consisting of elements in ``iterable``.\n Args:\n iterable (iterable): Set that powerset will be taken over\n\n Returns:\n iterator: the powerset\n\n Example:\n >>> pset = powerset(['a','b'])\n >>> list(pset)\n [('a',), (... |
def downward_closure(cliques):
"Returns the 'downward closure' of a list of cliques. The 'downward closure'\n is the union of powersets of each individual clique in a list. Elements within\n each clique are sorted, but the list of cliques is not.\n\n Args:\n cliques ([iterable]): List of cliques\n... |
def get_permutation_matrix(cl1, cl2, domain):
'Using the vector-of-counts representation of a database detailed in\n [Li 2012], we create a permutation matrix which maps the database with\n attributes in order cl1 to database with attributes in order cl2. Note that\n cl1 and cl2 contain the same elements... |
def get_aggregate(cl, matrices, domain):
'Returns additional measurement matrices by taking the Kronecker\n product between Identity and previous measurements.\n\n Args:\n cl (iterable): A clique marginal.\n matrices (dict): A dictionary of measurement matrices where the key is\n th... |
def get_identity(cl, post_plausibility, domain):
'Determine which cells in the cl marginal *could* have a count above\n threshold based on previous measurements.\n\n Args:\n cl (iterable): A clique marginal\n post_plausibility (dict): Dictionary of previously taken measurements.\n T... |
def exponential_mechanism(q, eps, sensitivity, prng=np.random, monotonic=False):
'Performs the exponential mechanism. Returned results satisfy eps-DP.\n\n Args:\n q (ndarray): Weights for each item.\n eps (float): Privacy parameter.\n sensitivity (float): Sensitivity of the query.\n ... |
def select(data, model, rho, targets=[]):
'Selects additional measurements using Minimum Spanning Tree based method\n with the exponential mechanism being used to privately select candidate\n edges. Weights for each edge of the tree are based on the L1 norm between\n the marginal counts from the data and... |
def adagrid(data, epsilon, delta, threshold, targets=[], split_strategy=None, **mbi_args):
'Implements the Adagrid mechanism used in Sprint 3 of NIST 2021\n Competition by Team Minutemen.\n\n Args:\n data (mbi.Dataset): The sensitive dataset.\n epsilon (float): Privacy parameter.\n delt... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = 'datasets/adult.zip'
params['domain'] = 'datasets/adult-domain.json'
params['epsilon'] = 1.0
... |
def powerset(iterable):
'powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)'
s = list(iterable)
return itertools.chain.from_iterable((itertools.combinations(s, r) for r in range(1, (len(s) + 1))))
|
def downward_closure(Ws):
ans = set()
for proj in Ws:
ans.update(powerset(proj))
return list(sorted(ans, key=len))
|
def hypothetical_model_size(domain, cliques):
model = GraphicalModel(domain, cliques)
return ((model.size * 8) / (2 ** 20))
|
def compile_workload(workload):
def score(cl):
return sum((len((set(cl) & set(ax))) for ax in workload))
return {cl: score(cl) for cl in downward_closure(workload)}
|
def filter_candidates(candidates, model, size_limit):
ans = {}
free_cliques = downward_closure(model.cliques)
for cl in candidates:
cond1 = (hypothetical_model_size(model.domain, (model.cliques + [cl])) <= size_limit)
cond2 = (cl in free_cliques)
if (cond1 or cond2):
an... |
class AIM(Mechanism):
def __init__(self, epsilon, delta, prng=None, rounds=None, max_model_size=80, structural_zeros={}):
super(AIM, self).__init__(epsilon, delta, prng)
self.rounds = rounds
self.max_model_size = max_model_size
self.structural_zeros = structural_zeros
def wor... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = '../data/adult.csv'
params['domain'] = '../data/adult-domain.json'
params['epsilon'] = 1.0
... |
def cdp_delta_standard(rho, eps):
assert (rho >= 0)
assert (eps >= 0)
if (rho == 0):
return 0
return math.exp(((- ((eps - rho) ** 2)) / (4 * rho)))
|
def cdp_delta(rho, eps):
assert (rho >= 0)
assert (eps >= 0)
if (rho == 0):
return 0
amin = 1.01
amax = (((eps + 1) / (2 * rho)) + 2)
for i in range(1000):
alpha = ((amin + amax) / 2)
derivative = (((((2 * alpha) - 1) * rho) - eps) + math.log1p(((- 1.0) / alpha)))
... |
def cdp_eps(rho, delta):
assert (rho >= 0)
assert (delta > 0)
if ((delta >= 1) or (rho == 0)):
return 0.0
epsmin = 0.0
epsmax = (rho + (2 * math.sqrt((rho * math.log((1 / delta))))))
for i in range(1000):
eps = ((epsmin + epsmax) / 2)
if (cdp_delta(rho, eps) <= delta):
... |
def cdp_rho(eps, delta):
assert (eps >= 0)
assert (delta > 0)
if (delta >= 1):
return 0.0
rhomin = 0.0
rhomax = (eps + 1)
for i in range(1000):
rho = ((rhomin + rhomax) / 2)
if (cdp_delta(rho, eps) <= delta):
rhomin = rho
else:
rhomax = r... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = '../data/adult.csv'
params['domain'] = '../data/adult-domain.json'
params['epsilon'] = 1.0
... |
def convert_matrix(domain, cliques):
weights = {}
for proj in cliques:
tpl = tuple([domain.attrs.index(i) for i in proj])
weights[tpl] = 1.0
return workload.Marginals.fromtuples(domain.shape, weights)
|
def convert_back(domain, Q):
cliques = []
weights = []
for Qi in Q.matrices:
wgt = Qi.weight
key = tuple([domain.attrs[i] for i in Qi.base.tuple()])
cliques.append(key)
weights.append(wgt)
return (cliques, weights)
|
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = '../data/adult.csv'
params['domain'] = '../data/adult-domain.json'
params['epsilon'] = 1.0
... |
def optm(queries, approx=False):
W = convert_matrix(data.domain, queries)
if os.path.exists(strategy_path):
print('loading strategy from file')
A = pickle.load(open(strategy_path, 'rb'))
else:
print('optimizing strategy, could take a while')
best_obj = np.inf
for _ ... |
def opt_plus(queries, approx=False):
weights = np.ones(len(queries))
return (queries, weights)
|
def MST(data, epsilon, delta):
rho = cdp_rho(epsilon, delta)
sigma = np.sqrt((3 / (2 * rho)))
cliques = [(col,) for col in data.domain]
log1 = measure(data, cliques, sigma)
(data, log1, undo_compress_fn) = compress_domain(data, log1)
cliques = select(data, (rho / 3.0), log1)
log2 = measure... |
def measure(data, cliques, sigma, weights=None):
if (weights is None):
weights = np.ones(len(cliques))
weights = (np.array(weights) / np.linalg.norm(weights))
measurements = []
for (proj, wgt) in zip(cliques, weights):
x = data.project(proj).datavector()
y = (x + np.random.norm... |
def compress_domain(data, measurements):
supports = {}
new_measurements = []
for (Q, y, sigma, proj) in measurements:
col = proj[0]
sup = (y >= (3 * sigma))
supports[col] = sup
if (supports[col].sum() == y.size):
new_measurements.append((Q, y, sigma, proj))
... |
def exponential_mechanism(q, eps, sensitivity, prng=np.random, monotonic=False):
coef = (1.0 if monotonic else 0.5)
scores = (((coef * eps) / sensitivity) * q)
probas = np.exp((scores - logsumexp(scores)))
return prng.choice(q.size, p=probas)
|
def select(data, rho, measurement_log, cliques=[]):
engine = FactoredInference(data.domain, iters=1000)
est = engine.estimate(measurement_log)
weights = {}
candidates = list(itertools.combinations(data.domain.attrs, 2))
for (a, b) in candidates:
xhat = est.project([a, b]).datavector()
... |
def transform_data(data, supports):
df = data.df.copy()
newdom = {}
for col in data.domain:
support = supports[col]
size = support.sum()
newdom[col] = int(size)
if (size < support.size):
newdom[col] += 1
mapping = {}
idx = 0
for i in rang... |
def reverse_data(data, supports):
df = data.df.copy()
newdom = {}
for col in data.domain:
support = supports[col]
mx = support.sum()
newdom[col] = int(support.size)
(idx, extra) = (np.where(support)[0], np.where((~ support))[0])
mask = (df[col] == mx)
if (ex... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = '../data/adult.csv'
params['domain'] = '../data/adult-domain.json'
params['epsilon'] = 1.0
... |
def worst_approximated(workload_answers, est, workload, eps, penalty=True, bounded=False):
' Select a (noisy) worst-approximated marginal for measurement.\n \n :param workload_answers: a dictionary of true answers to the workload\n keys are cliques\n values are numpy arrays, corresponding to t... |
def mwem_pgm(data, epsilon, delta=0.0, workload=None, rounds=None, maxsize_mb=25, pgm_iters=1000, noise='gaussian', bounded=False, alpha=0.9):
'\n Implementation of MWEM + PGM\n\n :param data: an mbi.Dataset object\n :param epsilon: privacy budget\n :param delta: privacy parameter (ignored)\n :para... |
def default_params():
'\n Return default parameters to run this program\n\n :returns: a dictionary of default parameter settings for each command line argument\n '
params = {}
params['dataset'] = '../data/adult.csv'
params['domain'] = '../data/adult-domain.json'
params['epsilon'] = 1.0
... |
class CallBack():
' A CallBack is a function called after every iteration of an iterative optimization procedure\n It is useful for tracking loss and other metrics over time.\n '
def __init__(self, engine, frequency=50):
' Initialize the callback objet\n\n :param engine: the FactoredInfe... |
class Logger(CallBack):
' Logger is the default callback function. It tracks the time, L1 loss, L2 loss, and\n optionally the total variation distance to the true query answers (when available).\n The last is for debugging purposes only - in practice the true answers can not be observed.\n '
... |
class CliqueVector(dict):
' This is a convenience class for simplifying arithmetic over the \n concatenated vector of marginals and potentials.\n\n These vectors are represented as a dictionary mapping cliques (subsets of attributes)\n to marginals/potentials (Factor objects)\n '
def ... |
class Domain():
def __init__(self, attrs, shape):
' Construct a Domain object\n \n :param attrs: a list or tuple of attribute names\n :param shape: a list or tuple of domain sizes for each attribute\n '
assert (len(attrs) == len(shape)), 'dimensions must be equal'
... |
class Factor():
def __init__(self, domain, values):
' Initialize a factor over the given domain\n\n :param domain: the domain of the factor\n :param values: the ndarray of factor values (for each element of the domain)\n\n Note: values may be a flattened 1d array or a ndarray with sa... |
class FactorGraph():
def __init__(self, domain, cliques, total=1.0, convex=False, iters=25):
self.domain = domain
self.cliques = cliques
self.total = total
self.convex = convex
self.iters = iters
if convex:
self.counting_numbers = self.get_counting_numb... |
class FactoredInference():
def __init__(self, domain, backend='numpy', structural_zeros={}, metric='L2', log=False, iters=1000, warm_start=False, elim_order=None):
'\n Class for learning a GraphicalModel from noisy measurements on a data distribution\n \n :param domain: The domain i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.