project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
dstallmann/transfer_learning_twinvae | util.py | Colours.red | red | Wrap text in red. | [
"Wrap",
"text",
"in",
"red."
] | def red(cls, s):
return cls._wrap_colour(s, cls.RED) | ['def', 'red(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.RED)'] | 964,748 |
dstallmann/transfer_learning_twinvae | util.py | Colours.underline | underline | Wrap text in underline. | [
"Wrap",
"text",
"in",
"underline."
] | def underline(cls, s):
return cls._wrap_colour(s, cls.UNDERLINE) | ['def', 'underline(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.UNDERLINE)'] | 964,749 |
kevin-atsou/transformer | utils.py | one_hot_encoding_with_label_smoothing | one_hot_encoding_with_label_smoothing | Converts a batch of 1D tensors of word indexes to a 3D tensor of one-hot encoding tensors with label smoothing. | [
"Converts",
"a",
"batch",
"of",
"1D",
"tensors",
"of",
"word",
"indexes",
"to",
"a",
"3D",
"tensor",
"of",
"one-hot",
"encoding",
"tensors",
"with",
"label",
"smoothing."
] | def one_hot_encoding_with_label_smoothing(input_tensor, num_classes, min_smoothing_factor, max_smoothing_factor):
batch_size = input_tensor.size(0)
seq_length = input_tensor.size(1)
one_hot = torch.zeros(batch_size, seq_length, num_classes, device=input_tensor.device)
one_hot.scatter_(2, input_tensor.un... | ['def', 'one_hot_encoding_with_label_smoothing(input_tensor,', 'num_classes,', 'min_smoothing_factor,', 'max_smoothing_factor):', 'batch_size', '=', 'input_tensor.size(0)', 'seq_length', '=', 'input_tensor.size(1)', 'one_hot', '=', 'torch.zeros(batch_size,', 'seq_length,', 'num_classes,', 'device=input_tensor.device)',... | 964,776 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | t2t_datagen.py | generate_data_for_problem | generate_data_for_problem | Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS. | [
"Generate",
"data",
"for",
"a",
"problem",
"in",
"_SUPPORTED_PROBLEM_GENERATORS."
] | def generate_data_for_problem(problem):
(training_gen, dev_gen, test_gen) = _SUPPORTED_PROBLEM_GENERATORS[problem]
num_train_shards = FLAGS.num_shards or 10
tf.logging.info('Generating training data for %s.', problem)
train_output_files = generator_utils.train_data_filenames(problem + generator_utils.UN... | ['def', 'generate_data_for_problem(problem):', '(training_gen,', 'dev_gen,', 'test_gen)', '=', '_SUPPORTED_PROBLEM_GENERATORS[problem]', 'num_train_shards', '=', 'FLAGS.num_shards', 'or', '10', "tf.logging.info('Generating", 'training', 'data', 'for', "%s.',", 'problem)', 'train_output_files', '=', 'generator_utils.tra... | 964,780 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | t2t_decoder.py | score_file | score_file | Score each line in a file and return the scores. | [
"Score",
"each",
"line",
"in",
"a",
"file",
"and",
"return",
"the",
"scores."
] | def score_file(filename):
hparams = create_hparams()
encoders = registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)
has_inputs = 'inputs' in encoders
if has_inputs:
inputs_ph = tf.placeholder(dtype=tf.int32)
batch_inputs = tf.reshape(inputs_ph, [1, -1, 1, 1])
targets_ph ... | ['def', 'score_file(filename):', 'hparams', '=', 'create_hparams()', 'encoders', '=', 'registry.problem(FLAGS.problem).feature_encoders(FLAGS.data_dir)', 'has_inputs', '=', "'inputs'", 'in', 'encoders', 'if', 'has_inputs:', 'inputs_ph', '=', 'tf.placeholder(dtype=tf.int32)', 'batch_inputs', '=', 'tf.reshape(inputs_ph,'... | 964,783 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | t2t_trainer.py | set_hparams_from_args | set_hparams_from_args | Set hparams overrides from unparsed args list. | [
"Set",
"hparams",
"overrides",
"from",
"unparsed",
"args",
"list."
] | def set_hparams_from_args(args):
if not args:
return
hp_prefix = '--hp_'
tf.logging.info('Found unparsed command-line arguments. Checking if any start with %s and interpreting those as hparams settings.', hp_prefix)
pairs = []
i = 0
while i < len(args):
arg = args[i]
if a... | ['def', 'set_hparams_from_args(args):', 'if', 'not', 'args:', 'return', 'hp_prefix', '=', "'--hp_'", "tf.logging.info('Found", 'unparsed', 'command-line', 'arguments.', 'Checking', 'if', 'any', 'start', 'with', '%s', 'and', 'interpreting', 'those', 'as', 'hparams', "settings.',", 'hp_prefix)', 'pairs', '=', '[]', 'i', ... | 964,784 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | t2t_trainer.py | create_run_config | create_run_config | Create a run config. | [
"Create",
"a",
"run",
"config."
] | def create_run_config(hp):
save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency)
save_ckpt_secs = FLAGS.save_checkpoints_secs or None
if save_ckpt_secs:
save_ckpt_steps = None
assert FLAGS.output_dir or FLAGS.checkpoint_path
tpu_config_extra_kwargs = {}
if getattr(... | ['def', 'create_run_config(hp):', 'save_ckpt_steps', '=', 'max(FLAGS.iterations_per_loop,', 'FLAGS.local_eval_frequency)', 'save_ckpt_secs', '=', 'FLAGS.save_checkpoints_secs', 'or', 'None', 'if', 'save_ckpt_secs:', 'save_ckpt_steps', '=', 'None', 'assert', 'FLAGS.output_dir', 'or', 'FLAGS.checkpoint_path', 'tpu_config... | 964,785 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | algorithmic.py | TinyAlgo.generate_data | generate_data | Ganerate data for this problem. | [
"Ganerate",
"data",
"for",
"this",
"problem."
] | def generate_data(self, data_dir, tmp_dir, task_id=-1):
del tmp_dir, task_id
identity_problem = AlgorithmicIdentityBinary40()
utils.generate_files(identity_problem.generator(self.num_symbols, 40, 100000), self.training_filepaths(data_dir, 1, shuffled=True), 100)
utils.generate_files(identity_problem.gen... | ['def', 'generate_data(self,', 'data_dir,', 'tmp_dir,', 'task_id=-1):', 'del', 'tmp_dir,', 'task_id', 'identity_problem', '=', 'AlgorithmicIdentityBinary40()', 'utils.generate_files(identity_problem.generator(self.num_symbols,', '40,', '100000),', 'self.training_filepaths(data_dir,', '1,', 'shuffled=True),', '100)', 'u... | 964,800 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | algorithmic.py | TinyAlgo.setup_for_test | setup_for_test | Setup directories and files required to run the problem. | [
"Setup",
"directories",
"and",
"files",
"required",
"to",
"run",
"the",
"problem."
] | def setup_for_test(cls):
tmp_dir = tf.test.get_temp_dir()
shutil.rmtree(tmp_dir)
os.mkdir(tmp_dir)
cls.data_dir = tmp_dir
cls().generate_data(TinyAlgo.data_dir, None) | ['def', 'setup_for_test(cls):', 'tmp_dir', '=', 'tf.test.get_temp_dir()', 'shutil.rmtree(tmp_dir)', 'os.mkdir(tmp_dir)', 'cls.data_dir', '=', 'tmp_dir', 'cls().generate_data(TinyAlgo.data_dir,', 'None)'] | 964,801 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain.py | random_square_mask | random_square_mask | Create a numpy array with specified shape and masked fraction. | [
"Create",
"a",
"numpy",
"array",
"with",
"specified",
"shape",
"and",
"masked",
"fraction."
] | def random_square_mask(shape, fraction):
mask = np.ones(shape)
patch_area = shape[0] * shape[1] * fraction
patch_dim = np.int(math.floor(math.sqrt(patch_area)))
if patch_area == 0 or patch_dim == 0:
return mask
x = np.random.randint(shape[0] - patch_dim)
y = np.random.randint(shape[1] - ... | ['def', 'random_square_mask(shape,', 'fraction):', 'mask', '=', 'np.ones(shape)', 'patch_area', '=', 'shape[0]', '*', 'shape[1]', '*', 'fraction', 'patch_dim', '=', 'np.int(math.floor(math.sqrt(patch_area)))', 'if', 'patch_area', '==', '0', 'or', 'patch_dim', '==', '0:', 'return', 'mask', 'x', '=', 'np.random.randint(s... | 964,816 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain.py | Img2imgAllenBrain.num_channels | num_channels | Number of color channels. | [
"Number",
"of",
"color",
"channels."
] | def num_channels(self):
return 3 | ['def', 'num_channels(self):', 'return', '3'] | 964,817 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain.py | Img2imgAllenBrain.input_dim | input_dim | The x and y dimension of the input image. | [
"The",
"x",
"and",
"y",
"dimension",
"of",
"the",
"input",
"image."
] | def input_dim(self):
return 64 | ['def', 'input_dim(self):', 'return', '64'] | 964,818 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain.py | Img2imgAllenBrain.output_dim | output_dim | The x and y dimension of the target image. | [
"The",
"x",
"and",
"y",
"dimension",
"of",
"the",
"target",
"image."
] | def output_dim(self):
return 64 | ['def', 'output_dim(self):', 'return', '64'] | 964,819 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain.py | Img2imgAllenBrain.inpaint_fraction | inpaint_fraction | The fraction of the input image to be in-painted. | [
"The",
"fraction",
"of",
"the",
"input",
"image",
"to",
"be",
"in-painted."
] | def inpaint_fraction(self):
return None | ['def', 'inpaint_fraction(self):', 'return', 'None'] | 964,820 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain_test.py | mock_raw_image | mock_raw_image | Generate random `x_dim` by `y_dim`, optionally to `output_path`. | [
"Generate",
"random",
"`x_dim`",
"by",
"`y_dim`,",
"optionally",
"to",
"`output_path`."
] | def mock_raw_image(x_dim=1024, y_dim=1024, num_channels=3, output_path=None, write_image=True):
rand_shape = (x_dim, y_dim, num_channels)
if num_channels != 3:
raise NotImplementedError('mock_raw_image for channels != 3 not yet implemented.')
img = np.random.random(rand_shape)
img = np.uint8(img... | ['def', 'mock_raw_image(x_dim=1024,', 'y_dim=1024,', 'num_channels=3,', 'output_path=None,', 'write_image=True):', 'rand_shape', '=', '(x_dim,', 'y_dim,', 'num_channels)', 'if', 'num_channels', '!=', '3:', 'raise', "NotImplementedError('mock_raw_image", 'for', 'channels', '!=', '3', 'not', 'yet', "implemented.')", 'img... | 964,821 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain_test.py | TestAllenBrain.test_generator_produces_examples | test_generator_produces_examples | Basic test that the generator produces examples with expected keys. | [
"Basic",
"test",
"that",
"the",
"generator",
"produces",
"examples",
"with",
"expected",
"keys."
] | def test_generator_produces_examples(self):
for is_training in [True, False]:
with TemporaryDirectory() as tmp_dir:
mock_raw_data(tmp_dir, raw_dim=256, num_images=100)
for example in allen_brain._generator(tmp_dir, is_training):
for key in ['image/encoded', 'image/for... | ['def', 'test_generator_produces_examples(self):', 'for', 'is_training', 'in', '[True,', 'False]:', 'with', 'TemporaryDirectory()', 'as', 'tmp_dir:', 'mock_raw_data(tmp_dir,', 'raw_dim=256,', 'num_images=100)', 'for', 'example', 'in', 'allen_brain._generator(tmp_dir,', 'is_training):', 'for', 'key', 'in', "['image/enco... | 964,823 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | allen_brain_test.py | TestMockRawData.test_runs | test_runs | Test that data mocking utility runs for cases expected to succeed. | [
"Test",
"that",
"data",
"mocking",
"utility",
"runs",
"for",
"cases",
"expected",
"to",
"succeed."
] | def test_runs(self):
with TemporaryDirectory() as tmp_dir:
mock_raw_data(tmp_dir, raw_dim=256, num_channels=3, num_images=40) | ['def', 'test_runs(self):', 'with', 'TemporaryDirectory()', 'as', 'tmp_dir:', 'mock_raw_data(tmp_dir,', 'raw_dim=256,', 'num_channels=3,', 'num_images=40)'] | 964,827 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | audio_encoder.py | AudioEncoder.encode | encode | Transform a string with a filename into a list of float32. | [
"Transform",
"a",
"string",
"with",
"a",
"filename",
"into",
"a",
"list",
"of",
"float32."
] | def encode(self, s):
if s.endswith('.mp3'):
out_filepath = s[:-4] + '.wav'
call(['sox', '--guard', s, '-r', '16k', '-b', '16', '-c', '1', out_filepath])
s = out_filepath
elif not s.endswith('.wav'):
out_filepath = s + '.wav'
if not os.path.exists(out_filepath):
... | ['def', 'encode(self,', 's):', 'if', "s.endswith('.mp3'):", 'out_filepath', '=', 's[:-4]', '+', "'.wav'", "call(['sox',", "'--guard',", 's,', "'-r',", "'16k',", "'-b',", "'16',", "'-c',", "'1',", 'out_filepath])', 's', '=', 'out_filepath', 'elif', 'not', "s.endswith('.wav'):", 'out_filepath', '=', 's', '+', "'.wav'", '... | 964,829 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | audio_encoder.py | AudioEncoder.decode | decode | Transform a sequence of float32 into a waveform. | [
"Transform",
"a",
"sequence",
"of",
"float32",
"into",
"a",
"waveform."
] | def decode(self, ids):
(_, tmp_file_path) = tempfile.mkstemp()
wavfile.write(tmp_file_path, self._sample_rate, np.asarray(ids))
return tmp_file_path | ['def', 'decode(self,', 'ids):', '(_,', 'tmp_file_path)', '=', 'tempfile.mkstemp()', 'wavfile.write(tmp_file_path,', 'self._sample_rate,', 'np.asarray(ids))', 'return', 'tmp_file_path'] | 964,830 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | babi_qa.py | BabiQa.get_labels_encoder | get_labels_encoder | Builds encoder for the given class labels. | [
"Builds",
"encoder",
"for",
"the",
"given",
"class",
"labels."
] | def get_labels_encoder(self, data_dir):
label_filepath = os.path.join(data_dir, self.vocab_filename)
return text_encoder.TokenTextEncoder(label_filepath) | ['def', 'get_labels_encoder(self,', 'data_dir):', 'label_filepath', '=', 'os.path.join(data_dir,', 'self.vocab_filename)', 'return', 'text_encoder.TokenTextEncoder(label_filepath)'] | 964,834 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | babi_qa.py | BabiQa.generate_encoded_samples | generate_encoded_samples | A generator that generates samples that are encoded. | [
"A",
"generator",
"that",
"generates",
"samples",
"that",
"are",
"encoded."
] | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
generator = self.generate_samples(data_dir, tmp_dir, dataset_split)
encoder = self.get_or_create_vocab(data_dir, tmp_dir)
label_encoder = self.get_labels_encoder(data_dir)
for sample in generator:
inputs = encoder.encode(sampl... | ['def', 'generate_encoded_samples(self,', 'data_dir,', 'tmp_dir,', 'dataset_split):', 'generator', '=', 'self.generate_samples(data_dir,', 'tmp_dir,', 'dataset_split)', 'encoder', '=', 'self.get_or_create_vocab(data_dir,', 'tmp_dir)', 'label_encoder', '=', 'self.get_labels_encoder(data_dir)', 'for', 'sample', 'in', 'ge... | 964,835 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | generator_utils.py | maybe_download_from_drive | maybe_download_from_drive | Download filename from Google drive unless it's already in directory. | [
"Download",
"filename",
"from",
"Google",
"drive",
"unless",
"it's",
"already",
"in",
"directory."
] | def maybe_download_from_drive(directory, filename, url):
if not tf.gfile.Exists(directory):
tf.logging.info('Creating directory %s' % directory)
tf.gfile.MakeDirs(directory)
filepath = os.path.join(directory, filename)
confirm_token = None
if tf.gfile.Exists(filepath):
tf.logging... | ['def', 'maybe_download_from_drive(directory,', 'filename,', 'url):', 'if', 'not', 'tf.gfile.Exists(directory):', "tf.logging.info('Creating", 'directory', "%s'", '%', 'directory)', 'tf.gfile.MakeDirs(directory)', 'filepath', '=', 'os.path.join(directory,', 'filename)', 'confirm_token', '=', 'None', 'if', 'tf.gfile.Exi... | 964,861 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | generator_utils.py | generate_lines_for_vocab | generate_lines_for_vocab | Generate lines for vocabulary generation. | [
"Generate",
"lines",
"for",
"vocabulary",
"generation."
] | def generate_lines_for_vocab(tmp_dir, sources, file_byte_budget=1000000.0):
tf.logging.info('Generating vocab from: %s', str(sources))
for source in sources:
url = source[0]
filename = os.path.basename(url)
compressed_file = maybe_download(tmp_dir, filename, url)
for lang_file in... | ['def', 'generate_lines_for_vocab(tmp_dir,', 'sources,', 'file_byte_budget=1000000.0):', "tf.logging.info('Generating", 'vocab', 'from:', "%s',", 'str(sources))', 'for', 'source', 'in', 'sources:', 'url', '=', 'source[0]', 'filename', '=', 'os.path.basename(url)', 'compressed_file', '=', 'maybe_download(tmp_dir,', 'fil... | 964,865 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | generator_utils.py | make_tmp_dir | make_tmp_dir | Make a temporary directory. | [
"Make",
"a",
"temporary",
"directory."
] | def make_tmp_dir(suffix='', prefix='tmp', dir=None):
if dir is None:
return tempfile.mkdtemp(suffix, prefix, dir)
else:
while True:
rand_term = random.randint(1, 9999)
tmp_dir = os.path.join(dir, '%s%d%s' % (prefix, rand_term, suffix))
if tf.gfile.Exists(tmp_d... | ['def', "make_tmp_dir(suffix='',", "prefix='tmp',", 'dir=None):', 'if', 'dir', 'is', 'None:', 'return', 'tempfile.mkdtemp(suffix,', 'prefix,', 'dir)', 'else:', 'while', 'True:', 'rand_term', '=', 'random.randint(1,', '9999)', 'tmp_dir', '=', 'os.path.join(dir,', "'%s%d%s'", '%', '(prefix,', 'rand_term,', 'suffix))', 'i... | 964,868 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | generator_utils.py | tfrecord_iterator_for_problem | tfrecord_iterator_for_problem | Iterate over the records on disk for the Problem. | [
"Iterate",
"over",
"the",
"records",
"on",
"disk",
"for",
"the",
"Problem."
] | def tfrecord_iterator_for_problem(problem, data_dir, dataset_split=tf.estimator.ModeKeys.TRAIN):
filenames = tf.gfile.Glob(problem.filepattern(data_dir, mode=dataset_split))
example_spec = problem.example_reading_spec()[0]
return tfrecord_iterator(filenames, example_spec=example_spec) | ['def', 'tfrecord_iterator_for_problem(problem,', 'data_dir,', 'dataset_split=tf.estimator.ModeKeys.TRAIN):', 'filenames', '=', 'tf.gfile.Glob(problem.filepattern(data_dir,', 'mode=dataset_split))', 'example_spec', '=', 'problem.example_reading_spec()[0]', 'return', 'tfrecord_iterator(filenames,', 'example_spec=example... | 964,869 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems.py | standard_atari_env_spec | standard_atari_env_spec | Parameters of environment specification. | [
"Parameters",
"of",
"environment",
"specification."
] | def standard_atari_env_spec(env):
standard_wrappers = [[tf_atari_wrappers.RewardClippingWrapper, {}], [tf_atari_wrappers.StackWrapper, {'history': 4}]]
env_lambda = None
if isinstance(env, str):
env_lambda = lambda : gym.make(env)
if callable(env):
env_lambda = env
assert env_lambda ... | ['def', 'standard_atari_env_spec(env):', 'standard_wrappers', '=', '[[tf_atari_wrappers.RewardClippingWrapper,', '{}],', '[tf_atari_wrappers.StackWrapper,', "{'history':", '4}]]', 'env_lambda', '=', 'None', 'if', 'isinstance(env,', 'str):', 'env_lambda', '=', 'lambda', ':', 'gym.make(env)', 'if', 'callable(env):', 'env... | 964,874 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems.py | GymDiscreteProblem.is_generate_per_split | is_generate_per_split | Whether we have a train/test split or just hold out data. | [
"Whether",
"we",
"have",
"a",
"train/test",
"split",
"or",
"just",
"hold",
"out",
"data."
] | def is_generate_per_split(self):
return False | ['def', 'is_generate_per_split(self):', 'return', 'False'] | 964,877 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems.py | GymDiscreteProblem.env_name | env_name | This is the name of the Gym environment for this problem. | [
"This",
"is",
"the",
"name",
"of",
"the",
"Gym",
"environment",
"for",
"this",
"problem."
] | def env_name(self):
raise NotImplementedError() | ['def', 'env_name(self):', 'raise', 'NotImplementedError()'] | 964,878 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems.py | GymDiscreteProblem.collect_statistics_and_generate_debug_image | collect_statistics_and_generate_debug_image | This generates extra statistics and debug images. | [
"This",
"generates",
"extra",
"statistics",
"and",
"debug",
"images."
] | def collect_statistics_and_generate_debug_image(self, index, observation, reward, done, action):
return None | ['def', 'collect_statistics_and_generate_debug_image(self,', 'index,', 'observation,', 'reward,', 'done,', 'action):', 'return', 'None'] | 964,879 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems.py | GymDiscreteProblemAutoencoded.autoencoder_factor | autoencoder_factor | By how much to divide sizes when using autoencoders. | [
"By",
"how",
"much",
"to",
"divide",
"sizes",
"when",
"using",
"autoencoders."
] | def autoencoder_factor(self):
hparams = autoencoders.autoencoder_discrete_pong()
return 2 ** hparams.num_hidden_layers | ['def', 'autoencoder_factor(self):', 'hparams', '=', 'autoencoders.autoencoder_discrete_pong()', 'return', '2', '**', 'hparams.num_hidden_layers'] | 964,881 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | gym_problems_specs.py | create_problems_for_game | create_problems_for_game | Create and register problems for game_name. | [
"Create",
"and",
"register",
"problems",
"for",
"game_name."
] | def create_problems_for_game(game_name, clipped_reward=True, game_mode='Deterministic-v4'):
if not clipped_reward:
raise ValueError('Creating problems without clipped reward is not yet supported.')
if game_name not in ATARI_GAMES:
raise ValueError('Game %s not in ATARI_GAMES' % game_name)
if... | ['def', 'create_problems_for_game(game_name,', 'clipped_reward=True,', "game_mode='Deterministic-v4'):", 'if', 'not', 'clipped_reward:', 'raise', "ValueError('Creating", 'problems', 'without', 'clipped', 'reward', 'is', 'not', 'yet', "supported.')", 'if', 'game_name', 'not', 'in', 'ATARI_GAMES:', 'raise', "ValueError('... | 964,885 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | image_lsun.py | ImageLsunBedrooms.generate_data | generate_data | Generates LSUN bedrooms dataset and writes it in data_dir. | [
"Generates",
"LSUN",
"bedrooms",
"dataset",
"and",
"writes",
"it",
"in",
"data_dir."
] | def generate_data(self, data_dir, tmp_dir, task_id=-1):
generator_utils.generate_dataset_and_shuffle(self.read_and_convert_to_png(tmp_dir, 'train'), self.training_filepaths(data_dir, 100, shuffled=False), self.read_and_convert_to_png(tmp_dir, 'val'), self.dev_filepaths(data_dir, 1, shuffled=False)) | ['def', 'generate_data(self,', 'data_dir,', 'tmp_dir,', 'task_id=-1):', 'generator_utils.generate_dataset_and_shuffle(self.read_and_convert_to_png(tmp_dir,', "'train'),", 'self.training_filepaths(data_dir,', '100,', 'shuffled=False),', 'self.read_and_convert_to_png(tmp_dir,', "'val'),", 'self.dev_filepaths(data_dir,', ... | 964,894 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | image_utils.py | make_multiscale | make_multiscale | Returns list of scaled images, one for each resolution. | [
"Returns",
"list",
"of",
"scaled",
"images,",
"one",
"for",
"each",
"resolution."
] | def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod.BICUBIC, num_channels=3):
scaled_images = []
for height in resolutions:
scaled_image = tf.image.resize_images(image, size=[height, height], method=resize_method)
scaled_image = tf.to_int64(scaled_image)
scaled_im... | ['def', 'make_multiscale(image,', 'resolutions,', 'resize_method=tf.image.ResizeMethod.BICUBIC,', 'num_channels=3):', 'scaled_images', '=', '[]', 'for', 'height', 'in', 'resolutions:', 'scaled_image', '=', 'tf.image.resize_images(image,', 'size=[height,', 'height],', 'method=resize_method)', 'scaled_image', '=', 'tf.to... | 964,899 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | image_utils.py | encode_images_as_png | encode_images_as_png | Yield images encoded as pngs. | [
"Yield",
"images",
"encoded",
"as",
"pngs."
] | def encode_images_as_png(images):
if tf.contrib.eager.in_eager_mode():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(hei... | ['def', 'encode_images_as_png(images):', 'if', 'tf.contrib.eager.in_eager_mode():', 'for', 'image', 'in', 'images:', 'yield', 'tf.image.encode_png(image).numpy()', 'else:', '(height,', 'width,', 'channels)', '=', 'images[0].shape', 'with', 'tf.Graph().as_default():', 'image_t', '=', 'tf.placeholder(dtype=tf.uint8,', 's... | 964,901 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | lambada.py | get_dataset_split | get_dataset_split | Gives the file paths with regards to the given split. | [
"Gives",
"the",
"file",
"paths",
"with",
"regards",
"to",
"the",
"given",
"split."
] | def get_dataset_split(tmp_dir, split, use_control_set):
if not use_control_set:
dataset_split = {problem.DatasetSplit.TRAIN: [f for f in tf.gfile.Glob(os.path.join(tmp_dir, 'train-novels/*/*.txt'))], problem.DatasetSplit.EVAL: [os.path.join(tmp_dir, 'lambada_development_plain_text.txt')], problem.DatasetSpl... | ['def', 'get_dataset_split(tmp_dir,', 'split,', 'use_control_set):', 'if', 'not', 'use_control_set:', 'dataset_split', '=', '{problem.DatasetSplit.TRAIN:', '[f', 'for', 'f', 'in', 'tf.gfile.Glob(os.path.join(tmp_dir,', "'train-novels/*/*.txt'))],", 'problem.DatasetSplit.EVAL:', '[os.path.join(tmp_dir,', "'lambada_devel... | 964,908 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | lambada.py | LambadaLm.use_control_set | use_control_set | If evaluate on control set. | [
"If",
"evaluate",
"on",
"control",
"set."
] | def use_control_set(self):
return False | ['def', 'use_control_set(self):', 'return', 'False'] | 964,911 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | lambada.py | LambadaLmControl.control_set | control_set | If test on control set. | [
"If",
"test",
"on",
"control",
"set."
] | def control_set(self):
return False | ['def', 'control_set(self):', 'return', 'False'] | 964,912 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | librispeech.py | Librispeech.use_train_shards_for_dev | use_train_shards_for_dev | If true, we only generate training data and hold out shards for dev. | [
"If",
"true,",
"we",
"only",
"generate",
"training",
"data",
"and",
"hold",
"out",
"shards",
"for",
"dev."
] | def use_train_shards_for_dev(self):
return False | ['def', 'use_train_shards_for_dev(self):', 'return', 'False'] | 964,921 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | cpu_count | cpu_count | Return the number of available cores. | [
"Return",
"the",
"number",
"of",
"available",
"cores."
] | def cpu_count():
num_available_cores = multiprocessing.cpu_count()
return num_available_cores | ['def', 'cpu_count():', 'num_available_cores', '=', 'multiprocessing.cpu_count()', 'return', 'num_available_cores'] | 964,938 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | pad_batch | pad_batch | Pad batch dim of features to nearest multiple of batch_multiple. | [
"Pad",
"batch",
"dim",
"of",
"features",
"to",
"nearest",
"multiple",
"of",
"batch_multiple."
] | def pad_batch(features, batch_multiple):
feature = list(features.items())[0][1]
batch_size = tf.shape(feature)[0]
mod = batch_size % batch_multiple
has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32)
batch_padding = batch_multiple * has_mod - mod
padded_features = {}
for (k, feature) in featu... | ['def', 'pad_batch(features,', 'batch_multiple):', 'feature', '=', 'list(features.items())[0][1]', 'batch_size', '=', 'tf.shape(feature)[0]', 'mod', '=', 'batch_size', '%', 'batch_multiple', 'has_mod', '=', 'tf.cast(tf.cast(mod,', 'tf.bool),', 'tf.int32)', 'batch_padding', '=', 'batch_multiple', '*', 'has_mod', '-', 'm... | 964,940 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | Problem.num_generate_tasks | num_generate_tasks | Needed if multiprocess_generate is True. | [
"Needed",
"if",
"multiprocess_generate",
"is",
"True."
] | def num_generate_tasks(self):
raise NotImplementedError() | ['def', 'num_generate_tasks(self):', 'raise', 'NotImplementedError()'] | 964,942 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | Problem.tpu_batch_size_per_shard | tpu_batch_size_per_shard | Batch size in examples per TPU core. | [
"Batch",
"size",
"in",
"examples",
"per",
"TPU",
"core."
] | def tpu_batch_size_per_shard(self, model_hparams):
if self.batch_size_means_tokens and (not model_hparams.use_fixed_batch_size):
return model_hparams.batch_size // self.max_length(model_hparams)
else:
return model_hparams.batch_size | ['def', 'tpu_batch_size_per_shard(self,', 'model_hparams):', 'if', 'self.batch_size_means_tokens', 'and', '(not', 'model_hparams.use_fixed_batch_size):', 'return', 'model_hparams.batch_size', '//', 'self.max_length(model_hparams)', 'else:', 'return', 'model_hparams.batch_size'] | 964,945 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | Problem.maybe_reverse_features | maybe_reverse_features | Reverse features between inputs and targets if the problem is '_rev'. | [
"Reverse",
"features",
"between",
"inputs",
"and",
"targets",
"if",
"the",
"problem",
"is",
"'_rev'."
] | def maybe_reverse_features(self, feature_map):
if not self._was_reversed:
return
inputs = feature_map.pop('inputs', None)
targets = feature_map.pop('targets', None)
inputs_seg = feature_map.pop('inputs_segmentation', None)
targets_seg = feature_map.pop('targets_segmentation', None)
input... | ['def', 'maybe_reverse_features(self,', 'feature_map):', 'if', 'not', 'self._was_reversed:', 'return', 'inputs', '=', "feature_map.pop('inputs',", 'None)', 'targets', '=', "feature_map.pop('targets',", 'None)', 'inputs_seg', '=', "feature_map.pop('inputs_segmentation',", 'None)', 'targets_seg', '=', "feature_map.pop('t... | 964,950 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | Problem.input_fn | input_fn | Builds input pipeline for problem. | [
"Builds",
"input",
"pipeline",
"for",
"problem."
] | def input_fn(self, mode, hparams, data_dir=None, params=None, config=None, force_repeat=False, dataset_kwargs=None):
(partition_id, num_partitions) = self._dataset_partition(mode, config)
is_training = mode == tf.estimator.ModeKeys.TRAIN
if config and config.use_tpu:
num_threads = 64
else:
... | ['def', 'input_fn(self,', 'mode,', 'hparams,', 'data_dir=None,', 'params=None,', 'config=None,', 'force_repeat=False,', 'dataset_kwargs=None):', '(partition_id,', 'num_partitions)', '=', 'self._dataset_partition(mode,', 'config)', 'is_training', '=', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN', 'if', 'config', 'and', '... | 964,956 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem.py | Problem.serving_input_fn | serving_input_fn | Input fn for serving export, starting from serialized example. | [
"Input",
"fn",
"for",
"serving",
"export,",
"starting",
"from",
"serialized",
"example."
] | def serving_input_fn(self, hparams):
mode = tf.estimator.ModeKeys.PREDICT
serialized_example = tf.placeholder(dtype=tf.string, shape=[None], name='serialized_example')
dataset = tf.data.Dataset.from_tensor_slices(serialized_example)
dataset = dataset.map(self.decode_example)
dataset = dataset.map(la... | ['def', 'serving_input_fn(self,', 'hparams):', 'mode', '=', 'tf.estimator.ModeKeys.PREDICT', 'serialized_example', '=', 'tf.placeholder(dtype=tf.string,', 'shape=[None],', "name='serialized_example')", 'dataset', '=', 'tf.data.Dataset.from_tensor_slices(serialized_example)', 'dataset', '=', 'dataset.map(self.decode_exa... | 964,958 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | problem_test.py | assert_tensors_equal | assert_tensors_equal | Compute tensors `n` times and ensure that they are equal. | [
"Compute",
"tensors",
"`n`",
"times",
"and",
"ensure",
"that",
"they",
"are",
"equal."
] | def assert_tensors_equal(sess, t1, t2, n):
for _ in range(n):
(v1, v2) = sess.run([t1, t2])
if v1.shape != v2.shape:
return False
if not np.all(v1 == v2):
return False
return True | ['def', 'assert_tensors_equal(sess,', 't1,', 't2,', 'n):', 'for', '_', 'in', 'range(n):', '(v1,', 'v2)', '=', 'sess.run([t1,', 't2])', 'if', 'v1.shape', '!=', 'v2.shape:', 'return', 'False', 'if', 'not', 'np.all(v1', '==', 'v2):', 'return', 'False', 'return', 'True'] | 964,960 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | program_search.py | ProgramSearchAlgolisp.maybe_download_dataset | maybe_download_dataset | Downloads the appropriate dataset file and returns its path. | [
"Downloads",
"the",
"appropriate",
"dataset",
"file",
"and",
"returns",
"its",
"path."
] | def maybe_download_dataset(self, tmp_dir, dataset_split):
url = self.DATA_URLS.get(dataset_split, None)
if url is None:
tf.logging.fatal('Unknown dataset_split passed: {}'.format(dataset_split))
return generator_utils.maybe_download(tmp_dir, self._extract_filename_from_url(url), url) | ['def', 'maybe_download_dataset(self,', 'tmp_dir,', 'dataset_split):', 'url', '=', 'self.DATA_URLS.get(dataset_split,', 'None)', 'if', 'url', 'is', 'None:', "tf.logging.fatal('Unknown", 'dataset_split', 'passed:', "{}'.format(dataset_split))", 'return', 'generator_utils.maybe_download(tmp_dir,', 'self._extract_filename... | 964,961 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | speech_recognition.py | add_delta_deltas | add_delta_deltas | Compute time first and second-order derivative channels. | [
"Compute",
"time",
"first",
"and",
"second-order",
"derivative",
"channels."
] | def add_delta_deltas(filterbanks, name=None):
delta_filter = np.array([2, 1, 0, -1, -2])
delta_delta_filter = scipy.signal.convolve(delta_filter, delta_filter, 'full')
delta_filter_stack = np.array([[0] * 4 + [1] + [0] * 4, [0] * 2 + list(delta_filter) + [0] * 2, list(delta_delta_filter)], dtype=np.float32)... | ['def', 'add_delta_deltas(filterbanks,', 'name=None):', 'delta_filter', '=', 'np.array([2,', '1,', '0,', '-1,', '-2])', 'delta_delta_filter', '=', 'scipy.signal.convolve(delta_filter,', 'delta_filter,', "'full')", 'delta_filter_stack', '=', 'np.array([[0]', '*', '4', '+', '[1]', '+', '[0]', '*', '4,', '[0]', '*', '2', ... | 964,962 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | speech_recognition.py | SpeechRecognitionModality.bottom | bottom | Use batchnorm instead of CMVN and shorten the stft with strided convs. | [
"Use",
"batchnorm",
"instead",
"of",
"CMVN",
"and",
"shorten",
"the",
"stft",
"with",
"strided",
"convs."
] | def bottom(self, x):
inputs = x
p = self._model_hparams
num_mel_bins = p.audio_num_mel_bins
num_channels = 3 if p.audio_add_delta_deltas else 1
with tf.variable_scope(self.name):
if p.audio_preproc_in_bottom:
with tf.variable_scope('fbanks'):
waveforms = tf.squeez... | ['def', 'bottom(self,', 'x):', 'inputs', '=', 'x', 'p', '=', 'self._model_hparams', 'num_mel_bins', '=', 'p.audio_num_mel_bins', 'num_channels', '=', '3', 'if', 'p.audio_add_delta_deltas', 'else', '1', 'with', 'tf.variable_scope(self.name):', 'if', 'p.audio_preproc_in_bottom:', 'with', "tf.variable_scope('fbanks'):", '... | 964,964 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | style_transfer.py | StyleTransferProblemShakespeare.vocab_data_files | vocab_data_files | Files to be passed to get_or_generate_vocab. | [
"Files",
"to",
"be",
"passed",
"to",
"get_or_generate_vocab."
] | def vocab_data_files(self):
return self.dataset_url(problem.DatasetSplit.TRAIN) | ['def', 'vocab_data_files(self):', 'return', 'self.dataset_url(problem.DatasetSplit.TRAIN)'] | 964,965 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | subject_verb_agreement.py | load_examples | load_examples | Loads exampls from the tsv file. | [
"Loads",
"exampls",
"from",
"the",
"tsv",
"file."
] | def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01):
infile = generator_utils.maybe_download(tmp_dir, _TAR, _URL)
tf.logging.info('Loading examples')
all_examples = []
for (i, d) in enumerate(csv.DictReader(gzip.open(infile), delimiter='\t')):
if i % 100000 == 0:
tf.logging.in... | ['def', 'load_examples(tmp_dir,', 'prop_train=0.09,', 'prop_val=0.01):', 'infile', '=', 'generator_utils.maybe_download(tmp_dir,', '_TAR,', '_URL)', "tf.logging.info('Loading", "examples')", 'all_examples', '=', '[]', 'for', '(i,', 'd)', 'in', 'enumerate(csv.DictReader(gzip.open(infile),', "delimiter='\\t')):", 'if', '... | 964,967 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_encoder.py | ImageEncoder.encode | encode | Transform a string with a filename into a list of RGB integers. | [
"Transform",
"a",
"string",
"with",
"a",
"filename",
"into",
"a",
"list",
"of",
"RGB",
"integers."
] | def encode(self, s):
try:
import matplotlib.image as im
except ImportError as e:
tf.logging.warning('Reading an image requires matplotlib to be installed: %s', e)
raise NotImplementedError('Image reading not implemented.')
return im.imread(s) | ['def', 'encode(self,', 's):', 'try:', 'import', 'matplotlib.image', 'as', 'im', 'except', 'ImportError', 'as', 'e:', "tf.logging.warning('Reading", 'an', 'image', 'requires', 'matplotlib', 'to', 'be', 'installed:', "%s',", 'e)', 'raise', "NotImplementedError('Image", 'reading', 'not', "implemented.')", 'return', 'im.i... | 964,986 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | Text2SelfProblem.generate_samples | generate_samples | Generate samples of text. | [
"Generate",
"samples",
"of",
"text."
] | def generate_samples(self, data_dir, tmp_dir, dataset_split):
raise NotImplementedError() | ['def', 'generate_samples(self,', 'data_dir,', 'tmp_dir,', 'dataset_split):', 'raise', 'NotImplementedError()'] | 965,014 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | Text2ClassProblem.class_labels | class_labels | String representation of the classes. | [
"String",
"representation",
"of",
"the",
"classes."
] | def class_labels(self, data_dir):
del data_dir
return ['ID_%d' % i for i in range(self.num_classes)] | ['def', 'class_labels(self,', 'data_dir):', 'del', 'data_dir', 'return', "['ID_%d'", '%', 'i', 'for', 'i', 'in', 'range(self.num_classes)]'] | 965,017 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | ChoppedTextProblem.sequence_length | sequence_length | Length of each example (in tokens). | [
"Length",
"of",
"each",
"example",
"(in",
"tokens)."
] | def sequence_length(self):
raise NotImplementedError() | ['def', 'sequence_length(self):', 'raise', 'NotImplementedError()'] | 965,020 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | ChoppedTextProblem.text_filepaths_for_task | text_filepaths_for_task | List of input filepaths for a particular training or dev shard. | [
"List",
"of",
"input",
"filepaths",
"for",
"a",
"particular",
"training",
"or",
"dev",
"shard."
] | def text_filepaths_for_task(self, tmp_dir, task_id):
assert task_id >= 0
assert task_id < self.num_train_shards + self.num_dev_shards
if task_id < self.num_train_shards:
return [f for (i, f) in enumerate(self.train_text_filepaths(tmp_dir)) if i % self.num_train_shards == task_id]
else:
r... | ['def', 'text_filepaths_for_task(self,', 'tmp_dir,', 'task_id):', 'assert', 'task_id', '>=', '0', 'assert', 'task_id', '<', 'self.num_train_shards', '+', 'self.num_dev_shards', 'if', 'task_id', '<', 'self.num_train_shards:', 'return', '[f', 'for', '(i,', 'f)', 'in', 'enumerate(self.train_text_filepaths(tmp_dir))', 'if'... | 965,021 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | text_problems.py | ChoppedTextProblem.max_chars_for_vocab | max_chars_for_vocab | Number of characters of training data to use for generating vocab. | [
"Number",
"of",
"characters",
"of",
"training",
"data",
"to",
"use",
"for",
"generating",
"vocab."
] | def max_chars_for_vocab(self):
return 10 ** 7 | ['def', 'max_chars_for_vocab(self):', 'return', '10', '**', '7'] | 965,026 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesProblem.dataset_splits | dataset_splits | Splits of data to produce and number the output shards for each. | [
"Splits",
"of",
"data",
"to",
"produce",
"and",
"number",
"the",
"output",
"shards",
"for",
"each."
] | def dataset_splits(self):
return [{'split': problem.DatasetSplit.TRAIN, 'shards': self.num_train_shards}, {'split': problem.DatasetSplit.EVAL, 'shards': self.num_eval_shards}, {'split': problem.DatasetSplit.TEST, 'shards': self.num_test_shards}] | ['def', 'dataset_splits(self):', 'return', "[{'split':", 'problem.DatasetSplit.TRAIN,', "'shards':", 'self.num_train_shards},', "{'split':", 'problem.DatasetSplit.EVAL,', "'shards':", 'self.num_eval_shards},', "{'split':", 'problem.DatasetSplit.TEST,', "'shards':", 'self.num_test_shards}]'] | 965,030 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesProblem.num_train_shards | num_train_shards | Number of training shards. | [
"Number",
"of",
"training",
"shards."
] | def num_train_shards(self):
return 9 | ['def', 'num_train_shards(self):', 'return', '9'] | 965,031 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesProblem.num_target_timestamps | num_target_timestamps | Number of timestamps to include in the target. | [
"Number",
"of",
"timestamps",
"to",
"include",
"in",
"the",
"target."
] | def num_target_timestamps(self):
raise NotImplementedError() | ['def', 'num_target_timestamps(self):', 'raise', 'NotImplementedError()'] | 965,035 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesProblem.normalizing_constant | normalizing_constant | Constant by which all data will be multiplied to be more normalized. | [
"Constant",
"by",
"which",
"all",
"data",
"will",
"be",
"multiplied",
"to",
"be",
"more",
"normalized."
] | def normalizing_constant(self):
return 1.0 | ['def', 'normalizing_constant(self):', 'return', '1.0'] | 965,037 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesSyntheticDataSeries10Samples100k.timeseries_params | timeseries_params | Parameters for each timeseries. | [
"Parameters",
"for",
"each",
"timeseries."
] | def timeseries_params(self):
timeseries_params = [{'m': 0.006, 'b': 300.0, 'A': 50.0, 'freqcoeff': 1500.0, 'rndA': 15.0, 'fn': np.sin}, {'m': 0.0, 'b': 500.0, 'A': 35.0, 'freqcoeff': 3500.0, 'rndA': 25.0, 'fn': np.cos}, {'m': -0.003, 'b': 800.0, 'A': 65.0, 'freqcoeff': 2500.0, 'rndA': 5.0, 'fn': np.sin}, {'m': 0.00... | ['def', 'timeseries_params(self):', 'timeseries_params', '=', "[{'m':", '0.006,', "'b':", '300.0,', "'A':", '50.0,', "'freqcoeff':", '1500.0,', "'rndA':", '15.0,', "'fn':", 'np.sin},', "{'m':", '0.0,', "'b':", '500.0,', "'A':", '35.0,', "'freqcoeff':", '3500.0,', "'rndA':", '25.0,', "'fn':", 'np.cos},', "{'m':", '-0.00... | 965,047 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | translate.py | compute_bleu_summaries | compute_bleu_summaries | Compute BLEU core summaries using the decoder output. | [
"Compute",
"BLEU",
"core",
"summaries",
"using",
"the",
"decoder",
"output."
] | def compute_bleu_summaries(hook_args):
decode_hparams = hook_args.decode_hparams
if decode_hparams.decode_reference is None or decode_hparams.decode_to_file is None:
return None
values = []
bleu = 100 * bleu_hook.bleu_wrapper(decode_hparams.decode_reference, decode_hparams.decode_to_file)
va... | ['def', 'compute_bleu_summaries(hook_args):', 'decode_hparams', '=', 'hook_args.decode_hparams', 'if', 'decode_hparams.decode_reference', 'is', 'None', 'or', 'decode_hparams.decode_to_file', 'is', 'None:', 'return', 'None', 'values', '=', '[]', 'bleu', '=', '100', '*', 'bleu_hook.bleu_wrapper(decode_hparams.decode_refe... | 965,053 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | translate.py | TranslateProblem.source_data_files | source_data_files | Files to be passed to compile_data. | [
"Files",
"to",
"be",
"passed",
"to",
"compile_data."
] | def source_data_files(self, dataset_split):
raise NotImplementedError() | ['def', 'source_data_files(self,', 'dataset_split):', 'raise', 'NotImplementedError()'] | 965,055 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | twentybn.py | twentybn_generator | twentybn_generator | Video generator for twenty-bn dataset. | [
"Video",
"generator",
"for",
"twenty-bn",
"dataset."
] | def twentybn_generator(tmp_dir, training):
data_suffix = 'train' if training else 'validation'
def process_labels():
all_labels = {}
with tf.gfile.Open(tmp_dir + _FILE_LABEL_PATTERN + 'labels.csv') as f:
for (i, label) in enumerate(f):
all_labels[label] = i + 1
... | ['def', 'twentybn_generator(tmp_dir,', 'training):', 'data_suffix', '=', "'train'", 'if', 'training', 'else', "'validation'", 'def', 'process_labels():', 'all_labels', '=', '{}', 'with', 'tf.gfile.Open(tmp_dir', '+', '_FILE_LABEL_PATTERN', '+', "'labels.csv')", 'as', 'f:', 'for', '(i,', 'label)', 'in', 'enumerate(f):',... | 965,059 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_generated.py | VideoStochasticShapes10k.get_triangle | get_triangle | Draws a triangle with center (x, y), color c, size s and z-order of z. | [
"Draws",
"a",
"triangle",
"with",
"center",
"(x,",
"y),",
"color",
"c,",
"size",
"s",
"and",
"z-order",
"of",
"z."
] | def get_triangle(x, y, z, c, s):
points = np.array([[0, 0], [s, s * math.sqrt(3.0)], [s * 2.0, 0]])
tri = plt.Polygon(points + [x - s, y - s], fc=c, zorder=z)
return tri | ['def', 'get_triangle(x,', 'y,', 'z,', 'c,', 's):', 'points', '=', 'np.array([[0,', '0],', '[s,', 's', '*', 'math.sqrt(3.0)],', '[s', '*', '2.0,', '0]])', 'tri', '=', 'plt.Polygon(points', '+', '[x', '-', 's,', 'y', '-', 's],', 'fc=c,', 'zorder=z)', 'return', 'tri'] | 965,064 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_utils.py | VideoProblem.random_skip | random_skip | Whether to skip random inputs at the beginning or not. | [
"Whether",
"to",
"skip",
"random",
"inputs",
"at",
"the",
"beginning",
"or",
"not."
] | def random_skip(self):
return True | ['def', 'random_skip(self):', 'return', 'True'] | 965,072 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_utils.py | VideoProblem.generate_encoded_samples_debug | generate_encoded_samples_debug | Generate samples of the encoded frames and dump for debug if needed. | [
"Generate",
"samples",
"of",
"the",
"encoded",
"frames",
"and",
"dump",
"for",
"debug",
"if",
"needed."
] | def generate_encoded_samples_debug(self, data_dir, tmp_dir, dataset_split):
counter = 0
for sample in self.generate_encoded_samples(data_dir, tmp_dir, dataset_split):
if self.debug_dump_frames_path:
if not tf.gfile.Exists(self.debug_dump_frames_path):
tf.gfile.MkDir(self.debu... | ['def', 'generate_encoded_samples_debug(self,', 'data_dir,', 'tmp_dir,', 'dataset_split):', 'counter', '=', '0', 'for', 'sample', 'in', 'self.generate_encoded_samples(data_dir,', 'tmp_dir,', 'dataset_split):', 'if', 'self.debug_dump_frames_path:', 'if', 'not', 'tf.gfile.Exists(self.debug_dump_frames_path):', 'tf.gfile.... | 965,080 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | video_utils.py | VideoProblem.generate_data | generate_data | The function generating the data. | [
"The",
"function",
"generating",
"the",
"data."
] | def generate_data(self, data_dir, tmp_dir, task_id=-1):
filepath_fns = {problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths}
split_paths = [(split['split'], filepath_fns[split['split']](data_dir, split['shards'], shuf... | ['def', 'generate_data(self,', 'data_dir,', 'tmp_dir,', 'task_id=-1):', 'filepath_fns', '=', '{problem.DatasetSplit.TRAIN:', 'self.training_filepaths,', 'problem.DatasetSplit.EVAL:', 'self.dev_filepaths,', 'problem.DatasetSplit.TEST:', 'self.test_filepaths}', 'split_paths', '=', "[(split['split'],", "filepath_fns[split... | 965,081 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | vqa.py | ImageVqav2Tokens10kLabels3k.vqa_v2_generator | vqa_v2_generator | VQA v2 generator using raw images. | [
"VQA",
"v2",
"generator",
"using",
"raw",
"images."
] | def vqa_v2_generator(self, data_dir, tmp_dir, datasets):
_get_vqa_v2_annotations(tmp_dir, self._VQA_V2_ANNOTATION_URL)
_get_vqa_v2_image_raw_dataset(tmp_dir, self._MSCOCO_ROOT_URL, self._MSCOCO_IMAGE_URLS)
vocab_path = os.path.join(data_dir, self.vocab_filename)
if not tf.gfile.Exists(vocab_path):
... | ['def', 'vqa_v2_generator(self,', 'data_dir,', 'tmp_dir,', 'datasets):', '_get_vqa_v2_annotations(tmp_dir,', 'self._VQA_V2_ANNOTATION_URL)', '_get_vqa_v2_image_raw_dataset(tmp_dir,', 'self._MSCOCO_ROOT_URL,', 'self._MSCOCO_IMAGE_URLS)', 'vocab_path', '=', 'os.path.join(data_dir,', 'self.vocab_filename)', 'if', 'not', '... | 965,083 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | vqa_utils.py | vqa_v2_preprocess_image | vqa_v2_preprocess_image | vqa v2 preprocess image. | [
"vqa",
"v2",
"preprocess",
"image."
] | def vqa_v2_preprocess_image(image, height, width, mode, resize_side=512, distort=True, image_model_fn='resnet_v1_152'):
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
assert resize_side > 0
if resize_side:
image = _aspect_preserving_resize(image, resize_side)
if mode == tf.estimat... | ['def', 'vqa_v2_preprocess_image(image,', 'height,', 'width,', 'mode,', 'resize_side=512,', 'distort=True,', "image_model_fn='resnet_v1_152'):", 'image', '=', 'tf.image.convert_image_dtype(image,', 'dtype=tf.float32)', 'assert', 'resize_side', '>', '0', 'if', 'resize_side:', 'image', '=', '_aspect_preserving_resize(ima... | 965,085 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | wiki.py | LanguagemodelWikiScramble.remainder_policy | remainder_policy | What to do with leftover tokens. | [
"What",
"to",
"do",
"with",
"leftover",
"tokens."
] | def remainder_policy(self):
return 'drop' | ['def', 'remainder_policy(self):', 'return', "'drop'"] | 965,090 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | html.py | get_text_from_html | get_text_from_html | Returns a plaintext representation of HTML content. | [
"Returns",
"a",
"plaintext",
"representation",
"of",
"HTML",
"content."
] | def get_text_from_html(html):
try:
soup = bs4.BeautifulSoup(html, 'html.parser')
except:
return ''
for s in soup(['script', 'style']):
s.decompose()
return '\n'.join([s for s in _soup_strings(soup)]) | ['def', 'get_text_from_html(html):', 'try:', 'soup', '=', 'bs4.BeautifulSoup(html,', "'html.parser')", 'except:', 'return', "''", 'for', 's', 'in', "soup(['script',", "'style']):", 's.decompose()', 'return', "'\\n'.join([s", 'for', 's', 'in', '_soup_strings(soup)])'] | 965,098 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | parallel_launch.py | remote_run | remote_run | Run command on GCS instance, optionally detached. | [
"Run",
"command",
"on",
"GCS",
"instance,",
"optionally",
"detached."
] | def remote_run(cmd, instance_name, detach=False, retries=1):
if detach:
cmd = SCREEN.format(command=cmd)
args = SSH.format(instance_name=instance_name).split()
args.append(cmd)
for i in range(retries + 1):
try:
if i > 0:
tf.logging.info('Retry %d for %s', i, a... | ['def', 'remote_run(cmd,', 'instance_name,', 'detach=False,', 'retries=1):', 'if', 'detach:', 'cmd', '=', 'SCREEN.format(command=cmd)', 'args', '=', 'SSH.format(instance_name=instance_name).split()', 'args.append(cmd)', 'for', 'i', 'in', 'range(retries', '+', '1):', 'try:', 'if', 'i', '>', '0:', "tf.logging.info('Retry... | 965,099 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | parallel_launch.py | wait_for_ssh | wait_for_ssh | Wait for SSH to be available at given IP address. | [
"Wait",
"for",
"SSH",
"to",
"be",
"available",
"at",
"given",
"IP",
"address."
] | def wait_for_ssh(ip):
for _ in range(12):
with safe_socket() as s:
try:
s.connect((ip, 22))
return True
except socket.timeout:
pass
time.sleep(10)
return False | ['def', 'wait_for_ssh(ip):', 'for', '_', 'in', 'range(12):', 'with', 'safe_socket()', 'as', 's:', 'try:', 's.connect((ip,', '22))', 'return', 'True', 'except', 'socket.timeout:', 'pass', 'time.sleep(10)', 'return', 'False'] | 965,100 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | parallel_launch.py | launch_instance | launch_instance | Launch a GCE instance. | [
"Launch",
"a",
"GCE",
"instance."
] | def launch_instance(instance_name, command, existing_ip=None, cpu=1, mem=4, code_dir=None, setup_command=None):
ip = existing_ip or create_instance(instance_name, cpu=cpu, mem=mem)
tf.logging.info('Waiting for SSH %s', instance_name)
ready = wait_for_ssh(ip)
if not ready:
raise ValueError('Insta... | ['def', 'launch_instance(instance_name,', 'command,', 'existing_ip=None,', 'cpu=1,', 'mem=4,', 'code_dir=None,', 'setup_command=None):', 'ip', '=', 'existing_ip', 'or', 'create_instance(instance_name,', 'cpu=cpu,', 'mem=mem)', "tf.logging.info('Waiting", 'for', 'SSH', "%s',", 'instance_name)', 'ready', '=', 'wait_for_s... | 965,101 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | utils.py | wet_records_from_file_obj | wet_records_from_file_obj | Iterate through records in WET file object. | [
"Iterate",
"through",
"records",
"in",
"WET",
"file",
"object."
] | def wet_records_from_file_obj(f, take_ownership=False):
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.close() | ['def', 'wet_records_from_file_obj(f,', 'take_ownership=False):', 'while', 'True:', 'record', '=', 'WETRecord.read(f)', 'if', 'record', 'is', 'None:', 'break', 'if', 'not', 'record.url:', 'continue', 'yield', 'record', 'if', 'take_ownership:', 'f.close()'] | 965,102 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | utils.py | shard | shard | Split items into num_shards groups. | [
"Split",
"items",
"into",
"num_shards",
"groups."
] | def shard(items, num_shards):
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - remainder
for i in rang... | ['def', 'shard(items,', 'num_shards):', 'sharded', '=', '[]', 'num_per_shard', '=', 'len(items)', '//', 'num_shards', 'start', '=', '0', 'for', '_', 'in', 'range(num_shards):', 'sharded.append(items[start:start', '+', 'num_per_shard])', 'start', '+=', 'num_per_shard', 'remainder', '=', 'len(items)', '%', 'num_shards', ... | 965,104 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | utils.py | timing | timing | Log start, end, and duration. | [
"Log",
"start,",
"end,",
"and",
"duration."
] | def timing(name=''):
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('Finished job [%s] at %s', name, timestamp)
duration ... | ['def', "timing(name=''):", 'start', '=', 'datetime.datetime.now()', 'timestamp', '=', "start.strftime('%H:%M')", "tf.logging.info('Starting", 'job', '[%s]', 'at', "%s',", 'name,', 'timestamp)', 'yield', 'end', '=', 'datetime.datetime.now()', 'timestamp', '=', "end.strftime('%H:%M')", "tf.logging.info('Finished", 'job'... | 965,106 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | validate_data.py | aggregate_stats | aggregate_stats | Aggregate stats in per-shard stats files. | [
"Aggregate",
"stats",
"in",
"per-shard",
"stats",
"files."
] | def aggregate_stats(stats_files):
all_stats = {}
for fname in stats_files:
with tf.gfile.Open(fname) as f:
stats = json.loads(f.read())
for (k, v) in stats.iteritems():
if k not in all_stats:
if isinstance(v, list):
all_... | ['def', 'aggregate_stats(stats_files):', 'all_stats', '=', '{}', 'for', 'fname', 'in', 'stats_files:', 'with', 'tf.gfile.Open(fname)', 'as', 'f:', 'stats', '=', 'json.loads(f.read())', 'for', '(k,', 'v)', 'in', 'stats.iteritems():', 'if', 'k', 'not', 'in', 'all_stats:', 'if', 'isinstance(v,', 'list):', 'all_stats[k]', ... | 965,109 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | wikisum.py | rank_reference_paragraphs | rank_reference_paragraphs | Rank and return reference paragraphs by tf-idf score on title tokens. | [
"Rank",
"and",
"return",
"reference",
"paragraphs",
"by",
"tf-idf",
"score",
"on",
"title",
"tokens."
] | def rank_reference_paragraphs(wiki_title, references_content, normalize=True):
normalized_title = _normalize_text(wiki_title)
title_tokens = _tokens_to_score(set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title))))
ref_paragraph_info = []
doc_counts = collections.defaultdict(int)
for... | ['def', 'rank_reference_paragraphs(wiki_title,', 'references_content,', 'normalize=True):', 'normalized_title', '=', '_normalize_text(wiki_title)', 'title_tokens', '=', '_tokens_to_score(set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title))))', 'ref_paragraph_info', '=', '[]', 'doc_counts', '=', 'colle... | 965,112 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | query_processor.py | QueryProcessor.process | process | Returns the generated visualizations for query. | [
"Returns",
"the",
"generated",
"visualizations",
"for",
"query."
] | def process(self, query):
del query
return {'result': []} | ['def', 'process(self,', 'query):', 'del', 'query', 'return', "{'result':", '[]}'] | 965,121 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | transformer_model.py | seq_filter | seq_filter | TFDBG data directory filter for capturing topk_seq operation dumps. | [
"TFDBG",
"data",
"directory",
"filter",
"for",
"capturing",
"topk_seq",
"operation",
"dumps."
] | def seq_filter(datum, tensor):
del tensor
return 'topk_seq' in datum.node_name | ['def', 'seq_filter(datum,', 'tensor):', 'del', 'tensor', 'return', "'topk_seq'", 'in', 'datum.node_name'] | 965,124 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | transformer_model.py | scores_filter | scores_filter | TFDBG data directory filter for capturing topk_scores operation dumps. | [
"TFDBG",
"data",
"directory",
"filter",
"for",
"capturing",
"topk_scores",
"operation",
"dumps."
] | def scores_filter(datum, tensor):
del tensor
return 'topk_scores' in datum.node_name | ['def', 'scores_filter(datum,', 'tensor):', 'del', 'tensor', 'return', "'topk_scores'", 'in', 'datum.node_name'] | 965,125 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | encoder_decoder_attention_loss | encoder_decoder_attention_loss | Computes encdec attention loss between expected and actual attentions. | [
"Computes",
"encdec",
"attention",
"loss",
"between",
"expected",
"and",
"actual",
"attentions."
] | def encoder_decoder_attention_loss(expected_attention_logits, actual_attentions, loss_type='kl_divergence', loss_multiplier=1.0):
def combine_attentions(attention_list):
attentions = tf.stack(attention_list)
return tf.reduce_mean(attentions, [0, 2])
def kl_divergence_loss(expected_logits, actu... | ['def', 'encoder_decoder_attention_loss(expected_attention_logits,', 'actual_attentions,', "loss_type='kl_divergence',", 'loss_multiplier=1.0):', 'def', 'combine_attentions(attention_list):', 'attentions', '=', 'tf.stack(attention_list)', 'return', 'tf.reduce_mean(attentions,', '[0,', '2])', 'def', 'kl_divergence_loss(... | 965,130 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | get_layer_timing_signal_sinusoid_1d | get_layer_timing_signal_sinusoid_1d | Add sinusoids of different frequencies as layer (vertical) timing signal. | [
"Add",
"sinusoids",
"of",
"different",
"frequencies",
"as",
"layer",
"(vertical)",
"timing",
"signal."
] | def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers):
signal = get_timing_signal_1d(num_layers, channels)
layer_signal = tf.expand_dims(signal[:, layer, :], axis=1)
return layer_signal | ['def', 'get_layer_timing_signal_sinusoid_1d(channels,', 'layer,', 'num_layers):', 'signal', '=', 'get_timing_signal_1d(num_layers,', 'channels)', 'layer_signal', '=', 'tf.expand_dims(signal[:,', 'layer,', ':],', 'axis=1)', 'return', 'layer_signal'] | 965,134 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | padding_to_length | padding_to_length | Calculate the length of mask based on padding. | [
"Calculate",
"the",
"length",
"of",
"mask",
"based",
"on",
"padding."
] | def padding_to_length(padding):
non_padding = 1.0 - padding
return tf.to_int32(tf.reduce_sum(non_padding, axis=-1)) | ['def', 'padding_to_length(padding):', 'non_padding', '=', '1.0', '-', 'padding', 'return', 'tf.to_int32(tf.reduce_sum(non_padding,', 'axis=-1))'] | 965,140 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | reshape_by_blocks | reshape_by_blocks | Reshapes input by splitting its length over blocks of memory_block_size. | [
"Reshapes",
"input",
"by",
"splitting",
"its",
"length",
"over",
"blocks",
"of",
"memory_block_size."
] | def reshape_by_blocks(x, x_shape, memory_block_size):
x = tf.reshape(x, [x_shape[0], x_shape[1], x_shape[2] // memory_block_size, memory_block_size, x_shape[3]])
return x | ['def', 'reshape_by_blocks(x,', 'x_shape,', 'memory_block_size):', 'x', '=', 'tf.reshape(x,', '[x_shape[0],', 'x_shape[1],', 'x_shape[2]', '//', 'memory_block_size,', 'memory_block_size,', 'x_shape[3]])', 'return', 'x'] | 965,163 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_attention.py | coordinate_tensor | coordinate_tensor | Return a tensor with given shape containing coordinate along given axis. | [
"Return",
"a",
"tensor",
"with",
"given",
"shape",
"containing",
"coordinate",
"along",
"given",
"axis."
] | def coordinate_tensor(shape, axis):
if axis < 0:
axis = tf.size(shape) + axis
r = tf.range(shape[axis])
r_shape = tf.one_hot(axis, tf.size(shape), on_value=-1, off_value=1, dtype=tf.int32)
return tf.zeros(shape, dtype=tf.int32) + tf.reshape(r, r_shape) | ['def', 'coordinate_tensor(shape,', 'axis):', 'if', 'axis', '<', '0:', 'axis', '=', 'tf.size(shape)', '+', 'axis', 'r', '=', 'tf.range(shape[axis])', 'r_shape', '=', 'tf.one_hot(axis,', 'tf.size(shape),', 'on_value=-1,', 'off_value=1,', 'dtype=tf.int32)', 'return', 'tf.zeros(shape,', 'dtype=tf.int32)', '+', 'tf.reshape... | 965,182 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | local_attention_2d | local_attention_2d | Local 2d, self attention layer. | [
"Local",
"2d,",
"self",
"attention",
"layer."
] | def local_attention_2d(x, hparams, attention_type='local_attention_2d'):
with tf.variable_scope('local_2d_self_att'):
y = common_attention.multihead_attention_2d(x, None, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hpar... | ['def', 'local_attention_2d(x,', 'hparams,', "attention_type='local_attention_2d'):", 'with', "tf.variable_scope('local_2d_self_att'):", 'y', '=', 'common_attention.multihead_attention_2d(x,', 'None,', 'hparams.attention_key_channels', 'or', 'hparams.hidden_size,', 'hparams.attention_value_channels', 'or', 'hparams.hid... | 965,210 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | local_attention_1d | local_attention_1d | Local 1d self attention. | [
"Local",
"1d",
"self",
"attention."
] | def local_attention_1d(x, hparams, attention_type='local_unmasked', q_padding='VALID', kv_padding='VALID'):
(x, x_shape, is_4d) = maybe_reshape_4d_to_3d(x)
with tf.variable_scope('local_1d_self_att'):
y = common_attention.multihead_attention(x, None, None, hparams.attention_key_channels or hparams.hidde... | ['def', 'local_attention_1d(x,', 'hparams,', "attention_type='local_unmasked',", "q_padding='VALID',", "kv_padding='VALID'):", '(x,', 'x_shape,', 'is_4d)', '=', 'maybe_reshape_4d_to_3d(x)', 'with', "tf.variable_scope('local_1d_self_att'):", 'y', '=', 'common_attention.multihead_attention(x,', 'None,', 'None,', 'hparams... | 965,212 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | get_self_attention_bias | get_self_attention_bias | Creates masked self attention bias. | [
"Creates",
"masked",
"self",
"attention",
"bias."
] | def get_self_attention_bias(x):
x_shape = common_layers.shape_list(x)
self_attention_bias = common_attention.attention_bias_lower_triangle(x_shape[1])
return self_attention_bias | ['def', 'get_self_attention_bias(x):', 'x_shape', '=', 'common_layers.shape_list(x)', 'self_attention_bias', '=', 'common_attention.attention_bias_lower_triangle(x_shape[1])', 'return', 'self_attention_bias'] | 965,217 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | transformer_layers_sharded | transformer_layers_sharded | Multi layer transformer, sharded by the data parallelism dp. | [
"Multi",
"layer",
"transformer,",
"sharded",
"by",
"the",
"data",
"parallelism",
"dp."
] | def transformer_layers_sharded(dp, ps_devices, inputs, num_layers, hparams, self_attention_bias=None, enc_output=None, attention_type=AttentionType.GLOBAL, name='transformer'):
x = inputs
extra_loss = tf.constant(0.0)
moe_hidden_sizes = [int(s) for s in hparams.moe_hidden_sizes.split(',')]
expert_fn = e... | ['def', 'transformer_layers_sharded(dp,', 'ps_devices,', 'inputs,', 'num_layers,', 'hparams,', 'self_attention_bias=None,', 'enc_output=None,', 'attention_type=AttentionType.GLOBAL,', "name='transformer'):", 'x', '=', 'inputs', 'extra_loss', '=', 'tf.constant(0.0)', 'moe_hidden_sizes', '=', '[int(s)', 'for', 's', 'in',... | 965,218 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | prepare_decoder | prepare_decoder | Prepare decoder for images. | [
"Prepare",
"decoder",
"for",
"images."
] | def prepare_decoder(targets, hparams):
targets_shape = common_layers.shape_list(targets)
channels = hparams.num_channels
curr_infer_length = None
if hparams.mode == tf.contrib.learn.ModeKeys.INFER:
curr_infer_length = targets_shape[1]
if hparams.block_raster_scan:
assert hpar... | ['def', 'prepare_decoder(targets,', 'hparams):', 'targets_shape', '=', 'common_layers.shape_list(targets)', 'channels', '=', 'hparams.num_channels', 'curr_infer_length', '=', 'None', 'if', 'hparams.mode', '==', 'tf.contrib.learn.ModeKeys.INFER:', 'curr_infer_length', '=', 'targets_shape[1]', 'if', 'hparams.block_raster... | 965,220 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_image_attention.py | create_output | create_output | Creates output from decoder output and vars. | [
"Creates",
"output",
"from",
"decoder",
"output",
"and",
"vars."
] | def create_output(decoder_output, rows, cols, targets, hparams):
decoded_image = postprocess_image(decoder_output, rows, cols, hparams)
depth = common_layers.shape_list(decoded_image)[-1]
(batch, height, width, channels) = common_layers.shape_list(targets)
likelihood = getattr(hparams, 'likelihood', Dis... | ['def', 'create_output(decoder_output,', 'rows,', 'cols,', 'targets,', 'hparams):', 'decoded_image', '=', 'postprocess_image(decoder_output,', 'rows,', 'cols,', 'hparams)', 'depth', '=', 'common_layers.shape_list(decoded_image)[-1]', '(batch,', 'height,', 'width,', 'channels)', '=', 'common_layers.shape_list(targets)',... | 965,221 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | convert_real_to_rgb | convert_real_to_rgb | Conversion of real numbers to pixel values. | [
"Conversion",
"of",
"real",
"numbers",
"to",
"pixel",
"values."
] | def convert_real_to_rgb(x):
with tf.name_scope('real_to_rgb', values=[x]):
x *= 255.0
return x | ['def', 'convert_real_to_rgb(x):', 'with', "tf.name_scope('real_to_rgb',", 'values=[x]):', 'x', '*=', '255.0', 'return', 'x'] | 965,238 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | expand_squeeze_to_nd | expand_squeeze_to_nd | Make x n-d with squeeze and expand_dims. | [
"Make",
"x",
"n-d",
"with",
"squeeze",
"and",
"expand_dims."
] | def expand_squeeze_to_nd(x, n, squeeze_dim=2, expand_dim=-1):
if len(x.shape) > n:
while len(x.shape) != n:
x = tf.squeeze(x, [squeeze_dim])
else:
while len(x.shape) != n:
x = tf.expand_dims(x, expand_dim)
return x | ['def', 'expand_squeeze_to_nd(x,', 'n,', 'squeeze_dim=2,', 'expand_dim=-1):', 'if', 'len(x.shape)', '>', 'n:', 'while', 'len(x.shape)', '!=', 'n:', 'x', '=', 'tf.squeeze(x,', '[squeeze_dim])', 'else:', 'while', 'len(x.shape)', '!=', 'n:', 'x', '=', 'tf.expand_dims(x,', 'expand_dim)', 'return', 'x'] | 965,239 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | standardize_images | standardize_images | Image standardization on batches and videos. | [
"Image",
"standardization",
"on",
"batches",
"and",
"videos."
] | def standardize_images(x):
with tf.name_scope('standardize_images', [x]):
x_shape = shape_list(x)
x = tf.to_float(tf.reshape(x, [-1] + x_shape[-3:]))
x_mean = tf.reduce_mean(x, axis=[1, 2, 3], keepdims=True)
x_variance = tf.reduce_mean(tf.square(x - x_mean), axis=[1, 2, 3], keepdims=... | ['def', 'standardize_images(x):', 'with', "tf.name_scope('standardize_images',", '[x]):', 'x_shape', '=', 'shape_list(x)', 'x', '=', 'tf.to_float(tf.reshape(x,', '[-1]', '+', 'x_shape[-3:]))', 'x_mean', '=', 'tf.reduce_mean(x,', 'axis=[1,', '2,', '3],', 'keepdims=True)', 'x_variance', '=', 'tf.reduce_mean(tf.square(x',... | 965,240 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | length_from_embedding | length_from_embedding | Compute the length of each sequence in the batch. | [
"Compute",
"the",
"length",
"of",
"each",
"sequence",
"in",
"the",
"batch."
] | def length_from_embedding(emb):
return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32) | ['def', 'length_from_embedding(emb):', 'return', 'tf.cast(tf.reduce_sum(mask_from_embedding(emb),', '[1,', '2,', '3]),', 'tf.int32)'] | 965,280 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | dml_loss | dml_loss | Discretized mixture of logistics loss. | [
"Discretized",
"mixture",
"of",
"logistics",
"loss."
] | def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True):
real_labels = convert_rgb_to_symmetric_real(labels)
dml_loss_value = discretized_mix_logistic_loss(pred=pred, labels=real_labels)
weights = weights_fn(labels)
loss_num = weights * dml_loss_value
loss_den = weights_nonzero(we... | ['def', 'dml_loss(pred,', 'labels,', 'weights_fn=_weights_one_third,', 'reduce_sum=True):', 'real_labels', '=', 'convert_rgb_to_symmetric_real(labels)', 'dml_loss_value', '=', 'discretized_mix_logistic_loss(pred=pred,', 'labels=real_labels)', 'weights', '=', 'weights_fn(labels)', 'loss_num', '=', 'weights', '*', 'dml_l... | 965,304 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.