code stringlengths 17 6.64M |
|---|
def conv1d(input_, output_dim, initializer='xavier', k_w=5, d_w=1, stddev=0.02, padding='VALID', reuse=False, name='conv1d'):
with tf.variable_scope(name, reuse=reuse):
if (initializer == 'xavier'):
init_type = tf.contrib.layers.xavier_initializer()
elif (initializer == 'normal'):
... |
def conv2d(input_, output_dim, initializer='xavier', k_h=5, k_w=5, d_h=1, d_w=1, stddev=0.02, padding='VALID', reuse=False, name='conv2d'):
with tf.variable_scope(name, reuse=reuse):
if (initializer == 'xavier'):
init_type = tf.contrib.layers.xavier_initializer()
elif (initializer == '... |
def conv2da(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='conv2d', reuse=False, padding='SAME'):
with tf.variable_scope(name, reuse=reuse):
w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[(- 1)], output_dim], initializer=tf.contrib.layers.xavier_initializer())
conv = tf... |
def conv2dp(input_, output_dim, params, d_h=1, d_w=1):
w = tf.Variable(params[0])
conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME')
biases = tf.Variable(params[1])
conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape())
return conv
|
def conv3d(input_, output_dim, initializer='xavier', k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='conv3d'):
with tf.variable_scope(name):
if (initializer == 'xavier'):
init_type = tf.contrib.layers.xavier_initializer()
elif (initializer == 'normal'):
init_type = tf.trunca... |
def deconv2d(input_, output_shape, initializer='xavier', k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name='deconv2d', with_w=False):
with tf.variable_scope(name):
if (initializer == 'xavier'):
init_type = tf.contrib.layers.xavier_initializer()
elif (initializer == 'normal'):
i... |
def lrelu(x, leak=0.2, name='lrelu'):
with tf.variable_scope(name):
f1 = (0.5 * (1 + leak))
f2 = (0.5 * (1 - leak))
return ((f1 * x) + (f2 * abs(x)))
|
def relu(x):
return tf.nn.relu(x)
|
def tanh(x):
return tf.nn.tanh(x)
|
def shape2d(a):
'\n a: a int or tuple/list of length 2\n '
if (type(a) == int):
return [a, a]
if isinstance(a, (list, tuple)):
assert (len(a) == 2)
return list(a)
raise RuntimeError('Illegal shape: {}'.format(a))
|
def shape4d(a):
return (([1] + shape2d(a)) + [1])
|
def UnPooling2x2ZeroFilled(x):
out = tf.concat(3, [x, tf.zeros_like(x)])
out = tf.concat(2, [out, tf.zeros_like(out)])
sh = x.get_shape().as_list()
if (None not in sh[1:]):
out_size = [(- 1), (sh[1] * 2), (sh[2] * 2), sh[3]]
return tf.reshape(out, out_size)
else:
sh = tf.sh... |
def MaxPooling(x, shape, stride=None, padding='VALID'):
"\n MaxPooling on images.\n :param input: NHWC tensor.\n :param shape: int or [h, w]\n :param stride: int or [h, w]. default to be shape.\n :param padding: 'valid' or 'same'. default to 'valid'\n :returns: NHWC tensor.\n "
padding = ... |
def FixedUnPooling(x, shape, unpool_mat=None):
'\n Unpool the input with a fixed mat to perform kronecker product with.\n :param input: NHWC tensor\n :param shape: int or [h, w]\n :param unpool_mat: a tf/np matrix with size=shape. If None, will use a mat\n with 1 at top-left corner.\n :retur... |
def linear(input_, output_size, name, stddev=0.02, bias_start=0.0, reuse=False, with_w=False):
shape = input_.get_shape().as_list()
with tf.variable_scope(name, reuse=reuse):
matrix = tf.get_variable('Matrix', [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev))
bi... |
class BatchCoCaBO(CoCaBO_Base):
def __init__(self, objfn, initN, bounds, acq_type, C, **kwargs):
super(BatchCoCaBO, self).__init__(objfn, initN, bounds, acq_type, C, **kwargs)
self.best_val_list = []
self.C_list = self.C
self.name = 'BCoCaBO'
def runOptim(self, budget, seed, ... |
class CoCaBO(CoCaBO_Base):
def __init__(self, objfn, initN, bounds, acq_type, C, **kwargs):
super(CoCaBO, self).__init__(objfn, initN, bounds, acq_type, C, **kwargs)
self.best_val_list = []
self.C_list = self.C
self.name = 'CoCaBO'
def runOptim(self, budget, seed, batch_size=... |
def CoCaBO_Exps(obj_func, budget, initN=24, trials=40, kernel_mix=0.5, batch=None):
saving_path = f'data/syntheticFns/{obj_func}/'
if (not os.path.exists(saving_path)):
os.makedirs(saving_path)
if (obj_func == 'func2C'):
f = testFunctions.syntheticFunctions.func2C
categories = [3, ... |
def DepRound(weights_p, k=1, isWeights=True):
' [[Algorithms for adversarial bandit problems with multiple plays, by T.Uchiya, A.Nakamura and M.Kudo, 2010](http://hdl.handle.net/2115/47057)] Figure 5 (page 15) is a very clean presentation of the algorithm.\n\n - Inputs: :math:`k < K` and weights_p :math:`= (p_... |
class AcquisitionFunction(object):
'\n Base class for acquisition functions. Used to define the interface\n '
def __init__(self, surrogate=None, verbose=False):
self.surrogate = surrogate
self.verbose = verbose
def evaluate(self, x: np.ndarray, **kwargs) -> np.ndarray:
rais... |
class AcquisitionOnSubspace():
def __init__(self, acq, free_idx, fixed_vals):
self.acq = acq
self.free_idx = free_idx
self.fixed_vals = fixed_vals
def evaluate(self, x: np.ndarray, **kwargs):
x_fixed = ([self.fixed_vals] * len(x))
x_complete = np.hstack((np.vstack(x_f... |
class EI(AcquisitionFunction):
'\n Expected improvement acquisition function for a Gaussian model\n\n Model should return (mu, var)\n '
def __init__(self, surrogate: GP, best: np.ndarray, verbose=False):
self.best = best
super().__init__(surrogate, verbose)
def __str__(self) -> ... |
class PI(AcquisitionFunction):
'\n Probability of improvement acquisition function for a Gaussian model\n\n Model should return (mu, var)\n '
def __init__(self, surrogate: GP, best: np.ndarray, tradeoff: float, verbose=False):
self.best = best
self.tradeoff = tradeoff
super()... |
class UCB(AcquisitionFunction):
'\n Upper confidence bound acquisition function for a Gaussian model\n\n Model should return (mu, var)\n '
def __init__(self, surrogate: GP, tradeoff: float, verbose=False):
self.tradeoff = tradeoff
super().__init__(surrogate, verbose)
def __str__... |
class AsyncBayesianOptimization(BayesianOptimisation):
"Async Bayesian optimization class\n\n Performs Bayesian optimization with a set number of busy and free workers\n\n Parameters\n ----------\n sampler : Callable\n function handle returning sample from expensive function being\n opti... |
class AsyncBOHeuristicQEI(AsyncBayesianOptimization):
"Async BO with approximate q-EI\n\n Q-EI is approximated by sequentially finding the best location and\n setting its y-value using one of Ginsbourger's heuristics until the\n batch is full\n "
def __init__(self, sampler, surrogate, bounds, asy... |
class BatchBOHeuristic(AsyncBOHeuristicQEI):
pass
|
class ExecutorBase():
'Base interface for interaction with multiple parallel workers\n\n The simulator and real async interfaces will subclass this class so that\n their interfaces are the same\n\n Main way to interact with this object is to queue jobs using\n add_job_to_queue(), to wait until the des... |
class JobExecutor(ExecutorBase):
"Async controller that interacts with external async function calls\n\n Will be used to run ML algorithms in parallel for synch and async BO\n\n Functions that run must take in a job dict and return the same\n job dict with the result ['y'] and runtime ['t'].\n "
... |
class JobExecutorInSeries(JobExecutor):
'Interface that runs the jobs in series\n but acts like a batch-running interface to the outside.\n\n self._futures is not a list of futures any more. This is a placeholder\n for the jobs that have yet to run to complete the batch\n '
def __init__(self, n_w... |
class JobExecutorInSeriesBlocking(ExecutorBase):
"Interface that runs the jobs in series and blocks execution of code\n until it's done\n "
def __init__(self, n_workers: int, verbose=False):
super().__init__(n_workers, verbose=verbose)
self._creation_time = time.time()
def run_unti... |
def add_hallucinations_to_x_and_y(bo, old_x, old_y, x_new, fixed_dim_vals=None) -> Tuple[(np.ndarray, np.ndarray)]:
'Add hallucinations to the data arrays.\n\n Parameters\n ----------\n old_x\n Current x values\n old_y\n Current y values\n x_new\n Locations at which to use the ... |
def make_hallucinated_data(bo, x: np.ndarray, strat: str) -> np.ndarray:
"Returns fake y-values based on the chosen heuristic\n\n Parameters\n ----------\n x\n Used to get the value for the kriging believer. Otherwise, this\n sets the number of values returned\n\n bo\n Instance of... |
def draw(weights):
choice = random.uniform(0, sum(weights))
choiceIndex = 0
for weight in weights:
choice -= weight
if (choice <= 0):
return choiceIndex
choiceIndex += 1
|
def distr(weights, gamma=0.0):
theSum = float(sum(weights))
return tuple(((((1.0 - gamma) * (w / theSum)) + (gamma / len(weights))) for w in weights))
|
def mean(aList):
theSum = 0
count = 0
for x in aList:
theSum += x
count += 1
return (0 if (count == 0) else (theSum / count))
|
def with_proba(epsilon):
'Bernoulli test, with probability :math:`\x0barepsilon`, return `True`, and with probability :math:`1 - \x0barepsilon`, return `False`.\n\n Example:\n\n >>> from random import seed; seed(0) # reproductible\n >>> with_proba(0.5)\n False\n >>> with_proba(0.9)\n True\n ... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
parser.add_argument('--section', required=True)
parser.add_argument('--inferred', required=True)
parser.add_argument('--output')
parser.add_argument('--logdir'... |
def main():
all_commands = []
all_eval_commands = []
for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), (10, 20, 40, 80)):
steps = (list(range(1100, 40000, 1000)) + [40000])
logdir = 'logdirs/20190425-django-allmatches-anysplit-multimean/filt-{... |
def main():
for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), (10, 20, 40, 80)):
steps = list(range(100, 2600, 100))
args = "{{filt: '{filt}', st: '{st}', nt: {nt}}}".format(filt=filt, st=st, nt=nt)
logdir = os.path.join('logdirs/20190201-hs-a... |
def main():
for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), (10, 20, 40, 80)):
steps = list(range(100, 2600, 100))
args = "{{filt: '{filt}', st: '{st}', nt: {nt}}}".format(filt=filt, st=st, nt=nt)
logdir = os.path.join('logdirs/20190201-hs-a... |
def main():
for att in (0, 1):
steps = list(range(100, 2600, 100))
logdir = os.path.join('logdirs/20181231-nl2code-hearthstone-fef2c5b', 'att{}'.format(att))
for step in steps:
if (not os.path.exists(os.path.join(logdir, 'model_checkpoint-{:08d}'.format(step)))):
... |
def main():
for (output_from, upd_steps) in itertools.product(('true', 'false'), (0, 1, 2)):
job_name = 'output_from={},upd_steps={}'.format(output_from, upd_steps)
commands = []
for (qenc, ctenc, tinc) in itertools.product(('e', 'eb'), ('e', 'eb', 'ebs'), ('true', 'false')):
c... |
def main():
job_name = 'spider_att3'
commands = []
for (output_from, upd_steps) in itertools.product(('true', 'false'), (0, 1, 2)):
for (qenc, ctenc, tinc) in itertools.product(('e', 'eb'), ('e', 'eb', 'ebs'), ('true', 'false')):
if ((output_from, qenc, ctenc, tinc, upd_steps) not in (... |
def main():
for (output_from, upd_steps) in itertools.product(('true', 'false'), (0, 1, 2)):
job_name = 'output_from={},upd_steps={}'.format(output_from, upd_steps)
commands = []
for (qenc, ctenc, tinc, step) in itertools.product(('e', 'eb'), ('e', 'eb', 'ebs'), ('true', 'false'), (list(ra... |
def main():
for (output_from, upd_steps) in itertools.product(('true', 'false'), (3, 4, 5, 6)):
job_name = 'output_from={},upd_steps={}'.format(output_from, upd_steps)
commands = []
for ((qenc, ctenc), max_steps, batch_size) in itertools.product((('e', 'e'), ('eb', 'ebs')), ('40000', '8000... |
def main():
for (output_from, upd_steps) in itertools.product(('true', 'false'), (2, 3, 4, 5, 6)):
job_name = 'output_from={},upd_steps={}'.format(output_from, upd_steps)
commands = []
for ((qenc, ctenc), max_steps, batch_size) in itertools.product((('e', 'e'), ('eb', 'ebs')), ('40000', '8... |
def main():
for (output_from, upd_steps) in itertools.product(('true', 'false'), (2, 3, 4, 5, 6)):
job_name = 'output_from={},upd_steps={}'.format(output_from, upd_steps)
commands = []
for ((qenc, ctenc), max_steps, batch_size) in itertools.product((('e', 'e'), ('eb', 'ebs')), ('40000', '8... |
def main():
all_commands = []
all_eval_commands = []
for (output_from, upd_steps) in itertools.product(('true', 'false'), (2, 3, 4, 5, 6)):
job_name = 'e0223,{},{}'.format(output_from, upd_steps)
commands = []
total = ((2 * 2) * (20 + 40))
i = 0
for ((qenc, ctenc), ... |
def main():
all_commands = []
all_eval_commands = []
for (output_from, max_steps, batch_size) in itertools.product(('true', 'false'), (40000, 80000), (10, 20)):
if (max_steps == 40000):
steps = (list(range(2100, 40000, 2000)) + [40000])
elif (max_steps == 80000):
st... |
def main():
all_commands = []
all_eval_commands = []
for (max_steps, batch_size) in itertools.product((40000, 80000), (10, 20)):
if (max_steps == 40000):
steps = (list(range(2100, 40000, 2000)) + [40000])
elif (max_steps == 80000):
steps = (list(range(2100, 80000, 2... |
def main():
all_commands = []
all_eval_commands = []
for (output_from, att) in itertools.product(('false', 'true'), (0, 1, 2, 3)):
steps = (list(range(1100, 40000, 1000)) + [40000])
for step in steps:
logdir = ('logdirs/20190327/rerun,output_from=%(output_from)s,att=%(att)d' % ... |
def main():
all_commands = []
all_eval_commands = []
for (output_from, emb, min_freq) in itertools.product(('false', 'true'), ('glove-42B', 'bpemb-10k', 'bpemb-100k'), (3, 50)):
if ((min_freq == 50) and (emb != 'glove-42B')):
continue
steps = (list(range(1100, 40000, 1000)) + [... |
def main():
all_commands = []
all_eval_commands = []
for (output_from, emb, min_freq) in itertools.product(('false', 'true'), ('glove-42B', 'bpemb-10k', 'bpemb-100k'), (3, 50)):
if ((min_freq == 50) and (emb != 'glove-42B')):
continue
steps = (list(range(1100, 40000, 1000)) + [... |
def main():
all_commands = []
all_eval_commands = []
for (att, enc_size, dec_size) in itertools.product((0, 1), (256, 512), (256, 512)):
steps = (list(range(1100, 40000, 1000)) + [40000])
for step in steps:
logdir = ('logdirs/20190420/output_from=false,enc_size=%(enc_size)d,dec... |
def main():
all_commands = []
all_eval_commands = []
for (att, fixed) in itertools.product((0, 1, 2, 3), (['init'], ['data', 'model'])):
steps = (list(range(1100, 40000, 1000)) + [40000])
for step in steps:
infer_command = (((('python infer.py --config configs/spider-20190205/n... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--beam-size', type=int, default=1)
script_args = parser.parse_args()
for ((bs, lr, end_lr), att) in itertools.product(((50, 0.001, 0),), (0, 1, 2)):
steps = (list(range(1100, 40000, 1000)) + [40000])
args = '{{bs: {bs}... |
def main():
all_commands = []
all_eval_commands = []
for (lr, wd, decay, att) in itertools.product((0.001, 0.0001), (0, 0.01), ('cosine', 'linear'), (0, 1)):
steps = (list(range(1100, 20000, 500)) + [20000])
for step in steps:
infer_command = ((('python infer.py --config config... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--beam-size', type=int, default=1)
script_args = parser.parse_args()
for ((glove, upd_type, num_layers), att) in itertools.product(((False, 'full', 4), (True, 'no_subtypes', 4), (True, 'merge_types', 4), (True, 'full', 2), (True, 'ful... |
def main():
all_commands = []
all_eval_commands = []
for (st, nt, att) in itertools.product(('cov-xent', 'cov-examples'), (10, 20, 40, 80), (0,)):
steps = (list(range(1100, 40000, 1000)) + [40000])
for step in steps:
infer_command = 'python infer.py --config configs/spider-idio... |
def main():
for (st, nt, att) in itertools.product(('cov-xent', 'cov-examples'), (40, 80), (0,)):
steps = (list(range(1100, 40000, 1000)) + [40000])
args = "{{st: '{st}', nt: {nt}, att: {att}}}".format(st=st, nt=nt, att=att)
config = json.loads(_jsonnet.evaluate_file('configs/spider-idioms... |
def maybe_slice(iterable, start, end):
if ((start is not None) or (end is not None)):
iterable = itertools.islice(iterable, start, end)
return iterable
|
class Inferer():
def __init__(self, config):
self.config = config
if torch.cuda.is_available():
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')
torch.set_num_threads(1)
self.model_preproc = registry.instantiate(registr... |
def write_all(output, genexp):
for item in genexp:
output.write(item)
output.flush()
|
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--logdir', required=True)
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
parser.add_argument('--step', type=int)
parser.add_argument('--section', required=True)
parser.add_argument('--o... |
def find_idiom_checkpoints():
accuracy_per_run = collections.defaultdict(dict)
all_metrics = []
metric_types = set()
rows = []
for d in sorted(glob.glob('logdirs/20190201-hs-allmatches-anysplit-multimean/*')):
exp_name = os.path.basename(d)
exp_vars = re.match('filt-([^_]+)_st-([^_... |
def find_baseline_checkpoints():
accuracy_per_run = collections.defaultdict(dict)
all_metrics = []
metric_types = set()
rows = []
for d in sorted(glob.glob('logdirs/20181231-nl2code-hearthstone-fef2c5b//*')):
exp_name = os.path.basename(d)
exp_vars = re.match('att([^_]+)', exp_name... |
def count_nodes(tree):
queue = collections.deque([tree])
count = 0
while queue:
node = queue.pop()
count += 1
if isinstance(node, dict):
for (k, v) in node.items():
if (k == '_type'):
continue
if isinstance(v, (list, t... |
def analyze_idiom_usage(infer_history_path, normalized_gold_code):
inferred_all = [json.loads(line) for line in open(infer_history_path)]
exact_match_all = [((normalized_gold_code[i] == example['beams'][0]['inferred_code']) if example['beams'] else False) for (i, example) in enumerate(inferred_all)]
decod... |
def analyze_teacher_forced_pr(report, templates, accuracy_ks=(1, 2), precision_ks=(1, 2), recall_ks=(1, 2)):
template_match_counts = collections.defaultdict(int)
template_choice_ranks = {'all': collections.defaultdict(list), 'templates only': collections.defaultdict(list)}
template_valid_choice_ranks = {'... |
def analyze_anysplit_one(name, section):
report = [json.loads(line) for line in open('../logdirs/20190201-hs-allmatches-anysplit/{}/debug-{}-step2600.jsonl'.format(name, section))]
templates = json.load(open('../data/hearthstone-idioms-20190201/all-matches-trees-anysplit/{}/templates.json'.format(name)))
... |
def load_inferred(infer_history_path, normalized_gold_code):
inferred_all = [json.loads(line) for line in open(infer_history_path)]
exact_match_all = [((normalized_gold_code[i] == example['beams'][0]['inferred_code']) if example['beams'] else False) for (i, example) in enumerate(inferred_all)]
return (inf... |
def analyze(report, templates, accuracy_ks=(1, 2), precision_ks=(1, 2), recall_ks=(1, 2)):
template_match_counts = collections.defaultdict(int)
template_choice_ranks = {'all': collections.defaultdict(list), 'templates only': collections.defaultdict(list)}
template_valid_choice_ranks = {'all': collections.... |
def analyze_anysplit_one(name, section):
report = [json.loads(line) for line in open('../logdirs/20190201-hs-allmatches-anysplit/{}/debug-{}-step2600.jsonl'.format(name, section))]
templates = json.load(open('../data/hearthstone-idioms-20190201/all-matches-trees-anysplit/{}/templates.json'.format(name)))
... |
def analyze_anysplit(section):
for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), ('10', '20', '40', '80')):
name = 'filt-{}_st-{}_nt-{}'.format(filt, st, nt)
(acc_df, pr_df) = analyze_anysplit_one(name, section)
print(name)
print('Temp... |
def analyze_anysplit_multimean_one(name, section):
report = [json.loads(line) for line in open('../logdirs/20190201-hs-allmatches-anysplit-multimean/{}/debug-{}-step2600.jsonl'.format(name, section))]
templates = json.load(open('../data/hearthstone-idioms-20190201/all-matches-trees-anysplit/{}/templates.json'... |
def analyze_anysplit_multimean(section):
for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), ('10', '20', '40', '80')):
name = 'filt-{}_st-{}_nt-{}'.format(filt, st, nt)
(acc_df, pr_df) = analyze_anysplit_multimean_one(name, section)
print(name)... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
def display_item(item):
question_toks = left_preproc[item['i']]['question']
IPython.display.display(IPython.display.HTML('\n <ul>\n <li>Database: <tt>{db_id}</tt></li>\n <li>Question: {question_tok}</li>\n <li>Gold: <tt>{gold}</tt></li>\n <li>Left: <tt>{left}</tt></li>\n ... |
def compare(data, left, right):
both_exact = []
left_exact = []
right_exact = []
neither_exact = []
for (i, (data_item, left_item, right_item)) in enumerate(zip(data, left['per_item'], right['per_item'])):
result = {'i': i, 'db_id': data_item['db_id'], 'question': data_item['question'], 'g... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
def compare(data, left, right):
both_exact = []
left_exact = []
right_exact = []
neither_exact = []
for (i, (data_item, left_item, right_item)) in enumerate(zip(data, left['per_item'], right['per_item'])):
result = {'i': i, 'db_id': data_item['db_id'], 'question': data_item['question'], 'g... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
def compare(data, left, right):
both_exact = []
left_exact = []
right_exact = []
neither_exact = []
for (i, (data_item, left_item, right_item)) in enumerate(zip(data, left['per_item'], right['per_item'])):
result = {'i': i, 'db_id': data_item['db_id'], 'question': data_item['question'], 'g... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
def compare(data, left, right):
both_exact = []
left_exact = []
right_exact = []
neither_exact = []
for (i, (data_item, left_item, right_item)) in enumerate(zip(data, left['per_item'], right['per_item'])):
result = {'i': i, 'db_id': data_item['db_id'], 'question': data_item['question'], 'g... |
def find_columns(query, include_from=False):
result = set()
queue = collections.deque([query])
while queue:
node = queue.popleft()
type_info = grammar.ast_wrapper.singular_types[node['_type']]
for field in type_info.fields:
if ((not include_from) and (field.name == 'fro... |
def group_by_schema(data):
result = collections.defaultdict(list)
for example in data:
result[example.schema.db_id].append(example)
return result
|
def analyze(data):
grouped = collections.defaultdict(list)
grouped_column_usage = collections.defaultdict(list)
for example in data:
grouped[example.schema.db_id].append(example)
grouped_column_usage[example.schema.db_id].append(find_columns(grammar.parse(example.code, 'train')))
for (... |
def compute_accuracy(rows):
levels = ['easy', 'medium', 'hard', 'extra', 'all']
total = collections.defaultdict(int)
exact = collections.defaultdict(int)
for row in rows:
exact[row['hardness']] += row['exact']
exact['all'] += row['exact']
total[row['hardness']] += 1
tot... |
class Preprocessor():
def __init__(self, config):
self.config = config
self.model_preproc = registry.instantiate(registry.lookup('model', config['model']).Preproc, config['model'])
def preprocess(self):
self.model_preproc.clear_items()
for section in self.config['data']:
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
args = parser.parse_args()
if args.config_args:
config = json.loads(_jsonnet.evaluate_file(args.config, tla_codes={'args': args.config_args}))
else:
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--infer', nargs='*', default=())
parser.add_argument('--sql', nargs='*', default=())
parser.add_argument('--names', nargs='*', default=())
parser.add_argument('--out', required=True)
args = parser.parse_args()
assert (len(... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('inputs', nargs='+')
args = parser.parse_args()
for path in args.inputs:
for existing in glob.glob(os.path.join(path, 'events.out.tfevents*')):
os.unlink(existing)
writer = tf.summary.FileWriter(path)
... |
def check_close(a, b):
assert ((a - b).abs().max() < 1e-05)
|
def test_enc_equal(input0, inputb, sequential):
input1 = input0
inputc = inputb
inputb0 = [inputb[0]]
input0_history = [input0]
inputb_history = [inputb]
inputb0_history = [inputb0]
for m in sequential:
input0 = m.forward_unbatched(input0)
input1 = m.forward_unbatched(input... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
args = parser.parse_args()
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
if args.config_args:
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', required=True)
parser.add_argument('--config-args')
parser.add_argument('--section', required=True)
parser.add_argument('--inferred', required=True)
parser.add_argument('--output', required=True)
args = parser.p... |
def count_glove(data, embedder):
present = collections.Counter()
missing = collections.Counter()
counted_db_ids = set()
for item in tqdm.tqdm(data):
question_tokens = embedder.tokenize(item.orig['question'])
for token in question_tokens:
if (embedder.lookup(token) is None):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.