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 |
|---|---|---|---|---|---|---|---|---|
Hironsan/tensorflow-nlp-examples | utils.py | Vocabulary.token_to_id | token_to_id | Get the token_id of given token. | [
"Get",
"the",
"token_id",
"of",
"given",
"token."
] | def token_to_id(self, token):
token = self.process_token(token)
return self._token2id.get(token, len(self._token2id) - 1) | ['def', 'token_to_id(self,', 'token):', 'token', '=', 'self.process_token(token)', 'return', 'self._token2id.get(token,', 'len(self._token2id)', '-', '1)'] | 921,508 |
Hironsan/tensorflow-nlp-examples | process_data.py | get_batch | get_batch | Group a numerical stream into batches and yield them as Numpy arrays. | [
"Group",
"a",
"numerical",
"stream",
"into",
"batches",
"and",
"yield",
"them",
"as",
"Numpy",
"arrays."
] | def get_batch(iterator, batch_size):
while True:
center_batch = np.zeros(batch_size, dtype=np.int32)
target_batch = np.zeros([batch_size, 1])
for index in range(batch_size):
(center_batch[index], target_batch[index]) = next(iterator)
yield (center_batch, target_batch) | ['def', 'get_batch(iterator,', 'batch_size):', 'while', 'True:', 'center_batch', '=', 'np.zeros(batch_size,', 'dtype=np.int32)', 'target_batch', '=', 'np.zeros([batch_size,', '1])', 'for', 'index', 'in', 'range(batch_size):', '(center_batch[index],', 'target_batch[index])', '=', 'next(iterator)', 'yield', '(center_batc... | 921,517 |
wangz10/tensorflow-playground | autoencoders.py | BaseAutoencoder.save | save | To save trained model and its params. | [
"To",
"save",
"trained",
"model",
"and",
"its",
"params."
] | def save(self, path):
if not os.path.isdir(path):
os.mkdir(path)
save_path = self.saver.save(self.sess, os.path.join(path, 'model.ckpt'), global_step=self.global_step)
params = self.get_params()
params.pop('session_kwargs', None)
json.dump(params, open(os.path.join(path, 'model_params.json')... | ['def', 'save(self,', 'path):', 'if', 'not', 'os.path.isdir(path):', 'os.mkdir(path)', 'save_path', '=', 'self.saver.save(self.sess,', 'os.path.join(path,', "'model.ckpt'),", 'global_step=self.global_step)', 'params', '=', 'self.get_params()', "params.pop('session_kwargs',", 'None)', 'json.dump(params,', 'open(os.path.... | 921,707 |
wangz10/tensorflow-playground | autoencoders.py | BaseAutoencoder.restore | restore | To restore a saved model. | [
"To",
"restore",
"a",
"saved",
"model."
] | def restore(cls, path):
path_dir = os.path.dirname(path)
params = json.load(open(os.path.join(path_dir, 'model_params.json'), 'rb'))
estimator = cls(**params)
estimator._restore(path)
global_step = int(path.split('-')[-1])
estimator.global_step = global_step
return estimator | ['def', 'restore(cls,', 'path):', 'path_dir', '=', 'os.path.dirname(path)', 'params', '=', 'json.load(open(os.path.join(path_dir,', "'model_params.json'),", "'rb'))", 'estimator', '=', 'cls(**params)', 'estimator._restore(path)', 'global_step', '=', "int(path.split('-')[-1])", 'estimator.global_step', '=', 'global_step... | 921,708 |
fpaupier/tensorflow-serving_sidecar | client.py | format_mask | format_mask | Format the m*m detection soft masks as full size binary masks. | [
"Format",
"the",
"m*m",
"detection",
"soft",
"masks",
"as",
"full",
"size",
"binary",
"masks."
] | def format_mask(detection_masks, detection_boxes, N, image_size):
(height, width, _) = image_size
output_masks = np.zeros((N, image_size[0], image_size[1]))
for i in range(N):
normalized_mask = detection_masks[i].astype(np.float32)
normalized_mask = Image.fromarray(normalized_mask, 'F')
... | ['def', 'format_mask(detection_masks,', 'detection_boxes,', 'N,', 'image_size):', '(height,', 'width,', '_)', '=', 'image_size', 'output_masks', '=', 'np.zeros((N,', 'image_size[0],', 'image_size[1]))', 'for', 'i', 'in', 'range(N):', 'normalized_mask', '=', 'detection_masks[i].astype(np.float32)', 'normalized_mask', '=... | 921,750 |
pannous/tensorflow-speech-recognition | speech_data.py | maybe_download | maybe_download | Download the data from Pannous's website, unless it's already here. | [
"Download",
"the",
"data",
"from",
"Pannous's",
"website,",
"unless",
"it's",
"already",
"here."
] | def maybe_download(file, work_directory=DATA_DIR):
print('Looking for data %s in %s' % (file, work_directory))
if not os.path.exists(work_directory):
try:
os.mkdir(work_directory)
except:
pass
filepath = os.path.join(work_directory, re.sub('.*\\/', '', file))
if n... | ['def', 'maybe_download(file,', 'work_directory=DATA_DIR):', "print('Looking", 'for', 'data', '%s', 'in', "%s'", '%', '(file,', 'work_directory))', 'if', 'not', 'os.path.exists(work_directory):', 'try:', 'os.mkdir(work_directory)', 'except:', 'pass', 'filepath', '=', 'os.path.join(work_directory,', "re.sub('.*\\\\/',",... | 922,341 |
pannous/tensorflow-speech-recognition | net.py | closest_unitary | closest_unitary | Calculate the unitary matrix U that is closest with respect to the operator norm distance to the general matrix A. | [
"Calculate",
"the",
"unitary",
"matrix",
"U",
"that",
"is",
"closest",
"with",
"respect",
"to",
"the",
"operator",
"norm",
"distance",
"to",
"the",
"general",
"matrix",
"A."
] | def closest_unitary(A):
import scipy
(V, __, Wh) = scipy.linalg.svd(A)
return np.matrix(V.dot(Wh)) | ['def', 'closest_unitary(A):', 'import', 'scipy', '(V,', '__,', 'Wh)', '=', 'scipy.linalg.svd(A)', 'return', 'np.matrix(V.dot(Wh))'] | 922,346 |
golbin/TensorFlow-Tutorials | game.py | Game.reset | reset | ìÂÂëÂÂì°¨, ìÂ¥ì 물ì ìÂÂì¹Âì 보ìÂÂê°Âë¤ì ì´Â기ÃÂÂéëÂÂë¤. | [
"ìÂÂëÂÂì°¨,",
"ìÂ¥ìÂÂ",
"물ìÂÂ",
"ìÂÂì¹ÂìÂÂ",
"ë³´ìÂÂê°Âë¤ìÂÂ",
"ì´Â기ÃÂÂéëÂÂë¤."
] | def reset(self):
self.current_reward = 0
self.total_game += 1
self.car['col'] = int(self.screen_width / 2)
self.block[0]['col'] = random.randrange(self.road_left, self.road_right + 1)
self.block[0]['row'] = 0
self.block[1]['col'] = random.randrange(self.road_left, self.road_right + 1)
self.b... | ['def', 'reset(self):', 'self.current_reward', '=', '0', 'self.total_game', '+=', '1', "self.car['col']", '=', 'int(self.screen_width', '/', '2)', "self.block[0]['col']", '=', 'random.randrange(self.road_left,', 'self.road_right', '+', '1)', "self.block[0]['row']", '=', '0', "self.block[1]['col']", '=', 'random.randran... | 922,383 |
omarabid59/TensorflowDeepSortTracking | deep_sort_tracker.py | DeepSortTracker.run | run | Run multi-target tracker on at one time step. | [
"Run",
"multi-target",
"tracker",
"on",
"at",
"one",
"time",
"step."
] | def run(self, output_data, image_np):
(height, width, _) = image_np.shape
detections = []
for (box, score) in zip(output_data.bbs, output_data.scores):
detections.append(Detection(box, score, image_np))
detections = [d for d in detections if d.confidence >= self.min_confidence]
boxes = np.ar... | ['def', 'run(self,', 'output_data,', 'image_np):', '(height,', 'width,', '_)', '=', 'image_np.shape', 'detections', '=', '[]', 'for', '(box,', 'score)', 'in', 'zip(output_data.bbs,', 'output_data.scores):', 'detections.append(Detection(box,', 'score,', 'image_np))', 'detections', '=', '[d', 'for', 'd', 'in', 'detection... | 922,447 |
omarabid59/TensorflowDeepSortTracking | AbstractPredictor.py | AbstractPredictor.getImage | getImage | Returns the resized image that we will use for prediction. | [
"Returns",
"the",
"resized",
"image",
"that",
"we",
"will",
"use",
"for",
"prediction."
] | def getImage(self):
if self.IMG_SCALE < 1.0:
self.output_data.image_np = cv2.resize(self.image_data.image_np.copy(), (0, 0), fx=self.IMG_SCALE, fy=self.IMG_SCALE)
else:
self.output_data.image_np = self.image_data.image_np
return self.output_data.image_np | ['def', 'getImage(self):', 'if', 'self.IMG_SCALE', '<', '1.0:', 'self.output_data.image_np', '=', 'cv2.resize(self.image_data.image_np.copy(),', '(0,', '0),', 'fx=self.IMG_SCALE,', 'fy=self.IMG_SCALE)', 'else:', 'self.output_data.image_np', '=', 'self.image_data.image_np', 'return', 'self.output_data.image_np'] | 922,467 |
omarabid59/TensorflowDeepSortTracking | helper.py | drawDetectedBBs | drawDetectedBBs | Draws the bounding boxes on the image ``image_np`` using the coordinates in the ``output_data`` and with the ``label_list`` as our subset. | [
"Draws",
"the",
"bounding",
"boxes",
"on",
"the",
"image",
"``image_np``",
"using",
"the",
"coordinates",
"in",
"the",
"``output_data``",
"and",
"with",
"the",
"``label_list``",
"as",
"our",
"subset."
] | def drawDetectedBBs(image_np, output_data, score_thresh=0.1):
if output_data.bbs.size > 0:
image_np = vis_util.visualize_boxes_and_labels_on_image_array(image_np, output_data.bbs, output_data.classes.astype(np.int32), output_data.scores, output_data.category_index, max_boxes_to_draw=300, use_normalized_coor... | ['def', 'drawDetectedBBs(image_np,', 'output_data,', 'score_thresh=0.1):', 'if', 'output_data.bbs.size', '>', '0:', 'image_np', '=', 'vis_util.visualize_boxes_and_labels_on_image_array(image_np,', 'output_data.bbs,', 'output_data.classes.astype(np.int32),', 'output_data.scores,', 'output_data.category_index,', 'max_box... | 922,469 |
xrick/tensorflow_nlp | loader.py | char_mapping | char_mapping | Create a dictionary and a mapping of words, sorted by frequency. | [
"Create",
"a",
"dictionary",
"and",
"a",
"mapping",
"of",
"words,",
"sorted",
"by",
"frequency."
] | def char_mapping(sentences, lower):
chars = [[x[0].lower() if lower else x[0] for x in s] for s in sentences]
dico = create_dico(chars)
dico['<PAD>'] = 10000001
dico['<UNK>'] = 10000000
(char_to_id, id_to_char) = create_mapping(dico)
print('Found %i unique words (%i in total)' % (len(dico), sum(... | ['def', 'char_mapping(sentences,', 'lower):', 'chars', '=', '[[x[0].lower()', 'if', 'lower', 'else', 'x[0]', 'for', 'x', 'in', 's]', 'for', 's', 'in', 'sentences]', 'dico', '=', 'create_dico(chars)', "dico['<PAD>']", '=', '10000001', "dico['<UNK>']", '=', '10000000', '(char_to_id,', 'id_to_char)', '=', 'create_mapping(... | 922,501 |
xrick/tensorflow_nlp | model.py | create_model | create_model | Create headline model and initialize or load parameters in session. | [
"Create",
"headline",
"model",
"and",
"initialize",
"or",
"load",
"parameters",
"in",
"session."
] | def create_model(session, train_dir, args, forward_only):
initializer = tf.random_uniform_initializer(-args.init_scale, args.init_scale)
with tf.variable_scope('', reuse=None, initializer=initializer):
model = Seq2SeqModel(args.vocab_size, args.vocab_size, args.buckets, args.hidden_size, args.num_layers... | ['def', 'create_model(session,', 'train_dir,', 'args,', 'forward_only):', 'initializer', '=', 'tf.random_uniform_initializer(-args.init_scale,', 'args.init_scale)', 'with', "tf.variable_scope('',", 'reuse=None,', 'initializer=initializer):', 'model', '=', 'Seq2SeqModel(args.vocab_size,', 'args.vocab_size,', 'args.bucke... | 922,561 |
DrewNF/Tensorflow_Object_Tracking_Video | multiclass_rectangle.py | Rectangle_Multiclass.get_code_string | get_code_string | Get the string of the label of the rect. | [
"Get",
"the",
"string",
"of",
"the",
"label",
"of",
"the",
"rect."
] | def get_code_string(self):
string = ''
if self.label_code is not -1:
string = self.label_code + ' '
return string | ['def', 'get_code_string(self):', 'string', '=', "''", 'if', 'self.label_code', 'is', 'not', '-1:', 'string', '=', 'self.label_code', '+', "'", "'", 'return', 'string'] | 923,339 |
DrewNF/Tensorflow_Object_Tracking_Video | multiclass_rectangle.py | Rectangle_Multiclass.get_coord_string | get_coord_string | Get the string of the coordinates of the rect. | [
"Get",
"the",
"string",
"of",
"the",
"coordinates",
"of",
"the",
"rect."
] | def get_coord_string(self):
string = '(' + str(self.x1) + ',' + str(self.y1) + ',' + str(self.x2) + ',' + str(self.y2) + ')'
return string | ['def', 'get_coord_string(self):', 'string', '=', "'('", '+', 'str(self.x1)', '+', "','", '+', 'str(self.y1)', '+', "','", '+', 'str(self.x2)', '+', "','", '+', 'str(self.y2)', '+', "')'", 'return', 'string'] | 923,341 |
tensorlayer/TensorLayerX | oneflow_backend.py | set_context | set_context | Set the context for the backend. | [
"Set",
"the",
"context",
"for",
"the",
"backend."
] | def set_context(**kwargs):
raise Exception('Using OneFlow backend, set_context is not supported.') | ['def', 'set_context(**kwargs):', 'raise', "Exception('Using", 'OneFlow', 'backend,', 'set_context', 'is', 'not', "supported.')"] | 923,431 |
tensorlayer/TensorLayerX | oneflow_backend.py | dtypes | dtypes | Returns the data type of dt as a DType. | [
"Returns",
"the",
"data",
"type",
"of",
"dt",
"as",
"a",
"DType."
] | def dtypes(dt):
if dt not in _dtypeDict.keys():
raise Exception('Unsupported dtype: {}'.format(dt))
return _dtypeDict[dt] | ['def', 'dtypes(dt):', 'if', 'dt', 'not', 'in', '_dtypeDict.keys():', 'raise', "Exception('Unsupported", 'dtype:', "{}'.format(dt))", 'return', '_dtypeDict[dt]'] | 923,446 |
tensorlayer/TensorLayerX | oneflow_backend.py | slice | slice | Extracts a slice from a tensor. | [
"Extracts",
"a",
"slice",
"from",
"a",
"tensor."
] | def slice(inputs, starts, sizes):
ends = [starts[i] + sizes[i] for i in range(len(starts))]
if len(inputs.shape) == 1:
return inputs[starts[0]:ends[0]]
if len(inputs.shape) == 2:
return inputs[starts[0]:ends[0], starts[1]:ends[1]]
if len(inputs.shape) == 3:
return inputs[starts[0... | ['def', 'slice(inputs,', 'starts,', 'sizes):', 'ends', '=', '[starts[i]', '+', 'sizes[i]', 'for', 'i', 'in', 'range(len(starts))]', 'if', 'len(inputs.shape)', '==', '1:', 'return', 'inputs[starts[0]:ends[0]]', 'if', 'len(inputs.shape)', '==', '2:', 'return', 'inputs[starts[0]:ends[0],', 'starts[1]:ends[1]]', 'if', 'len... | 923,470 |
tensorlayer/TensorLayerX | paddle_nn.py | rnnbase.flatten_parameters | flatten_parameters | Resets parameter data pointer to address in continuous memory block for cudnn usage. | [
"Resets",
"parameter",
"data",
"pointer",
"to",
"address",
"in",
"continuous",
"memory",
"block",
"for",
"cudnn",
"usage."
] | def flatten_parameters(self):
if self.could_use_cudnn:
params = self.parameters(include_sublayers=False)
shape = [np.prod(param.shape) for param in params]
self._all_weights = [None] * len(params)
for (i, param) in enumerate(params):
base = self.num_layers * self.bidirect... | ['def', 'flatten_parameters(self):', 'if', 'self.could_use_cudnn:', 'params', '=', 'self.parameters(include_sublayers=False)', 'shape', '=', '[np.prod(param.shape)', 'for', 'param', 'in', 'params]', 'self._all_weights', '=', '[None]', '*', 'len(params)', 'for', '(i,', 'param)', 'in', 'enumerate(params):', 'base', '=', ... | 923,542 |
tensorlayer/TensorLayerX | tensorflow_backend.py | flip | flip | Parameters ---------- x : Tensor The input tensor axis : list|tuple|int The axis(axes) to flip on. | [
"Parameters",
"----------",
"x",
":",
"Tensor",
"The",
"input",
"tensor",
"axis",
":",
"list|tuple|int",
"The",
"axis(axes)",
"to",
"flip",
"on."
] | def flip(x, axis):
raise NotImplementedError | ['def', 'flip(x,', 'axis):', 'raise', 'NotImplementedError'] | 923,667 |
tensorlayer/TensorLayerX | utils.py | file_exists | file_exists | Check whether a file exists by given file path. | [
"Check",
"whether",
"a",
"file",
"exists",
"by",
"given",
"file",
"path."
] | def file_exists(filepath):
return os.path.isfile(filepath) | ['def', 'file_exists(filepath):', 'return', 'os.path.isfile(filepath)'] | 923,760 |
tensorlayer/TensorLayerX | tensorflow_metric.py | Accuracy.reset | reset | Resets all of the metric state. | [
"Resets",
"all",
"of",
"the",
"metric",
"state."
] | def reset(self):
self.accuary.reset_states() | ['def', 'reset(self):', 'self.accuary.reset_states()'] | 923,861 |
tensorlayer/TensorLayerX | tensorflow_metric.py | Auc.result | result | Return the area (a float score) under auc curve Returns ------- computed result. | [
"Return",
"the",
"area",
"(a",
"float",
"score)",
"under",
"auc",
"curve",
"Returns",
"-------",
"computed",
"result."
] | def result(self):
tot_pos = 0.0
tot_neg = 0.0
auc = 0.0
idx = self.num_thresholds
while idx > 0:
tot_pos_prev = tot_pos
tot_neg_prev = tot_neg
tot_pos += self._stat_pos[idx]
tot_neg += self._stat_neg[idx]
auc += self.trapezoid_area(tot_neg, tot_neg_prev, tot_p... | ['def', 'result(self):', 'tot_pos', '=', '0.0', 'tot_neg', '=', '0.0', 'auc', '=', '0.0', 'idx', '=', 'self.num_thresholds', 'while', 'idx', '>', '0:', 'tot_pos_prev', '=', 'tot_pos', 'tot_neg_prev', '=', 'tot_neg', 'tot_pos', '+=', 'self._stat_pos[idx]', 'tot_neg', '+=', 'self._stat_neg[idx]', 'auc', '+=', 'self.trape... | 923,863 |
tensorlayer/TensorLayerX | tensorflow_metric.py | Precision.result | result | Return the precision Returns ------- computed result. | [
"Return",
"the",
"precision",
"Returns",
"-------",
"computed",
"result."
] | def result(self):
return self.precision.result().numpy() | ['def', 'result(self):', 'return', 'self.precision.result().numpy()'] | 923,866 |
tensorlayer/TensorLayerX | tensorflow_metric.py | Recall.result | result | Return the recall Returns ------- computed result. | [
"Return",
"the",
"recall",
"Returns",
"-------",
"computed",
"result."
] | def result(self):
return self.recall.result().numpy() | ['def', 'result(self):', 'return', 'self.recall.result().numpy()'] | 923,869 |
tensorlayer/TensorLayerX | core_mindspore.py | Module.save_weights | save_weights | Input file_path, save model weights into a file of given format. | [
"Input",
"file_path,",
"save",
"model",
"weights",
"into",
"a",
"file",
"of",
"given",
"format."
] | def save_weights(self, file_path, format=None):
_save_weights(self, file_path, format) | ['def', 'save_weights(self,', 'file_path,', 'format=None):', '_save_weights(self,', 'file_path,', 'format)'] | 923,876 |
tensorlayer/TensorLayerX | core_oneflow.py | ModuleList.insert | insert | Inserts a given layer before a given index in the list. | [
"Inserts",
"a",
"given",
"layer",
"before",
"a",
"given",
"index",
"in",
"the",
"list."
] | def insert(self, index, layer):
idx = _valid_index(len(self), index)
_valid_module(layer)
length = len(self)
while length > idx:
self._modules[str(length)] = self._modules[str(length - 1)]
length -= 1
self._modules[str(idx)] = layer | ['def', 'insert(self,', 'index,', 'layer):', 'idx', '=', '_valid_index(len(self),', 'index)', '_valid_module(layer)', 'length', '=', 'len(self)', 'while', 'length', '>', 'idx:', 'self._modules[str(length)]', '=', 'self._modules[str(length', '-', '1)]', 'length', '-=', '1', 'self._modules[str(idx)]', '=', 'layer'] | 923,889 |
tensorlayer/TensorLayerX | core_oneflow.py | ModuleList.append | append | Appends a given layer to the end of the list. | [
"Appends",
"a",
"given",
"layer",
"to",
"the",
"end",
"of",
"the",
"list."
] | def append(self, layer):
if _valid_module(layer):
self._modules[str(len(self))] = layer | ['def', 'append(self,', 'layer):', 'if', '_valid_module(layer):', 'self._modules[str(len(self))]', '=', 'layer'] | 923,891 |
tensorlayer/TensorLayerX | core_tensorflow.py | Module.layers | layers | Returns an iterator over immediate layers. | [
"Returns",
"an",
"iterator",
"over",
"immediate",
"layers."
] | def layers(self):
return self.name_layers().values() | ['def', 'layers(self):', 'return', 'self.name_layers().values()'] | 923,917 |
tensorlayer/TensorLayerX | functional.py | try_import | try_import | Try importing a module, with an informative error message on failure. | [
"Try",
"importing",
"a",
"module,",
"with",
"an",
"informative",
"error",
"message",
"on",
"failure."
] | def try_import(module_name):
install_name = module_name
if module_name.find('.') > -1:
install_name = module_name.split('.')[0]
if module_name == 'cv2':
install_name = 'opencv-python'
try:
mod = importlib.import_module(module_name)
return mod
except ImportError:
... | ['def', 'try_import(module_name):', 'install_name', '=', 'module_name', 'if', "module_name.find('.')", '>', '-1:', 'install_name', '=', "module_name.split('.')[0]", 'if', 'module_name', '==', "'cv2':", 'install_name', '=', "'opencv-python'", 'try:', 'mod', '=', 'importlib.import_module(module_name)', 'return', 'mod', '... | 924,070 |
tensorlayer/TensorLayerX | functional.py | adjust_contrast | adjust_contrast | Adjusts contrast of an image. | [
"Adjusts",
"contrast",
"of",
"an",
"image."
] | def adjust_contrast(image, contrast_factor):
if contrast_factor < 0:
raise ValueError('contrast_factor ({}) is not non-negative.'.format(contrast_factor))
table = np.array([(i - 127) * contrast_factor + 127 for i in range(0, 256)]).clip(0, 255).astype('uint8')
if len(image.shape) == 3 and image.shap... | ['def', 'adjust_contrast(image,', 'contrast_factor):', 'if', 'contrast_factor', '<', '0:', 'raise', "ValueError('contrast_factor", '({})', 'is', 'not', "non-negative.'.format(contrast_factor))", 'table', '=', 'np.array([(i', '-', '127)', '*', 'contrast_factor', '+', '127', 'for', 'i', 'in', 'range(0,', '256)]).clip(0,'... | 924,071 |
tensorlayer/TensorLayerX | functional.py | adjust_saturation | adjust_saturation | Adjusts color saturation of an image. | [
"Adjusts",
"color",
"saturation",
"of",
"an",
"image."
] | def adjust_saturation(image, saturation_factor):
if saturation_factor < 0:
raise ValueError('saturation_factor ({}) is not non-negative.'.format(saturation_factor))
dtype = image.dtype
image = image.astype(np.float32)
alpha = np.random.uniform(saturation_factor, saturation_factor)
gray_img =... | ['def', 'adjust_saturation(image,', 'saturation_factor):', 'if', 'saturation_factor', '<', '0:', 'raise', "ValueError('saturation_factor", '({})', 'is', 'not', "non-negative.'.format(saturation_factor))", 'dtype', '=', 'image.dtype', 'image', '=', 'image.astype(np.float32)', 'alpha', '=', 'np.random.uniform(saturation_... | 924,073 |
tensorlayer/TensorLayerX | functional.py | hflip | hflip | Horizontally flips the given image. | [
"Horizontally",
"flips",
"the",
"given",
"image."
] | def hflip(image):
return cv2.flip(image, 1) | ['def', 'hflip(image):', 'return', 'cv2.flip(image,', '1)'] | 924,074 |
tensorlayer/TensorLayerX | functional.py | rotate | rotate | Rotates the image by angle. | [
"Rotates",
"the",
"image",
"by",
"angle."
] | def rotate(img, angle, interpolation, expand, center, fill):
_cv2_interp_from_str = {'nearest': cv2.INTER_NEAREST, 'bilinear': cv2.INTER_LINEAR, 'area': cv2.INTER_AREA, 'bicubic': cv2.INTER_CUBIC, 'lanczos': cv2.INTER_LANCZOS4}
(h, w) = img.shape[0:2]
if center is None:
center = (w / 2.0, h / 2.0)
... | ['def', 'rotate(img,', 'angle,', 'interpolation,', 'expand,', 'center,', 'fill):', '_cv2_interp_from_str', '=', "{'nearest':", 'cv2.INTER_NEAREST,', "'bilinear':", 'cv2.INTER_LINEAR,', "'area':", 'cv2.INTER_AREA,', "'bicubic':", 'cv2.INTER_CUBIC,', "'lanczos':", 'cv2.INTER_LANCZOS4}', '(h,', 'w)', '=', 'img.shape[0:2]'... | 924,077 |
tensorx/tensorx | activation.py | identity | identity | Identity function Returns a tensor with the same content as the input tensor. | [
"Identity",
"function",
"Returns",
"a",
"tensor",
"with",
"the",
"same",
"content",
"as",
"the",
"input",
"tensor."
] | def identity(x, name: str=None) -> tf.Tensor:
return tf.identity(x, name=name) | ['def', 'identity(x,', 'name:', 'str=None)', '->', 'tf.Tensor:', 'return', 'tf.identity(x,', 'name=name)'] | 924,111 |
tensorx/tensorx | layers.py | LayerConfig.filter_args | filter_args | filter_args filters a given keyword argument dictionary removing any argument that is not present in the constructor for the current Layer type. | [
"filter_args",
"filters",
"a",
"given",
"keyword",
"argument",
"dictionary",
"removing",
"any",
"argument",
"that",
"is",
"not",
"present",
"in",
"the",
"constructor",
"for",
"the",
"current",
"Layer",
"type."
] | def filter_args(self, **kwargs):
new_kwargs = dict(kwargs)
for key in kwargs:
if key not in self.arg_names and (not self.arg_spec.varkw):
del new_kwargs[key]
return new_kwargs | ['def', 'filter_args(self,', '**kwargs):', 'new_kwargs', '=', 'dict(kwargs)', 'for', 'key', 'in', 'kwargs:', 'if', 'key', 'not', 'in', 'self.arg_names', 'and', '(not', 'self.arg_spec.varkw):', 'del', 'new_kwargs[key]', 'return', 'new_kwargs'] | 924,136 |
tensorx/tensorx | layers.py | LayerConfig.update | update | update Updates the config constructor argument dictionary and validates those parameters. | [
"update",
"Updates",
"the",
"config",
"constructor",
"argument",
"dictionary",
"and",
"validates",
"those",
"parameters."
] | def update(self, **kwargs):
self._validate_args(**kwargs)
self.kwargs.update(kwargs) | ['def', 'update(self,', '**kwargs):', 'self._validate_args(**kwargs)', 'self.kwargs.update(kwargs)'] | 924,137 |
tensorx/tensorx | layers.py | Wrap.reuse_with | reuse_with | Reuse with a different input layer Calls reuse with on the wrapped layer and then creates a new wrapped layer around it, using the current tensor function. | [
"Reuse",
"with",
"a",
"different",
"input",
"layer",
"Calls",
"reuse",
"with",
"on",
"the",
"wrapped",
"layer",
"and",
"then",
"creates",
"a",
"new",
"wrapped",
"layer",
"around",
"it,",
"using",
"the",
"current",
"tensor",
"function."
] | def reuse_with(self, *layers, name=None):
new_wrapped = self.wrapped.reuse_with(*layers)
attr_fwd = self.fwd_attr
if isinstance(new_wrapped, Wrap):
attr_fwd += new_wrapped.fwd_attr
if name is None:
name = self.name
return Wrap(wrapped_layer=new_wrapped, n_units=self.n_units, wrap_fn=... | ['def', 'reuse_with(self,', '*layers,', 'name=None):', 'new_wrapped', '=', 'self.wrapped.reuse_with(*layers)', 'attr_fwd', '=', 'self.fwd_attr', 'if', 'isinstance(new_wrapped,', 'Wrap):', 'attr_fwd', '+=', 'new_wrapped.fwd_attr', 'if', 'name', 'is', 'None:', 'name', '=', 'self.name', 'return', 'Wrap(wrapped_layer=new_w... | 924,145 |
tensorx/tensorx | layers.py | Linear.reuse_with | reuse_with | Reuses the current layer on a different input. | [
"Reuses",
"the",
"current",
"layer",
"on",
"a",
"different",
"input."
] | def reuse_with(self, input_layer, name=None, transpose_weights=None, sparse_weights=None, shape=None):
share_state_with = self if self.share_state_with is None else self.share_state_with
if name is None:
name = self.name
if transpose_weights is None:
transpose_weights = self.transpose_weight... | ['def', 'reuse_with(self,', 'input_layer,', 'name=None,', 'transpose_weights=None,', 'sparse_weights=None,', 'shape=None):', 'share_state_with', '=', 'self', 'if', 'self.share_state_with', 'is', 'None', 'else', 'self.share_state_with', 'if', 'name', 'is', 'None:', 'name', '=', 'self.name', 'if', 'transpose_weights', 'i... | 924,149 |
tensorx/tensorx | math.py | rms | rms | Root mean square (RMS) Also known as quadratic mean is defined as: $x_{\mathrm{RMS}}=\sqrt{\frac{x_{1}^{2}+x_{2}^{2}+\ldots+x_{n}^{2}}{n}}$ In estimation theory, the root-mean-square deviation of an estimator is a measure of the imperfection of the fit of the estimator to the data. | [
"Root",
"mean",
"square",
"(RMS)",
"Also",
"known",
"as",
"quadratic",
"mean",
"is",
"defined",
"as:",
"$x_{\\mathrm{RMS}}=\\sqrt{\\frac{x_{1}^{2}+x_{2}^{2}+\\ldots+x_{n}^{2}}{n}}$",
"In",
"estimation",
"theory,",
"the",
"root-mean-square",
"deviation",
"of",
"an",
"estimat... | def rms(x):
return tf.sqrt(tf.reduce_mean(tf.square(x))) | ['def', 'rms(x):', 'return', 'tf.sqrt(tf.reduce_mean(tf.square(x)))'] | 924,162 |
tensorx/tensorx | math.py | sparse_sparse_multiply | sparse_sparse_multiply | Element-wise multiplication of two sparse tensors !!! warning if the two sparse tensors don't overlap, returns an empty sparse tensor. | [
"Element-wise",
"multiplication",
"of",
"two",
"sparse",
"tensors",
"!!!",
"warning",
"if",
"the",
"two",
"sparse",
"tensors",
"don't",
"overlap,",
"returns",
"an",
"empty",
"sparse",
"tensor."
] | def sparse_sparse_multiply(sp_tensor1, sp_tensor2):
overlap1 = ops.sparse_overlap(sp_tensor1, sp_tensor2)
overlap2 = ops.sparse_overlap(sp_tensor2, sp_tensor1)
values = tf.math.multiply(overlap1.values, overlap2.values)
return tf.SparseTensor(overlap1.indices, values, overlap1.dense_shape) | ['def', 'sparse_sparse_multiply(sp_tensor1,', 'sp_tensor2):', 'overlap1', '=', 'ops.sparse_overlap(sp_tensor1,', 'sp_tensor2)', 'overlap2', '=', 'ops.sparse_overlap(sp_tensor2,', 'sp_tensor1)', 'values', '=', 'tf.math.multiply(overlap1.values,', 'overlap2.values)', 'return', 'tf.SparseTensor(overlap1.indices,', 'values... | 924,165 |
tensorx/tensorx | ops.py | binary_random_mask | binary_random_mask | Creates a binary mask with the same shape as the given tensor, randomly generated from the given mask probability. | [
"Creates",
"a",
"binary",
"mask",
"with",
"the",
"same",
"shape",
"as",
"the",
"given",
"tensor,",
"randomly",
"generated",
"from",
"the",
"given",
"mask",
"probability."
] | def binary_random_mask(tensor, mask_probability=0.0, seed=None):
with tf.name_scope(name='random_mask'):
tensor = as_tensor(tensor)
noise_shape = _get_noise_shape(tensor, None)
keep_prob = 1 - mask_probability
random_state = tf.random.uniform(noise_shape, seed=seed, dtype=tensor.dtyp... | ['def', 'binary_random_mask(tensor,', 'mask_probability=0.0,', 'seed=None):', 'with', "tf.name_scope(name='random_mask'):", 'tensor', '=', 'as_tensor(tensor)', 'noise_shape', '=', '_get_noise_shape(tensor,', 'None)', 'keep_prob', '=', '1', '-', 'mask_probability', 'random_state', '=', 'tf.random.uniform(noise_shape,', ... | 924,185 |
tensorx/tensorx | ops.py | sparse_overlap | sparse_overlap | sparse overlap Returns a `SparseTensor` where the indices of the overlapping indices in the two sparse tensors with the values of the first one. | [
"sparse",
"overlap",
"Returns",
"a",
"`SparseTensor`",
"where",
"the",
"indices",
"of",
"the",
"overlapping",
"indices",
"in",
"the",
"two",
"sparse",
"tensors",
"with",
"the",
"values",
"of",
"the",
"first",
"one."
] | def sparse_overlap(sp_tensor1, sp_tensor2, name='sparse_overlap'):
with tf.name_scope(name):
ones1 = mx.sparse_ones(sp_tensor1.indices, sp_tensor1.dense_shape)
ones2 = mx.sparse_ones(sp_tensor2.indices, sp_tensor2.dense_shape)
index_union = tf.sparse.add(ones1, ones2)
index_filter = ... | ['def', 'sparse_overlap(sp_tensor1,', 'sp_tensor2,', "name='sparse_overlap'):", 'with', 'tf.name_scope(name):', 'ones1', '=', 'mx.sparse_ones(sp_tensor1.indices,', 'sp_tensor1.dense_shape)', 'ones2', '=', 'mx.sparse_ones(sp_tensor2.indices,', 'sp_tensor2.dense_shape)', 'index_union', '=', 'tf.sparse.add(ones1,', 'ones2... | 924,191 |
tensorx/tensorx | utils.py | cast_like | cast_like | Cast x to y's dtype, if necessary. | [
"Cast",
"x",
"to",
"y's",
"dtype,",
"if",
"necessary."
] | def cast_like(x, y):
x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
if x.dtype.base_dtype == y.dtype.base_dtype:
return x
cast_x = tf.cast(x, y.dtype)
if cast_x.device != x.device:
x_name = '(eager Tensor)'
try:
x_name = x.name
except AttributeErr... | ['def', 'cast_like(x,', 'y):', 'x', '=', 'tf.convert_to_tensor(x)', 'y', '=', 'tf.convert_to_tensor(y)', 'if', 'x.dtype.base_dtype', '==', 'y.dtype.base_dtype:', 'return', 'x', 'cast_x', '=', 'tf.cast(x,', 'y.dtype)', 'if', 'cast_x.device', '!=', 'x.device:', 'x_name', '=', "'(eager", "Tensor)'", 'try:', 'x_name', '=',... | 924,207 |
tensorx/tensorx | utils.py | fix_reshape_dimensions | fix_reshape_dimensions | Find and replace a missing dimension in a target shape. | [
"Find",
"and",
"replace",
"a",
"missing",
"dimension",
"in",
"a",
"target",
"shape."
] | def fix_reshape_dimensions(original_shape, target_shape):
target_shape = list(target_shape)
target_n = 1
target_unknown = None
for (i, dim) in enumerate(target_shape):
if dim < 0:
if target_unknown is None:
target_unknown = i
else:
raise Va... | ['def', 'fix_reshape_dimensions(original_shape,', 'target_shape):', 'target_shape', '=', 'list(target_shape)', 'target_n', '=', '1', 'target_unknown', '=', 'None', 'for', '(i,', 'dim)', 'in', 'enumerate(target_shape):', 'if', 'dim', '<', '0:', 'if', 'target_unknown', 'is', 'None:', 'target_unknown', '=', 'i', 'else:', ... | 924,208 |
tensorx/tensorx | utils.py | Graph.add_edge | add_edge | Adds a new edge to the graph also removes nodes from input roots or outputs to reflect the current edge if necessary. | [
"Adds",
"a",
"new",
"edge",
"to",
"the",
"graph",
"also",
"removes",
"nodes",
"from",
"input",
"roots",
"or",
"outputs",
"to",
"reflect",
"the",
"current",
"edge",
"if",
"necessary."
] | def add_edge(self, node1, node2):
self.add_node(node1)
self.add_node(node2)
self.edges_out[node1].append(node2)
self.edges_in[node2].append(node1)
if node1 in self.out_nodes:
del self.out_nodes[node1]
if node2 in self.in_nodes:
del self.in_nodes[node2] | ['def', 'add_edge(self,', 'node1,', 'node2):', 'self.add_node(node1)', 'self.add_node(node2)', 'self.edges_out[node1].append(node2)', 'self.edges_in[node2].append(node1)', 'if', 'node1', 'in', 'self.out_nodes:', 'del', 'self.out_nodes[node1]', 'if', 'node2', 'in', 'self.in_nodes:', 'del', 'self.in_nodes[node2]'] | 924,209 |
asyml/texar | prepare_data.py | prepare_data | prepare_data | Builds the model and runs. | [
"Builds",
"the",
"model",
"and",
"runs."
] | def prepare_data():
data_dir = FLAGS.data_dir
if FLAGS.tfrecord_output_dir is None:
tfrecord_output_dir = data_dir
else:
tfrecord_output_dir = FLAGS.tfrecord_output_dir
tx.utils.maybe_create_dir(tfrecord_output_dir)
proc = processor.get_encoder(FLAGS.pretrain_model_dir)
data_util... | ['def', 'prepare_data():', 'data_dir', '=', 'FLAGS.data_dir', 'if', 'FLAGS.tfrecord_output_dir', 'is', 'None:', 'tfrecord_output_dir', '=', 'data_dir', 'else:', 'tfrecord_output_dir', '=', 'FLAGS.tfrecord_output_dir', 'tx.utils.maybe_create_dir(tfrecord_output_dir)', 'proc', '=', 'processor.get_encoder(FLAGS.pretrain_m... | 924,275 |
asyml/texar | data_utils.py | file_based_convert_examples_to_features | file_based_convert_examples_to_features | Converts a set of examples to a TFRecord file. | [
"Converts",
"a",
"set",
"of",
"examples",
"to",
"a",
"TFRecord",
"file."
] | def file_based_convert_examples_to_features(examples, max_seq_length, encoder, output_file, BOS_token='<|endoftext|>', EOS_token='<|endoftext|>', PAD_token='<|endoftext|>'):
writer = tf.python_io.TFRecordWriter(output_file)
for (_, example) in enumerate(examples):
(text_ids, length) = process_single_tex... | ['def', 'file_based_convert_examples_to_features(examples,', 'max_seq_length,', 'encoder,', 'output_file,', "BOS_token='<|endoftext|>',", "EOS_token='<|endoftext|>',", "PAD_token='<|endoftext|>'):", 'writer', '=', 'tf.python_io.TFRecordWriter(output_file)', 'for', '(_,', 'example)', 'in', 'enumerate(examples):', '(text... | 924,278 |
asyml/texar | embedding_test.py | EmbeddingTest.test_load_word2vec | test_load_word2vec | Tests the load_word2vec function. | [
"Tests",
"the",
"load_word2vec",
"function."
] | def test_load_word2vec(self):
header = '2 3'
words = ['word', 'è¯Â\x8d']
vec = np.array([1.2, 3.4, 5.6], dtype='float32')
w2v_file = tempfile.NamedTemporaryFile()
w2v_file.write(tf.compat.as_bytes(header + '\n'))
for word in words:
w2v_file.write(tf.compat.as_bytes(word + ' '))
... | ['def', 'test_load_word2vec(self):', 'header', '=', "'2", "3'", 'words', '=', "['word',", "'è¯Â\\x8d']", 'vec', '=', 'np.array([1.2,', '3.4,', '5.6],', "dtype='float32')", 'w2v_file', '=', 'tempfile.NamedTemporaryFile()', 'w2v_file.write(tf.compat.as_bytes(header', '+', "'\\n'))", 'for', 'word', 'in', 'words:', 'w2v_... | 924,320 |
asyml/texar | data_iterators_test.py | DataIteratorTest.test_iterator_single_dataset | test_iterator_single_dataset | Tests iterating over a single dataset. | [
"Tests",
"iterating",
"over",
"a",
"single",
"dataset."
] | def test_iterator_single_dataset(self):
data = tx.data.MonoTextData(self._test_hparams)
iterator = tx.data.DataIterator(data)
data_batch = iterator.get_next()
with self.test_session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
... | ['def', 'test_iterator_single_dataset(self):', 'data', '=', 'tx.data.MonoTextData(self._test_hparams)', 'iterator', '=', 'tx.data.DataIterator(data)', 'data_batch', '=', 'iterator.get_next()', 'with', 'self.test_session()', 'as', 'sess:', 'sess.run(tf.global_variables_initializer())', 'sess.run(tf.local_variables_initi... | 924,322 |
asyml/texar | bert_classifier_test.py | BERTClassifierTest.test_model_loading | test_model_loading | Tests model loading functionality. | [
"Tests",
"model",
"loading",
"functionality."
] | def test_model_loading(self):
inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
for pretrained_model_name in BERTClassifier.available_checkpoints():
classifier = BERTClassifier(pretrained_model_name=pretrained_model_name)
(_, _) = classifier(inputs) | ['def', 'test_model_loading(self):', 'inputs', '=', 'tf.placeholder(dtype=tf.int32,', 'shape=[None,', 'None])', 'for', 'pretrained_model_name', 'in', 'BERTClassifier.available_checkpoints():', 'classifier', '=', 'BERTClassifier(pretrained_model_name=pretrained_model_name)', '(_,', '_)', '=', 'classifier(inputs)'] | 924,345 |
asyml/texar | beam_search_decode_test.py | BeamSearchDecodeTest.test_basic_rnn_decoder_given_initial_state | test_basic_rnn_decoder_given_initial_state | Tests beam search with BasicRNNDecoder given initial state. | [
"Tests",
"beam",
"search",
"with",
"BasicRNNDecoder",
"given",
"initial",
"state."
] | def test_basic_rnn_decoder_given_initial_state(self):
hparams = {'rnn_cell': {'kwargs': {'num_units': self._cell_dim}}}
decoder = tx.modules.BasicRNNDecoder(vocab_size=self._vocab_size, hparams=hparams)
cell_state = decoder.cell.zero_state(self._batch_size, tf.float32)
self._test_beam_search(decoder, in... | ['def', 'test_basic_rnn_decoder_given_initial_state(self):', 'hparams', '=', "{'rnn_cell':", "{'kwargs':", "{'num_units':", 'self._cell_dim}}}', 'decoder', '=', 'tx.modules.BasicRNNDecoder(vocab_size=self._vocab_size,', 'hparams=hparams)', 'cell_state', '=', 'decoder.cell.zero_state(self._batch_size,', 'tf.float32)', '... | 924,358 |
asyml/texar | gpt2_decoder_test.py | GPT2DecoderTest.test_hparams | test_hparams | Tests the priority of the decoder arch parameters. | [
"Tests",
"the",
"priority",
"of",
"the",
"decoder",
"arch",
"parameters."
] | def test_hparams(self):
inputs = tf.placeholder(dtype=tf.int32, shape=[2, 3])
hparams = {'pretrained_model_name': 'gpt2-medium'}
decoder = GPT2Decoder(pretrained_model_name='gpt2-small', hparams=hparams)
_ = decoder(inputs=inputs)
self.assertEqual(decoder.hparams.decoder.num_blocks, 12)
hparams ... | ['def', 'test_hparams(self):', 'inputs', '=', 'tf.placeholder(dtype=tf.int32,', 'shape=[2,', '3])', 'hparams', '=', "{'pretrained_model_name':", "'gpt2-medium'}", 'decoder', '=', "GPT2Decoder(pretrained_model_name='gpt2-small',", 'hparams=hparams)', '_', '=', 'decoder(inputs=inputs)', 'self.assertEqual(decoder.hparams.... | 924,361 |
asyml/texar | rnn_decoders_test.py | BasicRNNDecoderTest.test_decode_train_with_tf | test_decode_train_with_tf | Compares decoding results with TF built-in decoder. | [
"Compares",
"decoding",
"results",
"with",
"TF",
"built-in",
"decoder."
] | def test_decode_train_with_tf(self):
_inputs_placeholder = tf.placeholder(tf.int32, [self._batch_size, self._max_time], name='inputs')
_embedding_placeholder = tf.placeholder(tf.float32, [self._vocab_size, self._emb_dim], name='emb')
inputs = tf.nn.embedding_lookup(_embedding_placeholder, _inputs_placeholde... | ['def', 'test_decode_train_with_tf(self):', '_inputs_placeholder', '=', 'tf.placeholder(tf.int32,', '[self._batch_size,', 'self._max_time],', "name='inputs')", '_embedding_placeholder', '=', 'tf.placeholder(tf.float32,', '[self._vocab_size,', 'self._emb_dim],', "name='emb')", 'inputs', '=', 'tf.nn.embedding_lookup(_emb... | 924,364 |
asyml/texar | xlnet_regressor_test.py | XLNetRegressorTest.test_regression | test_regression | Test the type of regression output. | [
"Test",
"the",
"type",
"of",
"regression",
"output."
] | def test_regression(self):
batch_size = 8
hparams = {'pretrained_model_name': None, 'regr_strategy': 'cls_time'}
inputs = tf.placeholder(tf.int32, shape=[batch_size, 6])
regressor = XLNetRegressor(hparams=hparams)
logits = regressor(inputs)
with self.test_session() as sess:
sess.run(tf.g... | ['def', 'test_regression(self):', 'batch_size', '=', '8', 'hparams', '=', "{'pretrained_model_name':", 'None,', "'regr_strategy':", "'cls_time'}", 'inputs', '=', 'tf.placeholder(tf.int32,', 'shape=[batch_size,', '6])', 'regressor', '=', 'XLNetRegressor(hparams=hparams)', 'logits', '=', 'regressor(inputs)', 'with', 'sel... | 924,389 |
asyml/texar | context.py | global_mode_eval | global_mode_eval | Returns a bool Tensor indicating whether the global mode is EVAL. | [
"Returns",
"a",
"bool",
"Tensor",
"indicating",
"whether",
"the",
"global",
"mode",
"is",
"EVAL."
] | def global_mode_eval():
mode = global_mode()
return tf.equal(mode, tf.estimator.ModeKeys.EVAL) | ['def', 'global_mode_eval():', 'mode', '=', 'global_mode()', 'return', 'tf.equal(mode,', 'tf.estimator.ModeKeys.EVAL)'] | 924,394 |
asyml/texar | agent_utils.py | Space.dtype | dtype | Data type of the element. | [
"Data",
"type",
"of",
"the",
"element."
] | def dtype(self):
return self._dtype | ['def', 'dtype(self):', 'return', 'self._dtype'] | 924,417 |
asyml/texar | layers.py | get_rnn_cell_trainable_variables | get_rnn_cell_trainable_variables | Returns the list of trainable variables of an RNN cell. | [
"Returns",
"the",
"list",
"of",
"trainable",
"variables",
"of",
"an",
"RNN",
"cell."
] | def get_rnn_cell_trainable_variables(cell):
cell_ = cell
while True:
try:
return cell_.trainable_variables
except AttributeError:
cell_ = cell._cell | ['def', 'get_rnn_cell_trainable_variables(cell):', 'cell_', '=', 'cell', 'while', 'True:', 'try:', 'return', 'cell_.trainable_variables', 'except', 'AttributeError:', 'cell_', '=', 'cell._cell'] | 924,433 |
asyml/texar | layers.py | SequentialLayer.layers | layers | The list of layers connected sequentially. | [
"The",
"list",
"of",
"layers",
"connected",
"sequentially."
] | def layers(self):
return self._layers | ['def', 'layers(self):', 'return', 'self._layers'] | 924,446 |
asyml/texar | optimization.py | get_optimizer | get_optimizer | Creates a optimizer instance. | [
"Creates",
"a",
"optimizer",
"instance."
] | def get_optimizer(learning_rate=None, global_step=None, hparams=None):
hparams = HParams(hparams, default_optimization_hparams())
opt_hparams = hparams['optimizer']
(optimizer_fn, optimizer_class) = get_optimizer_fn(opt_hparams)
static_lr = _get_static_lr(learning_rate, optimizer_class, hparams)
lr_... | ['def', 'get_optimizer(learning_rate=None,', 'global_step=None,', 'hparams=None):', 'hparams', '=', 'HParams(hparams,', 'default_optimization_hparams())', 'opt_hparams', '=', "hparams['optimizer']", '(optimizer_fn,', 'optimizer_class)', '=', 'get_optimizer_fn(opt_hparams)', 'static_lr', '=', '_get_static_lr(learning_ra... | 924,450 |
asyml/texar | replay_memories.py | DequeReplayMemory.size | size | Returns the current size of the memory. | [
"Returns",
"the",
"current",
"size",
"of",
"the",
"memory."
] | def size(self):
return len(self.deque) | ['def', 'size(self):', 'return', 'len(self.deque)'] | 924,461 |
asyml/texar | embedding.py | load_word2vec | load_word2vec | Loads embeddings in the word2vec binary format which has a header line containing the number of vectors and their dimensionality (two integers), followed with number-of-vectors lines each of which is formatted as '<word-string> <embedding-vector>'. | [
"Loads",
"embeddings",
"in",
"the",
"word2vec",
"binary",
"format",
"which",
"has",
"a",
"header",
"line",
"containing",
"the",
"number",
"of",
"vectors",
"and",
"their",
"dimensionality",
"(two",
"integers),",
"followed",
"with",
"number-of-vectors",
"lines",
"ea... | def load_word2vec(filename, vocab, word_vecs):
with gfile.GFile(filename, 'rb') as fin:
header = fin.readline()
(vocab_size, vector_size) = [int(s) for s in header.split()]
if vector_size != word_vecs.shape[1]:
raise ValueError('Inconsistent word vector sizes: %d vs %d' % (vector... | ['def', 'load_word2vec(filename,', 'vocab,', 'word_vecs):', 'with', 'gfile.GFile(filename,', "'rb')", 'as', 'fin:', 'header', '=', 'fin.readline()', '(vocab_size,', 'vector_size)', '=', '[int(s)', 'for', 's', 'in', 'header.split()]', 'if', 'vector_size', '!=', 'word_vecs.shape[1]:', 'raise', "ValueError('Inconsistent",... | 924,484 |
asyml/texar | data_iterators.py | DataIteratorBase.dataset_names | dataset_names | A list of dataset names. | [
"A",
"list",
"of",
"dataset",
"names."
] | def dataset_names(self):
return list(self._datasets.keys()) | ['def', 'dataset_names(self):', 'return', 'list(self._datasets.keys())'] | 924,516 |
asyml/texar | paired_text_data.py | PairedTextData.length_name | length_name | The name of length tensor, "length" by default. | [
"The",
"name",
"of",
"length",
"tensor,",
"\"length\"",
"by",
"default."
] | def length_name(self):
return self._src_decoder.length_tensor_name | ['def', 'length_name(self):', 'return', 'self._src_decoder.length_tensor_name'] | 924,574 |
asyml/texar | tfrecord_data.py | TFRecordData.feature_names | feature_names | A list of feature names. | [
"A",
"list",
"of",
"feature",
"names."
] | def feature_names(self):
return self.list_items() | ['def', 'feature_names(self):', 'return', 'self.list_items()'] | 924,582 |
asyml/texar | gpt2_tokenizer.py | GPT2Tokenizer.map_token_to_text | map_token_to_text | Maps a sequence of tokens (string) in a single string. | [
"Maps",
"a",
"sequence",
"of",
"tokens",
"(string)",
"in",
"a",
"single",
"string."
] | def map_token_to_text(self, tokens: List[str]) -> str:
text = ''.join(tokens)
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors=self.errors)
return text | ['def', 'map_token_to_text(self,', 'tokens:', 'List[str])', '->', 'str:', 'text', '=', "''.join(tokens)", 'text', '=', 'bytearray([self.byte_decoder[c]', 'for', 'c', 'in', "text]).decode('utf-8',", 'errors=self.errors)', 'return', 'text'] | 924,591 |
asyml/texar | tokenizer_base.py | TokenizerBase.load | load | Instantiate a tokenizer from the vocabulary files or the saved tokenizer files. | [
"Instantiate",
"a",
"tokenizer",
"from",
"the",
"vocabulary",
"files",
"or",
"the",
"saved",
"tokenizer",
"files."
] | def load(cls, pretrained_model_path: str, configs: Optional[Dict]=None):
vocab_files = {}
for (file_id, file_name) in cls._VOCAB_FILE_NAMES.items():
full_file_name: Optional[str]
if os.path.isdir(pretrained_model_path):
full_file_name = os.path.join(pretrained_model_path, file_name)
... | ['def', 'load(cls,', 'pretrained_model_path:', 'str,', 'configs:', 'Optional[Dict]=None):', 'vocab_files', '=', '{}', 'for', '(file_id,', 'file_name)', 'in', 'cls._VOCAB_FILE_NAMES.items():', 'full_file_name:', 'Optional[str]', 'if', 'os.path.isdir(pretrained_model_path):', 'full_file_name', '=', 'os.path.join(pretrain... | 924,595 |
asyml/texar | xlnet_tokenizer.py | XLNetTokenizer.save_vocab | save_vocab | Save the sentencepiece vocabulary (copy original file) to a directory. | [
"Save",
"the",
"sentencepiece",
"vocabulary",
"(copy",
"original",
"file)",
"to",
"a",
"directory."
] | def save_vocab(self, save_dir: str) -> Tuple[str]:
if not os.path.isdir(save_dir):
raise ValueError('Vocabulary path ({}) should be a directory'.format(save_dir))
out_vocab_file = os.path.join(save_dir, self._VOCAB_FILE_NAMES['vocab_file'])
if os.path.abspath(self.vocab_file) != os.path.abspath(out_... | ['def', 'save_vocab(self,', 'save_dir:', 'str)', '->', 'Tuple[str]:', 'if', 'not', 'os.path.isdir(save_dir):', 'raise', "ValueError('Vocabulary", 'path', '({})', 'should', 'be', 'a', "directory'.format(save_dir))", 'out_vocab_file', '=', 'os.path.join(save_dir,', "self._VOCAB_FILE_NAMES['vocab_file'])", 'if', 'os.path.... | 924,611 |
asyml/texar | seq2seq_base.py | Seq2seqBase.get_loss | get_loss | Computes the training loss. | [
"Computes",
"the",
"training",
"loss."
] | def get_loss(self, decoder_results, features, labels):
return sequence_sparse_softmax_cross_entropy(labels=labels['target_text_ids'][:, 1:], logits=decoder_results['outputs'].logits, sequence_length=decoder_results['sequence_length']) | ['def', 'get_loss(self,', 'decoder_results,', 'features,', 'labels):', 'return', "sequence_sparse_softmax_cross_entropy(labels=labels['target_text_ids'][:,", '1:],', "logits=decoder_results['outputs'].logits,", "sequence_length=decoder_results['sequence_length'])"] | 924,641 |
asyml/texar | conv_classifiers.py | Conv1DClassifier.layer_names | layer_names | A list of uniquified layer names. | [
"A",
"list",
"of",
"uniquified",
"layer",
"names."
] | def layer_names(self):
return self._encoder.layer_names | ['def', 'layer_names(self):', 'return', 'self._encoder.layer_names'] | 924,652 |
asyml/texar | beam_search_decode.py | beam_search_decode | beam_search_decode | Performs beam search sampling decoding. | [
"Performs",
"beam",
"search",
"sampling",
"decoding."
] | def beam_search_decode(decoder_or_cell, embedding, start_tokens, end_token, beam_width, initial_state=None, tiled_initial_state=None, output_layer=None, length_penalty_weight=0.0, max_decoding_length=None, output_time_major=False, **kwargs):
if isinstance(decoder_or_cell, RNNDecoderBase):
cell = decoder_or_... | ['def', 'beam_search_decode(decoder_or_cell,', 'embedding,', 'start_tokens,', 'end_token,', 'beam_width,', 'initial_state=None,', 'tiled_initial_state=None,', 'output_layer=None,', 'length_penalty_weight=0.0,', 'max_decoding_length=None,', 'output_time_major=False,', '**kwargs):', 'if', 'isinstance(decoder_or_cell,', '... | 924,663 |
asyml/texar | rnn_decoder_helpers.py | get_helper | get_helper | Creates a Helper instance. | [
"Creates",
"a",
"Helper",
"instance."
] | def get_helper(helper_type, inputs=None, sequence_length=None, embedding=None, start_tokens=None, end_token=None, **kwargs):
module_paths = ['texar.tf.modules.decoders.rnn_decoder_helpers', 'texar.tf.modules.decoders.tf_helpers', 'texar.tf.custom']
class_kwargs = {'inputs': inputs, 'sequence_length': sequence_l... | ['def', 'get_helper(helper_type,', 'inputs=None,', 'sequence_length=None,', 'embedding=None,', 'start_tokens=None,', 'end_token=None,', '**kwargs):', 'module_paths', '=', "['texar.tf.modules.decoders.rnn_decoder_helpers',", "'texar.tf.modules.decoders.tf_helpers',", "'texar.tf.custom']", 'class_kwargs', '=', "{'inputs'... | 924,679 |
asyml/texar | rnn_decoder_helpers.py | TopKSampleEmbeddingHelper.sample | sample | Gets a sample for one step. | [
"Gets",
"a",
"sample",
"for",
"one",
"step."
] | def sample(self, time, outputs, state, name=None):
del time, state
if not isinstance(outputs, tf.Tensor):
raise TypeError('Expected outputs to be a single Tensor, got: %s' % type(outputs))
if self._softmax_temperature is None:
logits = outputs
else:
logits = outputs / self._softm... | ['def', 'sample(self,', 'time,', 'outputs,', 'state,', 'name=None):', 'del', 'time,', 'state', 'if', 'not', 'isinstance(outputs,', 'tf.Tensor):', 'raise', "TypeError('Expected", 'outputs', 'to', 'be', 'a', 'single', 'Tensor,', 'got:', "%s'", '%', 'type(outputs))', 'if', 'self._softmax_temperature', 'is', 'None:', 'logi... | 924,680 |
asyml/texar | tf_helpers.py | ScheduledEmbeddingTrainingHelper.next_inputs | next_inputs | Gets the outputs for next step. | [
"Gets",
"the",
"outputs",
"for",
"next",
"step."
] | def next_inputs(self, time, outputs, state, sample_ids, name=None):
with ops.name_scope(name, 'ScheduledEmbeddingTrainingHelperNextInputs', [time, outputs, state, sample_ids]):
(finished, base_next_inputs, state) = super(ScheduledEmbeddingTrainingHelper, self).next_inputs(time=time, outputs=outputs, state=s... | ['def', 'next_inputs(self,', 'time,', 'outputs,', 'state,', 'sample_ids,', 'name=None):', 'with', 'ops.name_scope(name,', "'ScheduledEmbeddingTrainingHelperNextInputs',", '[time,', 'outputs,', 'state,', 'sample_ids]):', '(finished,', 'base_next_inputs,', 'state)', '=', 'super(ScheduledEmbeddingTrainingHelper,', 'self).... | 924,690 |
asyml/texar | tf_helpers.py | ScheduledOutputTrainingHelper.next_inputs | next_inputs | Gets the next inputs for next step. | [
"Gets",
"the",
"next",
"inputs",
"for",
"next",
"step."
] | def next_inputs(self, time, outputs, state, sample_ids, name=None):
with ops.name_scope(name, 'ScheduledOutputTrainingHelperNextInputs', [time, outputs, state, sample_ids]):
(finished, base_next_inputs, state) = super(ScheduledOutputTrainingHelper, self).next_inputs(time=time, outputs=outputs, state=state, ... | ['def', 'next_inputs(self,', 'time,', 'outputs,', 'state,', 'sample_ids,', 'name=None):', 'with', 'ops.name_scope(name,', "'ScheduledOutputTrainingHelperNextInputs',", '[time,', 'outputs,', 'state,', 'sample_ids]):', '(finished,', 'base_next_inputs,', 'state)', '=', 'super(ScheduledOutputTrainingHelper,', 'self).next_i... | 924,692 |
asyml/texar | tf_helpers.py | GreedyEmbeddingHelper.next_inputs | next_inputs | Gets the inputs for next step. | [
"Gets",
"the",
"inputs",
"for",
"next",
"step."
] | def next_inputs(self, time, outputs, state, sample_ids, name=None):
finished = math_ops.equal(sample_ids, self._end_token)
all_finished = math_ops.reduce_all(finished)
if self._embedding_args_cnt == 1:
del time, outputs
next_inputs = control_flow_ops.cond(all_finished, lambda : self._start_i... | ['def', 'next_inputs(self,', 'time,', 'outputs,', 'state,', 'sample_ids,', 'name=None):', 'finished', '=', 'math_ops.equal(sample_ids,', 'self._end_token)', 'all_finished', '=', 'math_ops.reduce_all(finished)', 'if', 'self._embedding_args_cnt', '==', '1:', 'del', 'time,', 'outputs', 'next_inputs', '=', 'control_flow_op... | 924,694 |
asyml/texar | transformer_decoders.py | TransformerDecoder.step | step | Called per step of decoding. | [
"Called",
"per",
"step",
"of",
"decoding."
] | def step(self, time, inputs, state, name=None):
(outputs, state) = self._inputs_to_outputs(inputs, state)
sample_ids = self._helper.sample(time=time, outputs=outputs, state=state)
if self.context is not None:
_times = tf.ones([self.batch_size], dtype=tf.int32) * time
sample_ids = tf.where(se... | ['def', 'step(self,', 'time,', 'inputs,', 'state,', 'name=None):', '(outputs,', 'state)', '=', 'self._inputs_to_outputs(inputs,', 'state)', 'sample_ids', '=', 'self._helper.sample(time=time,', 'outputs=outputs,', 'state=state)', 'if', 'self.context', 'is', 'not', 'None:', '_times', '=', 'tf.ones([self.batch_size],', 'd... | 924,701 |
asyml/texar | memory_network.py | MemNetBase.memory_dim | memory_dim | The dimension of embedded memory and all vectors in hops. | [
"The",
"dimension",
"of",
"embedded",
"memory",
"and",
"all",
"vectors",
"in",
"hops."
] | def memory_dim(self):
return self._memory_dim | ['def', 'memory_dim(self):', 'return', 'self._memory_dim'] | 924,730 |
asyml/texar | average_recorder.py | AverageRecorder.avg | avg | Returns the (moving) average. | [
"Returns",
"the",
"(moving)",
"average."
] | def avg(self, id_or_name=None):
if self._recorders is None:
return 0.0
keys = id_or_name
if keys is None:
keys = list(self._recorders.keys())
if not isinstance(keys, (list, tuple)):
return self._recorders[keys].avg()
avg = {key: self._recorders[key].avg() for key in keys}
... | ['def', 'avg(self,', 'id_or_name=None):', 'if', 'self._recorders', 'is', 'None:', 'return', '0.0', 'keys', '=', 'id_or_name', 'if', 'keys', 'is', 'None:', 'keys', '=', 'list(self._recorders.keys())', 'if', 'not', 'isinstance(keys,', '(list,', 'tuple)):', 'return', 'self._recorders[keys].avg()', 'avg', '=', '{key:', 'se... | 924,763 |
asyml/texar | dtypes.py | is_callable | is_callable | Return `True` if :attr:`x` is callable. | [
"Return",
"`True`",
"if",
":attr:`x`",
"is",
"callable."
] | def is_callable(x):
try:
_is_callable = callable(x)
except BaseException:
_is_callable = hasattr(x, '__call__')
return _is_callable | ['def', 'is_callable(x):', 'try:', '_is_callable', '=', 'callable(x)', 'except', 'BaseException:', '_is_callable', '=', 'hasattr(x,', "'__call__')", 'return', '_is_callable'] | 924,769 |
asyml/texar | dtypes.py | compat_as_text | compat_as_text | Converts strings into `unicode` (Python 2) or `str` (Python 3). | [
"Converts",
"strings",
"into",
"`unicode`",
"(Python",
"2)",
"or",
"`str`",
"(Python",
"3)."
] | def compat_as_text(str_):
def _recur_convert(s):
if isinstance(s, (list, tuple, np.ndarray)):
s_ = [_recur_convert(si) for si in s]
return _maybe_list_to_array(s_, s)
else:
try:
return tf.compat.as_text(s)
except TypeError:
... | ['def', 'compat_as_text(str_):', 'def', '_recur_convert(s):', 'if', 'isinstance(s,', '(list,', 'tuple,', 'np.ndarray)):', 's_', '=', '[_recur_convert(si)', 'for', 'si', 'in', 's]', 'return', '_maybe_list_to_array(s_,', 's)', 'else:', 'try:', 'return', 'tf.compat.as_text(s)', 'except', 'TypeError:', 'return', 'tf.compat... | 924,773 |
asyml/texar | shapes.py | transpose_batch_time | transpose_batch_time | Transposes inputs between time-major and batch-major. | [
"Transposes",
"inputs",
"between",
"time-major",
"and",
"batch-major."
] | def transpose_batch_time(inputs):
flat_input = nest.flatten(inputs)
flat_input = [ops.convert_to_tensor(input_) for input_ in flat_input]
flat_input = [rnn._transpose_batch_time(input_) for input_ in flat_input]
return nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input) | ['def', 'transpose_batch_time(inputs):', 'flat_input', '=', 'nest.flatten(inputs)', 'flat_input', '=', '[ops.convert_to_tensor(input_)', 'for', 'input_', 'in', 'flat_input]', 'flat_input', '=', '[rnn._transpose_batch_time(input_)', 'for', 'input_', 'in', 'flat_input]', 'return', 'nest.pack_sequence_as(structure=inputs,... | 924,782 |
asyml/texar | utils.py | get_class | get_class | Returns the class based on class name. | [
"Returns",
"the",
"class",
"based",
"on",
"class",
"name."
] | def get_class(class_name, module_paths=None):
class_ = locate(class_name)
if class_ is None and module_paths is not None:
for module_path in module_paths:
class_ = locate('.'.join([module_path, class_name]))
if class_ is not None:
break
if class_ is None:
... | ['def', 'get_class(class_name,', 'module_paths=None):', 'class_', '=', 'locate(class_name)', 'if', 'class_', 'is', 'None', 'and', 'module_paths', 'is', 'not', 'None:', 'for', 'module_path', 'in', 'module_paths:', 'class_', '=', "locate('.'.join([module_path,", 'class_name]))', 'if', 'class_', 'is', 'not', 'None:', 'bre... | 924,804 |
asyml/texar | utils.py | map_ids_to_strs | map_ids_to_strs | Transforms `int` indexes to strings by mapping ids to tokens, concatenating tokens into sentences, and stripping special tokens, etc. | [
"Transforms",
"`int`",
"indexes",
"to",
"strings",
"by",
"mapping",
"ids",
"to",
"tokens,",
"concatenating",
"tokens",
"into",
"sentences,",
"and",
"stripping",
"special",
"tokens,",
"etc."
] | def map_ids_to_strs(ids, vocab, join=True, strip_pad='<PAD>', strip_bos='<BOS>', strip_eos='<EOS>', compat=True):
tokens = vocab.map_ids_to_tokens_py(ids)
if isinstance(ids, (list, tuple)):
tokens = tokens.tolist()
if compat:
tokens = compat_as_text(tokens)
str_ = str_join(tokens, compat... | ['def', 'map_ids_to_strs(ids,', 'vocab,', 'join=True,', "strip_pad='<PAD>',", "strip_bos='<BOS>',", "strip_eos='<EOS>',", 'compat=True):', 'tokens', '=', 'vocab.map_ids_to_tokens_py(ids)', 'if', 'isinstance(ids,', '(list,', 'tuple)):', 'tokens', '=', 'tokens.tolist()', 'if', 'compat:', 'tokens', '=', 'compat_as_text(to... | 924,824 |
asyml/texar-pytorch | data_utils.py | prepare_pickle_data | prepare_pickle_data | Prepare the `pickle` dataset. | [
"Prepare",
"the",
"`pickle`",
"dataset."
] | def prepare_pickle_data(data_dir: str, max_seq_length: int, tokenizer: tx.data.GPT2Tokenizer, output_dir: str, feature_types: Dict[str, Any]):
train_fn = os.path.join(data_dir, 'train.txt')
if os.path.isfile(train_fn):
print('Processing %s' % train_fn)
train_examples = read_raw_data(train_fn)
... | ['def', 'prepare_pickle_data(data_dir:', 'str,', 'max_seq_length:', 'int,', 'tokenizer:', 'tx.data.GPT2Tokenizer,', 'output_dir:', 'str,', 'feature_types:', 'Dict[str,', 'Any]):', 'train_fn', '=', 'os.path.join(data_dir,', "'train.txt')", 'if', 'os.path.isfile(train_fn):', "print('Processing", "%s'", '%', 'train_fn)', ... | 924,849 |
asyml/texar-pytorch | model_utils.py | warmup_lr_lambda | warmup_lr_lambda | Create a learning rate schedule with a linear warm-up stage and linear decay. | [
"Create",
"a",
"learning",
"rate",
"schedule",
"with",
"a",
"linear",
"warm-up",
"stage",
"and",
"linear",
"decay."
] | def warmup_lr_lambda(total_steps: int, warmup_steps: int=0, min_lr_ratio: float=0.0) -> Callable[[int], float]:
def polynomial_lr(decay_steps: int, step: int) -> float:
return (1.0 - min_lr_ratio) * (1 - step / decay_steps) + min_lr_ratio
if warmup_steps == 0:
return lambda step: polynomial_lr(... | ['def', 'warmup_lr_lambda(total_steps:', 'int,', 'warmup_steps:', 'int=0,', 'min_lr_ratio:', 'float=0.0)', '->', 'Callable[[int],', 'float]:', 'def', 'polynomial_lr(decay_steps:', 'int,', 'step:', 'int)', '->', 'float:', 'return', '(1.0', '-', 'min_lr_ratio)', '*', '(1', '-', 'step', '/', 'decay_steps)', '+', 'min_lr_r... | 924,864 |
asyml/texar-pytorch | layers_test.py | MergeLayerTest.test_empty_merge_layer | test_empty_merge_layer | Test the output of MergeLayer with empty layers. | [
"Test",
"the",
"output",
"of",
"MergeLayer",
"with",
"empty",
"layers."
] | def test_empty_merge_layer(self):
m_layer = layers.MergeLayer(layers=None)
input = torch.randn(32, 32, 10)
output = m_layer(input)
self.assertEqual(torch.all(torch.eq(output, input)), 1) | ['def', 'test_empty_merge_layer(self):', 'm_layer', '=', 'layers.MergeLayer(layers=None)', 'input', '=', 'torch.randn(32,', '32,', '10)', 'output', '=', 'm_layer(input)', 'self.assertEqual(torch.all(torch.eq(output,', 'input)),', '1)'] | 924,870 |
asyml/texar-pytorch | mono_text_data_test.py | MonoTextDataTest.test_default_setting | test_default_setting | Tests the logic of MonoTextData. | [
"Tests",
"the",
"logic",
"of",
"MonoTextData."
] | def test_default_setting(self):
self._run_and_test(self._hparams) | ['def', 'test_default_setting(self):', 'self._run_and_test(self._hparams)'] | 924,878 |
asyml/texar-pytorch | mono_text_data_test.py | MonoTextDataTest.test_shuffle | test_shuffle | Tests different shuffling strategies. | [
"Tests",
"different",
"shuffling",
"strategies."
] | def test_shuffle(self):
hparams = copy.deepcopy(self._hparams)
hparams.update({'shard_and_shuffle': True, 'shuffle_buffer_size': 1})
self._run_and_test(hparams) | ['def', 'test_shuffle(self):', 'hparams', '=', 'copy.deepcopy(self._hparams)', "hparams.update({'shard_and_shuffle':", 'True,', "'shuffle_buffer_size':", '1})', 'self._run_and_test(hparams)'] | 924,879 |
asyml/texar-pytorch | mono_text_data_test.py | MonoTextDataTest.test_length_discard | test_length_discard | Tests discard length seq. | [
"Tests",
"discard",
"length",
"seq."
] | def test_length_discard(self):
hparams = copy.deepcopy(self._hparams)
hparams['dataset'].update({'max_seq_length': 4, 'length_filter_mode': 'discard'})
self._run_and_test(hparams) | ['def', 'test_length_discard(self):', 'hparams', '=', 'copy.deepcopy(self._hparams)', "hparams['dataset'].update({'max_seq_length':", '4,', "'length_filter_mode':", "'discard'})", 'self._run_and_test(hparams)'] | 924,882 |
asyml/texar-pytorch | multi_aligned_data_test.py | MultiAlignedDataTest.test_unsupported_scalar_types | test_unsupported_scalar_types | Tests if exception is thrown for unsupported types. | [
"Tests",
"if",
"exception",
"is",
"thrown",
"for",
"unsupported",
"types."
] | def test_unsupported_scalar_types(self):
hparams = copy.copy(self._hparams)
hparams['datasets'][3].update({'data_type': 'XYZ'})
with self.assertRaises(ValueError):
self._run_and_test(hparams)
hparams = copy.copy(self._hparams)
hparams['datasets'][3].update({'data_type': 'str'})
with self... | ['def', 'test_unsupported_scalar_types(self):', 'hparams', '=', 'copy.copy(self._hparams)', "hparams['datasets'][3].update({'data_type':", "'XYZ'})", 'with', 'self.assertRaises(ValueError):', 'self._run_and_test(hparams)', 'hparams', '=', 'copy.copy(self._hparams)', "hparams['datasets'][3].update({'data_type':", "'str'... | 924,887 |
asyml/texar-pytorch | scalar_data_test.py | ScalarDataTest.test_default_setting | test_default_setting | Tests the logic of ScalarData. | [
"Tests",
"the",
"logic",
"of",
"ScalarData."
] | def test_default_setting(self):
self._run_and_test(self._int_hparams)
self._run_and_test(self._float_hparams)
self._run_and_test(self._bool_hparams) | ['def', 'test_default_setting(self):', 'self._run_and_test(self._int_hparams)', 'self._run_and_test(self._float_hparams)', 'self._run_and_test(self._bool_hparams)'] | 924,894 |
asyml/texar-pytorch | scalar_data_test.py | ScalarDataTest.test_unsupported_scalar_types | test_unsupported_scalar_types | Tests exception for unsupported scalar types. | [
"Tests",
"exception",
"for",
"unsupported",
"scalar",
"types."
] | def test_unsupported_scalar_types(self):
hparams = copy.copy(self._int_hparams)
hparams['dataset'].update({'data_type': 'XYZ'})
with self.assertRaises(ValueError):
self._run_and_test(hparams)
hparams = copy.copy(self._int_hparams)
hparams['dataset'].update({'data_type': 'str'})
with self... | ['def', 'test_unsupported_scalar_types(self):', 'hparams', '=', 'copy.copy(self._int_hparams)', "hparams['dataset'].update({'data_type':", "'XYZ'})", 'with', 'self.assertRaises(ValueError):', 'self._run_and_test(hparams)', 'hparams', '=', 'copy.copy(self._int_hparams)', "hparams['dataset'].update({'data_type':", "'str'... | 924,896 |
asyml/texar-pytorch | decoder_helpers_test.py | SamplerTest.test_top_p_sampler | test_top_p_sampler | Tests Top-P Sampler also known as Nucleus Sampler. | [
"Tests",
"Top-P",
"Sampler",
"also",
"known",
"as",
"Nucleus",
"Sampler."
] | def test_top_p_sampler(self):
sampler = TopPSampleEmbeddingHelper(start_tokens=self.start_token, end_token=self.end_token, p=0.6)
index = sampler.sample(time=0, outputs=self.logits)
assert index.item() in [0, 1, 2] | ['def', 'test_top_p_sampler(self):', 'sampler', '=', 'TopPSampleEmbeddingHelper(start_tokens=self.start_token,', 'end_token=self.end_token,', 'p=0.6)', 'index', '=', 'sampler.sample(time=0,', 'outputs=self.logits)', 'assert', 'index.item()', 'in', '[0,', '1,', '2]'] | 924,919 |
asyml/texar-pytorch | rnn_decoders_test.py | BasicRNNDecoderTest.test_decode_train_with_torch | test_decode_train_with_torch | Compares decoding results with PyTorch built-in decoder. | [
"Compares",
"decoding",
"results",
"with",
"PyTorch",
"built-in",
"decoder."
] | def test_decode_train_with_torch(self):
decoder = BasicRNNDecoder(token_embedder=self._embedder, input_size=self._emb_dim, vocab_size=self._vocab_size, hparams=self._hparams)
input_size = self._emb_dim
hidden_size = decoder.hparams.rnn_cell.kwargs.num_units
num_layers = decoder.hparams.rnn_cell.num_laye... | ['def', 'test_decode_train_with_torch(self):', 'decoder', '=', 'BasicRNNDecoder(token_embedder=self._embedder,', 'input_size=self._emb_dim,', 'vocab_size=self._vocab_size,', 'hparams=self._hparams)', 'input_size', '=', 'self._emb_dim', 'hidden_size', '=', 'decoder.hparams.rnn_cell.kwargs.num_units', 'num_layers', '=', ... | 924,923 |
asyml/texar-pytorch | embedders_test.py | EmbedderTest.test_word_embedder_trainable | test_word_embedder_trainable | Tests freezing the embedding parameters. | [
"Tests",
"freezing",
"the",
"embedding",
"parameters."
] | def test_word_embedder_trainable(self):
init_value = np.expand_dims(np.arange(5), 1)
embedder = WordEmbedder(init_value=init_value, hparams={'trainable': False})
self.assertEqual(len(embedder.trainable_variables), 0)
embedder = WordEmbedder(init_value=init_value)
self.assertEqual(len(embedder.traina... | ['def', 'test_word_embedder_trainable(self):', 'init_value', '=', 'np.expand_dims(np.arange(5),', '1)', 'embedder', '=', 'WordEmbedder(init_value=init_value,', "hparams={'trainable':", 'False})', 'self.assertEqual(len(embedder.trainable_variables),', '0)', 'embedder', '=', 'WordEmbedder(init_value=init_value)', 'self.a... | 924,932 |
asyml/texar-pytorch | t5_encoder_decoder_test.py | T5EncoderDecoderTest.test_hparams | test_hparams | Tests the priority of the architecture. | [
"Tests",
"the",
"priority",
"of",
"the",
"architecture."
] | def test_hparams(self):
hparams = {'pretrained_model_name': 'T5-Small'}
t5 = T5EncoderDecoder(pretrained_model_name='T5-Base', hparams=hparams)
self.assertEqual(t5.hparams.encoder.num_blocks, 12)
(_, _) = t5(self.inputs)
hparams = {'pretrained_model_name': 'T5-Small', 'encoder': {'num_blocks': 16}}
... | ['def', 'test_hparams(self):', 'hparams', '=', "{'pretrained_model_name':", "'T5-Small'}", 't5', '=', "T5EncoderDecoder(pretrained_model_name='T5-Base',", 'hparams=hparams)', 'self.assertEqual(t5.hparams.encoder.num_blocks,', '12)', '(_,', '_)', '=', 't5(self.inputs)', 'hparams', '=', "{'pretrained_model_name':", "'T5-... | 924,949 |
asyml/texar-pytorch | module_base.py | ModuleBase.output_size | output_size | The feature size of :meth:`forward` output tensor(s), usually it is equal to the last dimension value of the output tensor size. | [
"The",
"feature",
"size",
"of",
":meth:`forward`",
"output",
"tensor(s),",
"usually",
"it",
"is",
"equal",
"to",
"the",
"last",
"dimension",
"value",
"of",
"the",
"output",
"tensor",
"size."
] | def output_size(self):
raise NotImplementedError | ['def', 'output_size(self):', 'raise', 'NotImplementedError'] | 924,959 |
asyml/texar-pytorch | attention_mechanism.py | compute_attention | compute_attention | Computes the attention and alignments for a given :attr:`attention_mechanism`. | [
"Computes",
"the",
"attention",
"and",
"alignments",
"for",
"a",
"given",
":attr:`attention_mechanism`."
] | def compute_attention(attention_mechanism: AttentionMechanism, cell_output: torch.Tensor, attention_state: torch.Tensor, memory: torch.Tensor, attention_layer: Optional[nn.Module], memory_sequence_length: Optional[torch.LongTensor]=None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
(alignments, next_attentio... | ['def', 'compute_attention(attention_mechanism:', 'AttentionMechanism,', 'cell_output:', 'torch.Tensor,', 'attention_state:', 'torch.Tensor,', 'memory:', 'torch.Tensor,', 'attention_layer:', 'Optional[nn.Module],', 'memory_sequence_length:', 'Optional[torch.LongTensor]=None)', '->', 'Tuple[torch.Tensor,', 'torch.Tensor... | 924,961 |
asyml/texar-pytorch | attention_mechanism.py | AttentionMechanism.memory_layer | memory_layer | The layer used to transform the attention memory. | [
"The",
"layer",
"used",
"to",
"transform",
"the",
"attention",
"memory."
] | def memory_layer(self) -> nn.Module:
return self._memory_layer | ['def', 'memory_layer(self)', '->', 'nn.Module:', 'return', 'self._memory_layer'] | 924,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.