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 |
|---|---|---|---|---|---|---|---|---|
facebookresearch/fvcore | test_common.py | TestCfgNode.test_merge_from_list | test_merge_from_list | Test merge_from_list function provided in the class. | [
"Test",
"merge_from_list",
"function",
"provided",
"in",
"the",
"class."
] | def test_merge_from_list(self) -> None:
cfg = TestCfgNode.gen_default_cfg()
cfg.merge_from_list(['KEY1', 'list1', 'KEY2', 'list2'])
self.assertEqual(cfg.KEY1, 'list1')
self.assertEqual(cfg.KEY2, 'list2') | ['def', 'test_merge_from_list(self)', '->', 'None:', 'cfg', '=', 'TestCfgNode.gen_default_cfg()', "cfg.merge_from_list(['KEY1',", "'list1',", "'KEY2',", "'list2'])", 'self.assertEqual(cfg.KEY1,', "'list1')", 'self.assertEqual(cfg.KEY2,', "'list2')"] | 565,960 |
cheng052/BRNet | centerpoint_head.py | SeparateHead.forward | forward | Forward function for SepHead. | [
"Forward",
"function",
"for",
"SepHead."
] | def forward(self, x):
ret_dict = dict()
for head in self.heads:
ret_dict[head] = self.__getattr__(head)(x)
return ret_dict | ['def', 'forward(self,', 'x):', 'ret_dict', '=', 'dict()', 'for', 'head', 'in', 'self.heads:', 'ret_dict[head]', '=', 'self.__getattr__(head)(x)', 'return', 'ret_dict'] | 409,867 |
MycroftAI/mycroft-core | mycroft_skill.py | MycroftSkill.load_regex_files | load_regex_files | Load regex files found under the skill directory. | [
"Load",
"regex",
"files",
"found",
"under",
"the",
"skill",
"directory."
] | def load_regex_files(self, root_directory):
regexes = []
regex_dir = join(root_directory, 'regex', self.lang)
locale_dir = join(root_directory, 'locale', self.lang)
if exists(regex_dir):
regexes = load_regex(regex_dir, self.skill_id)
elif exists(locale_dir):
regexes = load_regex(loca... | ['def', 'load_regex_files(self,', 'root_directory):', 'regexes', '=', '[]', 'regex_dir', '=', 'join(root_directory,', "'regex',", 'self.lang)', 'locale_dir', '=', 'join(root_directory,', "'locale',", 'self.lang)', 'if', 'exists(regex_dir):', 'regexes', '=', 'load_regex(regex_dir,', 'self.skill_id)', 'elif', 'exists(loc... | 290,639 |
bachiraoun/fullrmc | GroupSelector.py | RecursiveGroupSelector.selector | selector | The wrapped selector instance. | [
"The",
"wrapped",
"selector",
"instance."
] | def selector(self):
return self.__selector | ['def', 'selector(self):', 'return', 'self.__selector'] | 213,849 |
asyml/texar | mono_text_data.py | MonoTextData.dataset | dataset | The dataset, an instance of :tf_main:`TF dataset <data/TextLineDataset>`. | [
"The",
"dataset,",
"an",
"instance",
"of",
":tf_main:`TF",
"dataset",
"<data/TextLineDataset>`."
] | def dataset(self):
return self._dataset | ['def', 'dataset(self):', 'return', 'self._dataset'] | 924,536 |
PacktPublishing/Hands-On-Artificial--for-Banking | construction.py | to_arrays | to_arrays | Return list of arrays, columns. | [
"Return",
"list",
"of",
"arrays,",
"columns."
] | def to_arrays(data, columns, coerce_float: bool=False, dtype: Optional[DtypeObj]=None):
if isinstance(data, ABCDataFrame):
if columns is not None:
arrays = [data._ixs(i, axis=1).values for (i, col) in enumerate(data.columns) if col in columns]
else:
columns = data.columns
... | ['def', 'to_arrays(data,', 'columns,', 'coerce_float:', 'bool=False,', 'dtype:', 'Optional[DtypeObj]=None):', 'if', 'isinstance(data,', 'ABCDataFrame):', 'if', 'columns', 'is', 'not', 'None:', 'arrays', '=', '[data._ixs(i,', 'axis=1).values', 'for', '(i,', 'col)', 'in', 'enumerate(data.columns)', 'if', 'col', 'in', 'co... | 236,783 |
tobegit3hub/deep_image_model | export.py | logistic_regression_signature_fn | logistic_regression_signature_fn | Creates logistic regression signature from given examples and predictions. | [
"Creates",
"logistic",
"regression",
"signature",
"from",
"given",
"examples",
"and",
"predictions."
] | def logistic_regression_signature_fn(examples, unused_features, predictions):
if examples is None:
raise ValueError('examples cannot be None when using this signature fn.')
if isinstance(predictions, dict):
predictions_tensor = predictions['probabilities']
else:
predictions_tensor = ... | ['def', 'logistic_regression_signature_fn(examples,', 'unused_features,', 'predictions):', 'if', 'examples', 'is', 'None:', 'raise', "ValueError('examples", 'cannot', 'be', 'None', 'when', 'using', 'this', 'signature', "fn.')", 'if', 'isinstance(predictions,', 'dict):', 'predictions_tensor', '=', "predictions['probabil... | 181,877 |
nicknochnack/RealTimeSignLanguageTFJS | model.py | DetectionModel.groundtruth_lists | groundtruth_lists | Access list of groundtruth tensors. | [
"Access",
"list",
"of",
"groundtruth",
"tensors."
] | def groundtruth_lists(self, field):
if field not in self._groundtruth_lists:
raise RuntimeError('Groundtruth tensor {} has not been provided'.format(field))
return self._groundtruth_lists[field] | ['def', 'groundtruth_lists(self,', 'field):', 'if', 'field', 'not', 'in', 'self._groundtruth_lists:', 'raise', "RuntimeError('Groundtruth", 'tensor', '{}', 'has', 'not', 'been', "provided'.format(field))", 'return', 'self._groundtruth_lists[field]'] | 852,188 |
suarez12138/AI-Reversi_IMP_TextDichotomy | _layoutbox.py | seq_id | seq_id | Generate a short sequential id for layoutbox objects. | [
"Generate",
"a",
"short",
"sequential",
"id",
"for",
"layoutbox",
"objects."
] | def seq_id():
return '%06d' % next(_layoutboxobjnum) | ['def', 'seq_id():', 'return', "'%06d'", '%', 'next(_layoutboxobjnum)'] | 96,960 |
yoonc5536/computer_vision | visualization_utils.py | draw_keypoints_on_image_array | draw_keypoints_on_image_array | Draws keypoints on an image (numpy array). | [
"Draws",
"keypoints",
"on",
"an",
"image",
"(numpy",
"array)."
] | def draw_keypoints_on_image_array(image, keypoints, color='red', radius=2, use_normalized_coordinates=True):
image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
draw_keypoints_on_image(image_pil, keypoints, color, radius, use_normalized_coordinates)
np.copyto(image, np.array(image_pil)) | ['def', 'draw_keypoints_on_image_array(image,', 'keypoints,', "color='red',", 'radius=2,', 'use_normalized_coordinates=True):', 'image_pil', '=', "Image.fromarray(np.uint8(image)).convert('RGB')", 'draw_keypoints_on_image(image_pil,', 'keypoints,', 'color,', 'radius,', 'use_normalized_coordinates)', 'np.copyto(image,',... | 514,072 |
caiiiac/Machine-Learning-with-Python | base.py | spmatrix.maximum | maximum | Element-wise maximum between this and another matrix. | [
"Element-wise",
"maximum",
"between",
"this",
"and",
"another",
"matrix."
] | def maximum(self, other):
return self.tocsr().maximum(other) | ['def', 'maximum(self,', 'other):', 'return', 'self.tocsr().maximum(other)'] | 719,888 |
chribsen/simple-machine-learning-examples | data.py | RobustScaler.transform | transform | Center and scale the data Parameters ---------- X : array-like The data used to scale along the specified axis. | [
"Center",
"and",
"scale",
"the",
"data",
"Parameters",
"----------",
"X",
":",
"array-like",
"The",
"data",
"used",
"to",
"scale",
"along",
"the",
"specified",
"axis."
] | def transform(self, X, y=None):
if self.with_centering:
check_is_fitted(self, 'center_')
if self.with_scaling:
check_is_fitted(self, 'scale_')
X = self._check_array(X, self.copy)
if X.ndim == 1:
warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning)
if sparse.issparse(X):
... | ['def', 'transform(self,', 'X,', 'y=None):', 'if', 'self.with_centering:', 'check_is_fitted(self,', "'center_')", 'if', 'self.with_scaling:', 'check_is_fitted(self,', "'scale_')", 'X', '=', 'self._check_array(X,', 'self.copy)', 'if', 'X.ndim', '==', '1:', 'warnings.warn(DEPRECATION_MSG_1D,', 'DeprecationWarning)', 'if'... | 882,905 |
qm19/A-Weakly-Supervised-Learning-based-Oversampling-Framework-for-Imbalanced-Classification | utils.py | recall_at_precision | recall_at_precision | Compute recall at precision. | [
"Compute",
"recall",
"at",
"precision."
] | def recall_at_precision(label, y_pred, precision):
(prec, reca, _) = precision_recall_curve(label, y_pred)
idx = np.searchsorted(prec, precision, 'right')
return reca[idx] | ['def', 'recall_at_precision(label,', 'y_pred,', 'precision):', '(prec,', 'reca,', '_)', '=', 'precision_recall_curve(label,', 'y_pred)', 'idx', '=', 'np.searchsorted(prec,', 'precision,', "'right')", 'return', 'reca[idx]'] | 5,135 |
johnnyp2587/transfer-learning | flipGradientTF.py | reverse_gradient | reverse_gradient | Flips the sign of the incoming gradient during training. | [
"Flips",
"the",
"sign",
"of",
"the",
"incoming",
"gradient",
"during",
"training."
] | def reverse_gradient(X, hp_lambda):
try:
reverse_gradient.num_calls += 1
except AttributeError:
reverse_gradient.num_calls = 1
grad_name = 'GradientReversal%d' % reverse_gradient.num_calls
@tf.RegisterGradient(grad_name)
def _flip_gradients(op, grad):
return [tf.negative(gra... | ['def', 'reverse_gradient(X,', 'hp_lambda):', 'try:', 'reverse_gradient.num_calls', '+=', '1', 'except', 'AttributeError:', 'reverse_gradient.num_calls', '=', '1', 'grad_name', '=', "'GradientReversal%d'", '%', 'reverse_gradient.num_calls', '@tf.RegisterGradient(grad_name)', 'def', '_flip_gradients(op,', 'grad):', 'ret... | 928,864 |
sek788432/Waymo-2D-Object-Detection | data_download.py | shuffle_records | shuffle_records | Shuffle records in a single file. | [
"Shuffle",
"records",
"in",
"a",
"single",
"file."
] | def shuffle_records(fname):
logging.info('Shuffling records in file %s', fname)
tmp_fname = six.ensure_str(fname) + '.unshuffled'
tf.gfile.Rename(fname, tmp_fname)
reader = tf.io.tf_record_iterator(tmp_fname)
records = []
for record in reader:
records.append(record)
if len(record... | ['def', 'shuffle_records(fname):', "logging.info('Shuffling", 'records', 'in', 'file', "%s',", 'fname)', 'tmp_fname', '=', 'six.ensure_str(fname)', '+', "'.unshuffled'", 'tf.gfile.Rename(fname,', 'tmp_fname)', 'reader', '=', 'tf.io.tf_record_iterator(tmp_fname)', 'records', '=', '[]', 'for', 'record', 'in', 'reader:', ... | 972,840 |
Ruturaj123/Flowchart-Detection | dp_mnist.py | Eval | Eval | Evaluate MNIST for a number of steps. | [
"Evaluate",
"MNIST",
"for",
"a",
"number",
"of",
"steps."
] | def Eval(mnist_data_file, network_parameters, num_testing_images, randomize, load_path, save_mistakes=False):
batch_size = 100
with tf.Graph().as_default(), tf.Session() as sess:
(images, labels) = MnistInput(mnist_data_file, batch_size, randomize)
(logits, _, _) = utils.BuildNetwork(images, net... | ['def', 'Eval(mnist_data_file,', 'network_parameters,', 'num_testing_images,', 'randomize,', 'load_path,', 'save_mistakes=False):', 'batch_size', '=', '100', 'with', 'tf.Graph().as_default(),', 'tf.Session()', 'as', 'sess:', '(images,', 'labels)', '=', 'MnistInput(mnist_data_file,', 'batch_size,', 'randomize)', '(logit... | 585,543 |
Ruturaj123/Flowchart-Detection | gbdt_batch_test.py | GbdtTest.testTrainFnNonChiefNoBiasCentering | testTrainFnNonChiefNoBiasCentering | Tests the train function running on worker without bias centering. | [
"Tests",
"the",
"train",
"function",
"running",
"on",
"worker",
"without",
"bias",
"centering."
] | def testTrainFnNonChiefNoBiasCentering(self):
with self.test_session():
ensemble_handle = model_ops.tree_ensemble_variable(stamp_token=0, tree_ensemble_config='', name='tree_ensemble')
learner_config = learner_pb2.LearnerConfig()
learner_config.learning_rate_tuner.fixed.learning_rate = 0.1
... | ['def', 'testTrainFnNonChiefNoBiasCentering(self):', 'with', 'self.test_session():', 'ensemble_handle', '=', 'model_ops.tree_ensemble_variable(stamp_token=0,', "tree_ensemble_config='',", "name='tree_ensemble')", 'learner_config', '=', 'learner_pb2.LearnerConfig()', 'learner_config.learning_rate_tuner.fixed.learning_ra... | 586,901 |
tobegit3hub/deep_image_model | classifier.py | Classifier.predict_proba | predict_proba | Returns predicted probabilty distributions for given features. | [
"Returns",
"predicted",
"probabilty",
"distributions",
"for",
"given",
"features."
] | def predict_proba(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
predictions = super(Classifier, self).predict(x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable, outputs=[Classifier.PROBABILITY_OUTPUT])
if as_iterable:
return (p[Classifier.PROBABILITY_OUTPUT] for p... | ['def', 'predict_proba(self,', 'x=None,', 'input_fn=None,', 'batch_size=None,', 'as_iterable=True):', 'predictions', '=', 'super(Classifier,', 'self).predict(x=x,', 'input_fn=input_fn,', 'batch_size=batch_size,', 'as_iterable=as_iterable,', 'outputs=[Classifier.PROBABILITY_OUTPUT])', 'if', 'as_iterable:', 'return', '(p... | 181,637 |
bnpy/bnpy | ParallelUtil.py | numpyToSharedMemArray | numpyToSharedMemArray | Get copy of X accessible as shared memory Returns -------- Xsh : RawArray (same size as X) Uses separate storage than original array X. | [
"Get",
"copy",
"of",
"X",
"accessible",
"as",
"shared",
"memory",
"Returns",
"--------",
"Xsh",
":",
"RawArray",
"(same",
"size",
"as",
"X)",
"Uses",
"separate",
"storage",
"than",
"original",
"array",
"X."
] | def numpyToSharedMemArray(X):
Xtmp = np.ctypeslib.as_ctypes(X)
Xsh = multiprocessing.sharedctypes.RawArray(Xtmp._type_, Xtmp)
return Xsh | ['def', 'numpyToSharedMemArray(X):', 'Xtmp', '=', 'np.ctypeslib.as_ctypes(X)', 'Xsh', '=', 'multiprocessing.sharedctypes.RawArray(Xtmp._type_,', 'Xtmp)', 'return', 'Xsh'] | 465,203 |
astroML/astroML | settings.py | setup_text_plots | setup_text_plots | This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. | [
"This",
"function",
"adjusts",
"matplotlib",
"settings",
"so",
"that",
"all",
"figures",
"in",
"the",
"textbook",
"have",
"a",
"uniform",
"format",
"and",
"look."
] | def setup_text_plots(fontsize=8, usetex=True):
import matplotlib
from packaging.version import Version
matplotlib.rc('legend', fontsize=fontsize, handlelength=3)
matplotlib.rc('axes', titlesize=fontsize)
matplotlib.rc('axes', labelsize=fontsize)
matplotlib.rc('xtick', labelsize=fontsize)
mat... | ['def', 'setup_text_plots(fontsize=8,', 'usetex=True):', 'import', 'matplotlib', 'from', 'packaging.version', 'import', 'Version', "matplotlib.rc('legend',", 'fontsize=fontsize,', 'handlelength=3)', "matplotlib.rc('axes',", 'titlesize=fontsize)', "matplotlib.rc('axes',", 'labelsize=fontsize)', "matplotlib.rc('xtick',",... | 402,608 |
ballaneypranav/cs50ai | minesweeper.py | Sentence.mark_safe | mark_safe | Updates internal knowledge representation given the fact that a cell is known to be safe. | [
"Updates",
"internal",
"knowledge",
"representation",
"given",
"the",
"fact",
"that",
"a",
"cell",
"is",
"known",
"to",
"be",
"safe."
] | def mark_safe(self, cell):
if cell in self.cells:
self.cells.remove(cell) | ['def', 'mark_safe(self,', 'cell):', 'if', 'cell', 'in', 'self.cells:', 'self.cells.remove(cell)'] | 192,468 |
PaddlePaddle/PARL | train.py | Learner.create_actors | create_actors | Connect to the cluster and start sampling of the remote actor. | [
"Connect",
"to",
"the",
"cluster",
"and",
"start",
"sampling",
"of",
"the",
"remote",
"actor."
] | def create_actors(self):
parl.connect(self.config['master_address'])
logger.info('Waiting for {} remote actors to connect.'.format(self.config['actor_num']))
for i in six.moves.range(self.config['actor_num']):
params_queue = queue.Queue()
self.params_queues.append(params_queue)
self.... | ['def', 'create_actors(self):', "parl.connect(self.config['master_address'])", "logger.info('Waiting", 'for', '{}', 'remote', 'actors', 'to', "connect.'.format(self.config['actor_num']))", 'for', 'i', 'in', "six.moves.range(self.config['actor_num']):", 'params_queue', '=', 'queue.Queue()', 'self.params_queues.append(pa... | 277,580 |
zhoroh/ObjectDetection | box_utils.py | encode_multi | encode_multi | Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. | [
"Encode",
"the",
"variances",
"from",
"the",
"priorbox",
"layers",
"into",
"the",
"ground",
"truth",
"boxes",
"we",
"have",
"matched",
"(based",
"on",
"jaccard",
"overlap)",
"with",
"the",
"prior",
"boxes."
] | def encode_multi(matched, priors, offsets, variances):
g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2] - offsets[:, :2]
g_cxcy.div_(variances[0] * offsets[:, 2:])
g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
g_wh = torch.log(g_wh) / variances[1]
return torch.cat([g_cxcy, g... | ['def', 'encode_multi(matched,', 'priors,', 'offsets,', 'variances):', 'g_cxcy', '=', '(matched[:,', ':2]', '+', 'matched[:,', '2:])', '/', '2', '-', 'priors[:,', ':2]', '-', 'offsets[:,', ':2]', 'g_cxcy.div_(variances[0]', '*', 'offsets[:,', '2:])', 'g_wh', '=', '(matched[:,', '2:]', '-', 'matched[:,', ':2])', '/', 'p... | 742,329 |
muhanzhang/D-VAE | opt.py | local_mul_to_sqr | local_mul_to_sqr | x*x -> sqr(x) This is faster on the GPU when memory fetching is a big part of the computation time. | [
"x*x",
"->",
"sqr(x)",
"This",
"is",
"faster",
"on",
"the",
"GPU",
"when",
"memory",
"fetching",
"is",
"a",
"big",
"part",
"of",
"the",
"computation",
"time."
] | def local_mul_to_sqr(node):
if node.op == T.mul:
if len(node.inputs) == 2:
if node.inputs[0] is node.inputs[1]:
return [T.sqr(node.inputs[0])] | ['def', 'local_mul_to_sqr(node):', 'if', 'node.op', '==', 'T.mul:', 'if', 'len(node.inputs)', '==', '2:', 'if', 'node.inputs[0]', 'is', 'node.inputs[1]:', 'return', '[T.sqr(node.inputs[0])]'] | 525,572 |
weimin17/Object-Detection_HelmetDetection | graph_builder_test.py | GraphBuilderTest.testTrainingWithAdamAndAveraging | testTrainingWithAdamAndAveraging | Adds code coverage for ADAM and the use of moving averaging. | [
"Adds",
"code",
"coverage",
"for",
"ADAM",
"and",
"the",
"use",
"of",
"moving",
"averaging."
] | def testTrainingWithAdamAndAveraging(self):
self.RunTraining(self.MakeHyperparams(learning_method='adam', use_moving_average=True)) | ['def', 'testTrainingWithAdamAndAveraging(self):', "self.RunTraining(self.MakeHyperparams(learning_method='adam',", 'use_moving_average=True))'] | 753,310 |
kakaobrain/pororo | BrainLaBERTa.py | RobertaLabelModel.register_classification_head | register_classification_head | Register a classification head. | [
"Register",
"a",
"classification",
"head."
] | def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs):
if name in self.classification_heads:
prev_num_classes = self.classification_heads[name].out_proj.out_features
prev_inner_dim = self.classification_heads[name].dense.out_features
if num_classes != prev_... | ['def', 'register_classification_head(self,', 'name,', 'num_classes=None,', 'inner_dim=None,', '**kwargs):', 'if', 'name', 'in', 'self.classification_heads:', 'prev_num_classes', '=', 'self.classification_heads[name].out_proj.out_features', 'prev_inner_dim', '=', 'self.classification_heads[name].dense.out_features', 'i... | 782,407 |
rifqind/Agent-Programs-3KS1 | compiler.py | compile | compile | Compile grammar (given as regex string), returning a `CompiledGrammar` instance. | [
"Compile",
"grammar",
"(given",
"as",
"regex",
"string),",
"returning",
"a",
"`CompiledGrammar`",
"instance."
] | def compile(expression, escape_funcs=None, unescape_funcs=None):
return _compile_from_parse_tree(parse_regex(tokenize_regex(expression)), escape_funcs=escape_funcs, unescape_funcs=unescape_funcs) | ['def', 'compile(expression,', 'escape_funcs=None,', 'unescape_funcs=None):', 'return', '_compile_from_parse_tree(parse_regex(tokenize_regex(expression)),', 'escape_funcs=escape_funcs,', 'unescape_funcs=unescape_funcs)'] | 45,066 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | beam_reader_ops_test.py | ParsingReaderOpsTest.testParseMomentum | testParseMomentum | Ensures that Momentum training can be done using the gradients. | [
"Ensures",
"that",
"Momentum",
"training",
"can",
"be",
"done",
"using",
"the",
"gradients."
] | def testParseMomentum(self):
self.Train()
self.Train(model_cost='perceptron_loss')
self.Train(model_cost='perceptron_loss', only_train='softmax_weight,softmax_bias', softmax_init=0)
self.Train(only_train='softmax_weight,softmax_bias', softmax_init=0) | ['def', 'testParseMomentum(self):', 'self.Train()', "self.Train(model_cost='perceptron_loss')", "self.Train(model_cost='perceptron_loss',", "only_train='softmax_weight,softmax_bias',", 'softmax_init=0)', "self.Train(only_train='softmax_weight,softmax_bias',", 'softmax_init=0)'] | 111,701 |
tinazhouhui/computer_vision | cpp_lint.py | CheckEmptyBlockBody | CheckEmptyBlockBody | Look for empty loop/conditional body with only a single semicolon. | [
"Look",
"for",
"empty",
"loop/conditional",
"body",
"with",
"only",
"a",
"single",
"semicolon."
] | def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
matched = Match('\\s*(for|while|if)\\s*\\(', line)
if matched:
(end_line, end_linenum, end_pos) = CloseExpression(clean_lines, linenum, line.find('('))
if end_pos >= 0 and Match(';', end_line[e... | ['def', 'CheckEmptyBlockBody(filename,', 'clean_lines,', 'linenum,', 'error):', 'line', '=', 'clean_lines.elided[linenum]', 'matched', '=', "Match('\\\\s*(for|while|if)\\\\s*\\\\(',", 'line)', 'if', 'matched:', '(end_line,', 'end_linenum,', 'end_pos)', '=', 'CloseExpression(clean_lines,', 'linenum,', "line.find('('))",... | 473,065 |
clvrai/spirl | replay_buffer.py | RolloutStorage.rollout_stats | rollout_stats | Returns AttrDict of average statistics over the rollouts. | [
"Returns",
"AttrDict",
"of",
"average",
"statistics",
"over",
"the",
"rollouts."
] | def rollout_stats(self):
assert self.rollouts
stats = RecursiveAverageMeter()
for rollout in self.rollouts:
stats.update(AttrDict(avg_reward=np.stack(rollout.reward).sum()))
return stats.avg | ['def', 'rollout_stats(self):', 'assert', 'self.rollouts', 'stats', '=', 'RecursiveAverageMeter()', 'for', 'rollout', 'in', 'self.rollouts:', 'stats.update(AttrDict(avg_reward=np.stack(rollout.reward).sum()))', 'return', 'stats.avg'] | 897,024 |
ecobost/cnn4brca | train.py | new_example | new_example | Creates an infinite queue of filenames, augments and preprocess the image and returns a new example: (image, label) pair. | [
"Creates",
"an",
"infinite",
"queue",
"of",
"filenames,",
"augments",
"and",
"preprocess",
"the",
"image",
"and",
"returns",
"a",
"new",
"example:",
"(image,",
"label)",
"pair."
] | def new_example(image_filenames, label_filenames, data_dir):
with tf.name_scope('filename_queue'):
image_filenames = tf.convert_to_tensor(image_filenames)
label_filenames = tf.convert_to_tensor(label_filenames)
(image_filename, label_filename) = tf.train.slice_input_producer([image_filenames... | ['def', 'new_example(image_filenames,', 'label_filenames,', 'data_dir):', 'with', "tf.name_scope('filename_queue'):", 'image_filenames', '=', 'tf.convert_to_tensor(image_filenames)', 'label_filenames', '=', 'tf.convert_to_tensor(label_filenames)', '(image_filename,', 'label_filename)', '=', 'tf.train.slice_input_produc... | 123,890 |
ashwanitanwar/nmt-transfer-learning-xlm-r | transformer.py | TransformerModel.get_normalized_probs | get_normalized_probs | Get normalized probabilities (or log probs) from a net's output. | [
"Get",
"normalized",
"probabilities",
"(or",
"log",
"probs)",
"from",
"a",
"net's",
"output."
] | def get_normalized_probs(self, net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], log_probs: bool, sample: Optional[Dict[str, Tensor]]=None):
return self.get_normalized_probs_scriptable(net_output, log_probs, sample) | ['def', 'get_normalized_probs(self,', 'net_output:', 'Tuple[Tensor,', 'Optional[Dict[str,', 'List[Optional[Tensor]]]]],', 'log_probs:', 'bool,', 'sample:', 'Optional[Dict[str,', 'Tensor]]=None):', 'return', 'self.get_normalized_probs_scriptable(net_output,', 'log_probs,', 'sample)'] | 733,427 |
jimtin/Stock_Comparison | inprocess.py | QtInProcessChannel.stop | stop | Reimplemented to emit signal. | [
"Reimplemented",
"to",
"emit",
"signal."
] | def stop(self):
super(QtInProcessChannel, self).stop()
self.stopped.emit() | ['def', 'stop(self):', 'super(QtInProcessChannel,', 'self).stop()', 'self.stopped.emit()'] | 358,573 |
Katja-M/Python_NaturalLanguageProcessing | spearman.py | ranks_from_sequence | ranks_from_sequence | Given a sequence, yields each element with an increasing rank, suitable for use as an argument to ``spearman_correlation``. | [
"Given",
"a",
"sequence,",
"yields",
"each",
"element",
"with",
"an",
"increasing",
"rank,",
"suitable",
"for",
"use",
"as",
"an",
"argument",
"to",
"``spearman_correlation``."
] | def ranks_from_sequence(seq):
return ((k, i) for (i, k) in enumerate(seq)) | ['def', 'ranks_from_sequence(seq):', 'return', '((k,', 'i)', 'for', '(i,', 'k)', 'in', 'enumerate(seq))'] | 866,602 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | RouletteWheel.is_empty | is_empty | Returns whether there is anything in the roulette wheel. | [
"Returns",
"whether",
"there",
"is",
"anything",
"in",
"the",
"roulette",
"wheel."
] | def is_empty(self):
return not self.partial_sums | ['def', 'is_empty(self):', 'return', 'not', 'self.partial_sums'] | 52,555 |
tinazhouhui/computer_vision | sast_postprocess.py | SASTPostProcess.estimate_sample_pts_num | estimate_sample_pts_num | Estimate sample points number. | [
"Estimate",
"sample",
"points",
"number."
] | def estimate_sample_pts_num(self, quad, xy_text):
eh = (np.linalg.norm(quad[0] - quad[3]) + np.linalg.norm(quad[1] - quad[2])) / 2.0
ew = (np.linalg.norm(quad[0] - quad[1]) + np.linalg.norm(quad[2] - quad[3])) / 2.0
dense_sample_pts_num = max(2, int(ew))
dense_xy_center_line = xy_text[np.linspace(0, xy_... | ['def', 'estimate_sample_pts_num(self,', 'quad,', 'xy_text):', 'eh', '=', '(np.linalg.norm(quad[0]', '-', 'quad[3])', '+', 'np.linalg.norm(quad[1]', '-', 'quad[2]))', '/', '2.0', 'ew', '=', '(np.linalg.norm(quad[0]', '-', 'quad[1])', '+', 'np.linalg.norm(quad[2]', '-', 'quad[3]))', '/', '2.0', 'dense_sample_pts_num', '... | 474,440 |
tensorlayer/TensorLayer | nlp.py | Vocabulary.word_to_id | word_to_id | Returns the integer word id of a word string. | [
"Returns",
"the",
"integer",
"word",
"id",
"of",
"a",
"word",
"string."
] | def word_to_id(self, word):
if word in self.vocab:
return self.vocab[word]
else:
return self.unk_id | ['def', 'word_to_id(self,', 'word):', 'if', 'word', 'in', 'self.vocab:', 'return', 'self.vocab[word]', 'else:', 'return', 'self.unk_id'] | 366,174 |
agoragames/haigha | transaction_class.py | TransactionClass.enabled | enabled | Get whether transactions have been enabled. | [
"Get",
"whether",
"transactions",
"have",
"been",
"enabled."
] | def enabled(self):
return self._enabled | ['def', 'enabled(self):', 'return', 'self._enabled'] | 234,611 |
fajarzuhrihadiyanto/artificial-intelligence | test_histograms.py | TestHistogramOptimBinNums.test_limited_variance | test_limited_variance | Check when IQR is 0, but variance exists, we return the sturges value and not the fd value. | [
"Check",
"when",
"IQR",
"is",
"0,",
"but",
"variance",
"exists,",
"we",
"return",
"the",
"sturges",
"value",
"and",
"not",
"the",
"fd",
"value."
] | def test_limited_variance(self):
lim_var_data = np.ones(1000)
lim_var_data[:3] = 0
lim_var_data[-4:] = 100
edges_auto = histogram_bin_edges(lim_var_data, 'auto')
assert_equal(edges_auto, np.linspace(0, 100, 12))
edges_fd = histogram_bin_edges(lim_var_data, 'fd')
assert_equal(edges_fd, np.arr... | ['def', 'test_limited_variance(self):', 'lim_var_data', '=', 'np.ones(1000)', 'lim_var_data[:3]', '=', '0', 'lim_var_data[-4:]', '=', '100', 'edges_auto', '=', 'histogram_bin_edges(lim_var_data,', "'auto')", 'assert_equal(edges_auto,', 'np.linspace(0,', '100,', '12))', 'edges_fd', '=', 'histogram_bin_edges(lim_var_data... | 170,532 |
adamshamsudeen/vision.ai | __init__.py | DebuggedApplication.get_resource | get_resource | Return a static resource from the shared folder. | [
"Return",
"a",
"static",
"resource",
"from",
"the",
"shared",
"folder."
] | def get_resource(self, request, filename):
filename = join(dirname(__file__), 'shared', basename(filename))
if isfile(filename):
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
f = open(filename, 'rb')
try:
return Response(f.read(), mimetype=mimetyp... | ['def', 'get_resource(self,', 'request,', 'filename):', 'filename', '=', 'join(dirname(__file__),', "'shared',", 'basename(filename))', 'if', 'isfile(filename):', 'mimetype', '=', 'mimetypes.guess_type(filename)[0]', 'or', "'application/octet-stream'", 'f', '=', 'open(filename,', "'rb')", 'try:', 'return', 'Response(f.... | 944,763 |
openvinotoolkit/training_extensions | dataset.py | ImageTilingDataset.get_ann_info | get_ann_info | Get annotation information of a tile. | [
"Get",
"annotation",
"information",
"of",
"a",
"tile."
] | def get_ann_info(self, idx):
return self.tile_dataset.get_ann_info(idx) | ['def', 'get_ann_info(self,', 'idx):', 'return', 'self.tile_dataset.get_ann_info(idx)'] | 918,057 |
AlibabaResearch/efficientteacher | nanodet_utils.py | compute_max_iou_anchor | compute_max_iou_anchor | For each anchor, find the GT with the largest IOU. | [
"For",
"each",
"anchor,",
"find",
"the",
"GT",
"with",
"the",
"largest",
"IOU."
] | def compute_max_iou_anchor(ious):
num_max_boxes = ious.shape[-2]
max_iou_index = ious.argmax(axis=-2)
is_max_iou = F.one_hot(max_iou_index, num_max_boxes).permute(0, 2, 1)
return is_max_iou.to(ious.dtype) | ['def', 'compute_max_iou_anchor(ious):', 'num_max_boxes', '=', 'ious.shape[-2]', 'max_iou_index', '=', 'ious.argmax(axis=-2)', 'is_max_iou', '=', 'F.one_hot(max_iou_index,', 'num_max_boxes).permute(0,', '2,', '1)', 'return', 'is_max_iou.to(ious.dtype)'] | 560,994 |
rail-berkeley/softlearning | rl_algorithm.py | RLAlgorithm.train | train | Initiate training of the SAC instance. | [
"Initiate",
"training",
"of",
"the",
"SAC",
"instance."
] | def train(self, *args, **kwargs):
return self._train(*args, **kwargs) | ['def', 'train(self,', '*args,', '**kwargs):', 'return', 'self._train(*args,', '**kwargs)'] | 879,259 |
rudranil723/mini-main | query.py | RawQuerySet.model_fields | model_fields | A dict mapping column names to model field names. | [
"A",
"dict",
"mapping",
"column",
"names",
"to",
"model",
"field",
"names."
] | def model_fields(self):
converter = connections[self.db].introspection.table_name_converter
model_fields = {}
for field in self.model._meta.fields:
(name, column) = field.get_attname_column()
model_fields[converter(column)] = field
return model_fields | ['def', 'model_fields(self):', 'converter', '=', 'connections[self.db].introspection.table_name_converter', 'model_fields', '=', '{}', 'for', 'field', 'in', 'self.model._meta.fields:', '(name,', 'column)', '=', 'field.get_attname_column()', 'model_fields[converter(column)]', '=', 'field', 'return', 'model_fields'] | 316,064 |
MushroomRL/mushroom-rl | mujoco.py | MuJoCo.get_action_space | get_action_space | Returns the action space bounding box given the action_indices and the model. | [
"Returns",
"the",
"action",
"space",
"bounding",
"box",
"given",
"the",
"action_indices",
"and",
"the",
"model."
] | def get_action_space(action_indices, model):
low = []
high = []
for index in action_indices:
if model.actuator_ctrllimited[index]:
low.append(model.actuator_ctrlrange[index][0])
high.append(model.actuator_ctrlrange[index][1])
else:
low.append(-np.inf)
... | ['def', 'get_action_space(action_indices,', 'model):', 'low', '=', '[]', 'high', '=', '[]', 'for', 'index', 'in', 'action_indices:', 'if', 'model.actuator_ctrllimited[index]:', 'low.append(model.actuator_ctrlrange[index][0])', 'high.append(model.actuator_ctrlrange[index][1])', 'else:', 'low.append(-np.inf)', 'high.appe... | 266,040 |
AgileRL/AgileRL | evolvable_bert.py | EvolvableBERT.get_model_dict | get_model_dict | Returns dictionary with model information and weights. | [
"Returns",
"dictionary",
"with",
"model",
"information",
"and",
"weights."
] | def get_model_dict(self):
model_dict = self.init_dict
model_dict.update({'stored_values': self.extract_parameters(without_layer_norm=False)})
return model_dict | ['def', 'get_model_dict(self):', 'model_dict', '=', 'self.init_dict', "model_dict.update({'stored_values':", 'self.extract_parameters(without_layer_norm=False)})', 'return', 'model_dict'] | 23,952 |
ldkong1205/LaserMix | dfm.py | DfM.with_depth_head | with_depth_head | Whether the detector has a frustum-based depth head. | [
"Whether",
"the",
"detector",
"has",
"a",
"frustum-based",
"depth",
"head."
] | def with_depth_head(self):
return hasattr(self, 'depth_head') and self.depth_head is not None | ['def', 'with_depth_head(self):', 'return', 'hasattr(self,', "'depth_head')", 'and', 'self.depth_head', 'is', 'not', 'None'] | 624,058 |
DataPieInc/GANs----Generative-Adversarial-Networks | DiscoGAN_main.py | data_network_x | data_network_x | Approximate x log data density. | [
"Approximate",
"x",
"log",
"data",
"density."
] | def data_network_x(x, n_layers=2, n_hidden=256, activation_fn=None):
h = tf.concat(x, 1)
with tf.variable_scope('discriminator_x'):
h = slim.repeat(h, n_layers, slim.fully_connected, n_hidden, activation_fn=tf.nn.relu)
log_d = slim.fully_connected(h, 1, activation_fn=activation_fn)
return tf... | ['def', 'data_network_x(x,', 'n_layers=2,', 'n_hidden=256,', 'activation_fn=None):', 'h', '=', 'tf.concat(x,', '1)', 'with', "tf.variable_scope('discriminator_x'):", 'h', '=', 'slim.repeat(h,', 'n_layers,', 'slim.fully_connected,', 'n_hidden,', 'activation_fn=tf.nn.relu)', 'log_d', '=', 'slim.fully_connected(h,', '1,',... | 566,604 |
tfzhou/ProtoSeg | image_helper.py | ImageHelper.imfrombytes | imfrombytes | Read an image from bytes. | [
"Read",
"an",
"image",
"from",
"bytes."
] | def imfrombytes(content, flag='color'):
imread_flags = {'color': cv2.IMREAD_COLOR, 'grayscale': cv2.IMREAD_GRAYSCALE, 'unchanged': cv2.IMREAD_UNCHANGED}
img_np = np.fromstring(content, np.uint8)
flag = imread_flags[flag] if isinstance(flag, str) else flag
img = cv2.imdecode(img_np, flag)
return img | ['def', 'imfrombytes(content,', "flag='color'):", 'imread_flags', '=', "{'color':", 'cv2.IMREAD_COLOR,', "'grayscale':", 'cv2.IMREAD_GRAYSCALE,', "'unchanged':", 'cv2.IMREAD_UNCHANGED}', 'img_np', '=', 'np.fromstring(content,', 'np.uint8)', 'flag', '=', 'imread_flags[flag]', 'if', 'isinstance(flag,', 'str)', 'else', 'f... | 818,035 |
cleanlab/cleanlab | util.py | print_noise_matrix | print_noise_matrix | Pretty prints the noise matrix. | [
"Pretty",
"prints",
"the",
"noise",
"matrix."
] | def print_noise_matrix(noise_matrix, round_places=2):
print_square_matrix(noise_matrix, title=' Noise Matrix (aka Noisy Channel) P(given_label|true_label)', short_title='p(s|y)', round_places=round_places) | ['def', 'print_noise_matrix(noise_matrix,', 'round_places=2):', 'print_square_matrix(noise_matrix,', "title='", 'Noise', 'Matrix', '(aka', 'Noisy', 'Channel)', "P(given_label|true_label)',", "short_title='p(s|y)',", 'round_places=round_places)'] | 488,037 |
hoangminhle/hierarchical_IL_RL | mdp_obstacles.py | MDP.R | R | Return a numeric reward for this state. | [
"Return",
"a",
"numeric",
"reward",
"for",
"this",
"state."
] | def R(self, state):
return self.reward[state] | ['def', 'R(self,', 'state):', 'return', 'self.reward[state]'] | 206,419 |
feast-dev/feast | redshift_source.py | RedshiftSource.table | table | Returns the table of this Redshift source. | [
"Returns",
"the",
"table",
"of",
"this",
"Redshift",
"source."
] | def table(self):
return self.redshift_options.table | ['def', 'table(self):', 'return', 'self.redshift_options.table'] | 544,390 |
AgnostiqHQ/covalent | electron_test.py | test_as_transportable_dict | test_as_transportable_dict | Test the get transportable electron function. | [
"Test",
"the",
"get",
"transportable",
"electron",
"function."
] | def test_as_transportable_dict():
@ct.electron
def test_func(a):
return a
mock_metadata = {'a': 1, 'b': 2, 'c': None}
electron = Electron(function=test_func, node_id=1, metadata=mock_metadata)
transportable_electron = electron.as_transportable_dict
assert transportable_electron['name'] ... | ['def', 'test_as_transportable_dict():', '@ct.electron', 'def', 'test_func(a):', 'return', 'a', 'mock_metadata', '=', "{'a':", '1,', "'b':", '2,', "'c':", 'None}', 'electron', '=', 'Electron(function=test_func,', 'node_id=1,', 'metadata=mock_metadata)', 'transportable_electron', '=', 'electron.as_transportable_dict', '... | 489,892 |
kukuruza/shuffler | shuffler_dataset.py | DatasetWriter.addObject | addObject | Record an object into the database. | [
"Record",
"an",
"object",
"into",
"the",
"database."
] | def addObject(self, object_dict):
if not isinstance(object_dict, Mapping):
raise TypeError('object_dict should be a dict, not %s' % type(object_dict))
if 'imagefile' not in object_dict:
raise KeyError('"imagefile" is required in object_dict, got %s' % object_dict)
imagefile = object_dict['im... | ['def', 'addObject(self,', 'object_dict):', 'if', 'not', 'isinstance(object_dict,', 'Mapping):', 'raise', "TypeError('object_dict", 'should', 'be', 'a', 'dict,', 'not', "%s'", '%', 'type(object_dict))', 'if', "'imagefile'", 'not', 'in', 'object_dict:', 'raise', 'KeyError(\'"imagefile"', 'is', 'required', 'in', 'object_... | 933,796 |
enuguru/artificial_intelligence_and_machine_learning | index.py | FileIndex.lock | lock | Returns a lock object that you can try to call acquire() on to lock the index. | [
"Returns",
"a",
"lock",
"object",
"that",
"you",
"can",
"try",
"to",
"call",
"acquire()",
"on",
"to",
"lock",
"the",
"index."
] | def lock(self, name):
return self.storage.lock(self.indexname + '_' + name) | ['def', 'lock(self,', 'name):', 'return', 'self.storage.lock(self.indexname', '+', "'_'", '+', 'name)'] | 132,952 |
david8862/Object-Detection-Evaluation | object_detection_eval.py | get_rec_prec | get_rec_prec | Calculate precision/recall based on true_positive, false_positive result. | [
"Calculate",
"precision/recall",
"based",
"on",
"true_positive,",
"false_positive",
"result."
] | def get_rec_prec(true_positive, false_positive, gt_records):
cumsum = 0
for (idx, val) in enumerate(false_positive):
false_positive[idx] += cumsum
cumsum += val
cumsum = 0
for (idx, val) in enumerate(true_positive):
true_positive[idx] += cumsum
cumsum += val
rec = tru... | ['def', 'get_rec_prec(true_positive,', 'false_positive,', 'gt_records):', 'cumsum', '=', '0', 'for', '(idx,', 'val)', 'in', 'enumerate(false_positive):', 'false_positive[idx]', '+=', 'cumsum', 'cumsum', '+=', 'val', 'cumsum', '=', '0', 'for', '(idx,', 'val)', 'in', 'enumerate(true_positive):', 'true_positive[idx]', '+=... | 726,125 |
Rshcaroline/FDU-Artificial-Intelligence | submission.py | peekingMDP | peekingMDP | Return an instance of BlackjackMDP where peeking is the optimal action at least 10% of the time. | [
"Return",
"an",
"instance",
"of",
"BlackjackMDP",
"where",
"peeking",
"is",
"the",
"optimal",
"action",
"at",
"least",
"10%",
"of",
"the",
"time."
] | def peekingMDP():
return BlackjackMDP(cardValues=[1, 2, 3, 4, 5, 100], multiplicity=1, threshold=20, peekCost=1) | ['def', 'peekingMDP():', 'return', 'BlackjackMDP(cardValues=[1,', '2,', '3,', '4,', '5,', '100],', 'multiplicity=1,', 'threshold=20,', 'peekCost=1)'] | 179,338 |
weimin17/Object-Detection_HelmetDetection | data_provider.py | central_crop | central_crop | Returns a central crop for the specified size of an image. | [
"Returns",
"a",
"central",
"crop",
"for",
"the",
"specified",
"size",
"of",
"an",
"image."
] | def central_crop(image, crop_size):
with tf.variable_scope('CentralCrop'):
(target_width, target_height) = crop_size
(image_height, image_width) = (tf.shape(image)[0], tf.shape(image)[1])
assert_op1 = tf.Assert(tf.greater_equal(image_height, target_height), ['image_height < target_height', i... | ['def', 'central_crop(image,', 'crop_size):', 'with', "tf.variable_scope('CentralCrop'):", '(target_width,', 'target_height)', '=', 'crop_size', '(image_height,', 'image_width)', '=', '(tf.shape(image)[0],', 'tf.shape(image)[1])', 'assert_op1', '=', 'tf.Assert(tf.greater_equal(image_height,', 'target_height),', "['imag... | 761,692 |
mme/vergeml | env.py | Environment.set_defaults | set_defaults | Set up environment defaults before executing the command. | [
"Set",
"up",
"environment",
"defaults",
"before",
"executing",
"the",
"command."
] | def set_defaults(self, cmd, args):
if self.model_plugin:
self.model_plugin.set_defaults(cmd, args, self)
self._config['device'] = parse_device(self._config.get('device', {}))
self._config['data'] = parse_data(self._config.get('data', {})) | ['def', 'set_defaults(self,', 'cmd,', 'args):', 'if', 'self.model_plugin:', 'self.model_plugin.set_defaults(cmd,', 'args,', 'self)', "self._config['device']", '=', "parse_device(self._config.get('device',", '{}))', "self._config['data']", '=', "parse_data(self._config.get('data',", '{}))'] | 931,531 |
enuguru/artificial_intelligence_and_machine_learning | blueprints.py | Blueprint.app_url_defaults | app_url_defaults | Same as :meth:`url_defaults` but application wide. | [
"Same",
"as",
":meth:`url_defaults`",
"but",
"application",
"wide."
] | def app_url_defaults(self, f):
self.record_once(lambda s: s.app.url_default_functions.setdefault(None, []).append(f))
return f | ['def', 'app_url_defaults(self,', 'f):', 'self.record_once(lambda', 's:', 's.app.url_default_functions.setdefault(None,', '[]).append(f))', 'return', 'f'] | 148,042 |
voxel51/fiftyone | stages.py | GroupBy.sort_expr | sort_expr | An expression defining how the sort the groups in the output view. | [
"An",
"expression",
"defining",
"how",
"the",
"sort",
"the",
"groups",
"in",
"the",
"output",
"view."
] | def sort_expr(self):
return self._sort_expr | ['def', 'sort_expr(self):', 'return', 'self._sort_expr'] | 583,317 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | layers.py | evaluate | evaluate | Calculates total loss and performance metrics like accuracy. | [
"Calculates",
"total",
"loss",
"and",
"performance",
"metrics",
"like",
"accuracy."
] | def evaluate(logits, labels, num_targets, scope, loss_type):
with tf.name_scope('loss'):
if loss_type == 'sigmoid':
classification_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels / 2.0, logits=logits)
elif loss_type == 'softmax':
classification_loss = tf.nn.softm... | ['def', 'evaluate(logits,', 'labels,', 'num_targets,', 'scope,', 'loss_type):', 'with', "tf.name_scope('loss'):", 'if', 'loss_type', '==', "'sigmoid':", 'classification_loss', '=', 'tf.nn.sigmoid_cross_entropy_with_logits(labels=labels', '/', '2.0,', 'logits=logits)', 'elif', 'loss_type', '==', "'softmax':", 'classific... | 47,059 |
TRAILab/CaDDN | fastai_optim.py | get_master | get_master | Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32. | [
"Return",
"two",
"lists,",
"one",
"for",
"the",
"model",
"parameters",
"in",
"FP16",
"and",
"one",
"for",
"the",
"master",
"parameters",
"in",
"FP32."
] | def get_master(layer_groups, flat_master: bool=False):
split_groups = split_bn_bias(layer_groups)
model_params = [[param for param in lg.parameters() if param.requires_grad] for lg in split_groups]
if flat_master:
master_params = []
for lg in model_params:
if len(lg) != 0:
... | ['def', 'get_master(layer_groups,', 'flat_master:', 'bool=False):', 'split_groups', '=', 'split_bn_bias(layer_groups)', 'model_params', '=', '[[param', 'for', 'param', 'in', 'lg.parameters()', 'if', 'param.requires_grad]', 'for', 'lg', 'in', 'split_groups]', 'if', 'flat_master:', 'master_params', '=', '[]', 'for', 'lg'... | 410,793 |
suarez12138/AI-Reversi_IMP_TextDichotomy | geo.py | GeoAxes.set_longitude_grid | set_longitude_grid | Set the number of degrees between each longitude grid. | [
"Set",
"the",
"number",
"of",
"degrees",
"between",
"each",
"longitude",
"grid."
] | def set_longitude_grid(self, degrees):
grid = np.arange(-180 + degrees, 180, degrees)
self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.xaxis.set_major_formatter(self.ThetaFormatter(degrees)) | ['def', 'set_longitude_grid(self,', 'degrees):', 'grid', '=', 'np.arange(-180', '+', 'degrees,', '180,', 'degrees)', 'self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))', 'self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))'] | 97,192 |
lingyunwu14/STFT | loss.py | Shift2BoxTransform.apply_deltas | apply_deltas | Apply transformation `deltas` (dl, dt, dr, db) to `shifts`. | [
"Apply",
"transformation",
"`deltas`",
"(dl,",
"dt,",
"dr,",
"db)",
"to",
"`shifts`."
] | def apply_deltas(self, deltas, shifts):
assert torch.isfinite(deltas).all().item()
shifts = shifts.to(deltas.dtype)
if deltas.numel() == 0:
return torch.empty_like(deltas)
deltas = deltas.view(deltas.size()[:-1] + (-1, 4)) / shifts.new_tensor(self.weights)
boxes = torch.cat((shifts.unsqueeze... | ['def', 'apply_deltas(self,', 'deltas,', 'shifts):', 'assert', 'torch.isfinite(deltas).all().item()', 'shifts', '=', 'shifts.to(deltas.dtype)', 'if', 'deltas.numel()', '==', '0:', 'return', 'torch.empty_like(deltas)', 'deltas', '=', 'deltas.view(deltas.size()[:-1]', '+', '(-1,', '4))', '/', 'shifts.new_tensor(self.weig... | 908,798 |
nicknochnack/RealTimeSignLanguageTFJS | dataset_loader.py | KittiOdom.load_example | load_example | Returns a sequence with requested target frame. | [
"Returns",
"a",
"sequence",
"with",
"requested",
"target",
"frame."
] | def load_example(self, frames, target_frame_index):
(image_seq, zoom_x, zoom_y) = self.load_image_sequence(frames, target_frame_index)
(target_frame_drive, target_frame_id) = frames[target_frame_index].split(' ')
intrinsics = self.load_intrinsics(target_frame_drive, target_frame_id)
intrinsics = self.sc... | ['def', 'load_example(self,', 'frames,', 'target_frame_index):', '(image_seq,', 'zoom_x,', 'zoom_y)', '=', 'self.load_image_sequence(frames,', 'target_frame_index)', '(target_frame_drive,', 'target_frame_id)', '=', "frames[target_frame_index].split('", "')", 'intrinsics', '=', 'self.load_intrinsics(target_frame_drive,'... | 831,399 |
pavol6999/NaturalLanguageProcessing | run_squad.py | validate_flags_or_throw | validate_flags_or_throw | Validate the input FLAGS or throw an exception. | [
"Validate",
"the",
"input",
"FLAGS",
"or",
"throw",
"an",
"exception."
] | def validate_flags_or_throw(bert_config):
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case, FLAGS.init_checkpoint)
if not FLAGS.do_train and (not FLAGS.do_predict):
raise ValueError('At least one of `do_train` or `do_predict` must be True.')
if FLAGS.do_train:
if not FLAGS.t... | ['def', 'validate_flags_or_throw(bert_config):', 'tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,', 'FLAGS.init_checkpoint)', 'if', 'not', 'FLAGS.do_train', 'and', '(not', 'FLAGS.do_predict):', 'raise', "ValueError('At", 'least', 'one', 'of', '`do_train`', 'or', '`do_predict`', 'must', 'be', "True.')... | 799,492 |
43Carrig/recurrent_neural_networks_practice | ops.py | Tensor.value_index | value_index | The index of this tensor in the outputs of its `Operation`. | [
"The",
"index",
"of",
"this",
"tensor",
"in",
"the",
"outputs",
"of",
"its",
"`Operation`."
] | def value_index(self):
return self._value_index | ['def', 'value_index(self):', 'return', 'self._value_index'] | 336,375 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | sample_generation_tools.py | progress_bar | progress_bar | Print a progress bar to the terminal to see how things are moving along. | [
"Print",
"a",
"progress",
"bar",
"to",
"the",
"terminal",
"to",
"see",
"how",
"things",
"are",
"moving",
"along."
] | def progress_bar(current_value, max_value, elapsed_time=0, bar_length=50):
percent = float(current_value) / max_value
full_bar = '=' * int(round(percent * bar_length))
empty_bar = '-' * (bar_length - len(full_bar))
eta = elapsed_time / percent - elapsed_time
out = '\r[{0}] {1}% ({2}/{3}) | {4:.1f}s ... | ['def', 'progress_bar(current_value,', 'max_value,', 'elapsed_time=0,', 'bar_length=50):', 'percent', '=', 'float(current_value)', '/', 'max_value', 'full_bar', '=', "'='", '*', 'int(round(percent', '*', 'bar_length))', 'empty_bar', '=', "'-'", '*', '(bar_length', '-', 'len(full_bar))', 'eta', '=', 'elapsed_time', '/',... | 12,378 |
JedMills/MTFL-For-Personalised-DNNs | models.py | CIFAR10Model.forward | forward | Returns outputs of model given data x. | [
"Returns",
"outputs",
"of",
"model",
"given",
"data",
"x."
] | def forward(self, x):
a = self.bn0(self.pool0(self.relu0(self.conv0(x))))
b = self.bn1(self.pool1(self.relu1(self.conv1(a))))
c = self.relu2(self.fc0(self.flat(b)))
return self.out(c) | ['def', 'forward(self,', 'x):', 'a', '=', 'self.bn0(self.pool0(self.relu0(self.conv0(x))))', 'b', '=', 'self.bn1(self.pool1(self.relu1(self.conv1(a))))', 'c', '=', 'self.relu2(self.fc0(self.flat(b)))', 'return', 'self.out(c)'] | 642,736 |
myothida/Supervised-Machine-Learning | test_plot_partial_dependence.py | test_partial_dependence_plot_limits_two_way | test_partial_dependence_plot_limits_two_way | Check that the PD limit on the plots are properly set on two-way plots. | [
"Check",
"that",
"the",
"PD",
"limit",
"on",
"the",
"plots",
"are",
"properly",
"set",
"on",
"two-way",
"plots."
] | def test_partial_dependence_plot_limits_two_way(pyplot, clf_diabetes, diabetes, centered):
disp = PartialDependenceDisplay.from_estimator(clf_diabetes, diabetes.data, features=[(0, 1)], kind='average', grid_resolution=25, feature_names=diabetes.feature_names)
range_pd = np.array([-1, 1], dtype=np.float64)
f... | ['def', 'test_partial_dependence_plot_limits_two_way(pyplot,', 'clf_diabetes,', 'diabetes,', 'centered):', 'disp', '=', 'PartialDependenceDisplay.from_estimator(clf_diabetes,', 'diabetes.data,', 'features=[(0,', '1)],', "kind='average',", 'grid_resolution=25,', 'feature_names=diabetes.feature_names)', 'range_pd', '=', ... | 364,055 |
rouge8/20questions | webinterface.py | learn.GET | GET | Renders the learn page, allowing the user to select the correct character and add a new question. | [
"Renders",
"the",
"learn",
"page,",
"allowing",
"the",
"user",
"to",
"select",
"the",
"correct",
"character",
"and",
"add",
"a",
"new",
"question."
] | def GET(self):
nearby_objects = game.get_nearby_objects(session.objects_values, how_many=20)
return render.learn(nearby_objects) | ['def', 'GET(self):', 'nearby_objects', '=', 'game.get_nearby_objects(session.objects_values,', 'how_many=20)', 'return', 'render.learn(nearby_objects)'] | 4,402 |
liuweijie19980216/DRL-for-FSOD | coco.py | coco.image_path_at | image_path_at | Return the absolute path to image i in the image sequence. | [
"Return",
"the",
"absolute",
"path",
"to",
"image",
"i",
"in",
"the",
"image",
"sequence."
] | def image_path_at(self, i):
return self.image_path_from_index(self._image_index[i]) | ['def', 'image_path_at(self,', 'i):', 'return', 'self.image_path_from_index(self._image_index[i])'] | 552,809 |
googleapis/python-aiplatform | proto_converters.py | TrialConverter.from_protos | from_protos | Convenience wrapper for from_proto. | [
"Convenience",
"wrapper",
"for",
"from_proto."
] | def from_protos(cls, protos: Sequence[study_pb2.Trial]) -> List[Trial]:
return [TrialConverter.from_proto(proto) for proto in protos] | ['def', 'from_protos(cls,', 'protos:', 'Sequence[study_pb2.Trial])', '->', 'List[Trial]:', 'return', '[TrialConverter.from_proto(proto)', 'for', 'proto', 'in', 'protos]'] | 810,294 |
Sea1004/artificial_intelligence | sysconfig.py | get_path_names | get_path_names | Return a tuple containing the paths names. | [
"Return",
"a",
"tuple",
"containing",
"the",
"paths",
"names."
] | def get_path_names():
return _SCHEMES.options('posix_prefix') | ['def', 'get_path_names():', 'return', "_SCHEMES.options('posix_prefix')"] | 148,629 |
VinayMatcha/NaturalLanguageProcessing | modeling.py | assert_rank | assert_rank | Raises an exception if the tensor rank is not of the expected rank. | [
"Raises",
"an",
"exception",
"if",
"the",
"tensor",
"rank",
"is",
"not",
"of",
"the",
"expected",
"rank."
] | def assert_rank(tensor, expected_rank, name=None):
if name is None:
name = tensor.name
expected_rank_dict = {}
if isinstance(expected_rank, six.integer_types):
expected_rank_dict[expected_rank] = True
else:
for x in expected_rank:
expected_rank_dict[x] = True
actu... | ['def', 'assert_rank(tensor,', 'expected_rank,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', 'tensor.name', 'expected_rank_dict', '=', '{}', 'if', 'isinstance(expected_rank,', 'six.integer_types):', 'expected_rank_dict[expected_rank]', '=', 'True', 'else:', 'for', 'x', 'in', 'expected_rank:', 'expected_ran... | 712,139 |
kubeflow/pipelines | pipeline.py | list_versions | list_versions | List versions of an uploaded KFP pipeline. | [
"List",
"versions",
"of",
"an",
"uploaded",
"KFP",
"pipeline."
] | def list_versions(ctx: click.Context, pipeline_id: str, page_token: str, max_size: int, sort_by: str, filter: str):
client = ctx.obj['client']
output_format = ctx.obj['output']
response = client.list_pipeline_versions(pipeline_id, page_token=page_token, page_size=max_size, sort_by=sort_by, filter=filter)
... | ['def', 'list_versions(ctx:', 'click.Context,', 'pipeline_id:', 'str,', 'page_token:', 'str,', 'max_size:', 'int,', 'sort_by:', 'str,', 'filter:', 'str):', 'client', '=', "ctx.obj['client']", 'output_format', '=', "ctx.obj['output']", 'response', '=', 'client.list_pipeline_versions(pipeline_id,', 'page_token=page_token... | 779,993 |
epfl-ml4ed/meta-transfer-learning | resnet12.py | Models.construct_fc_weights | construct_fc_weights | The function to construct fc weights. | [
"The",
"function",
"to",
"construct",
"fc",
"weights."
] | def construct_fc_weights(self):
dtype = tf.float32
fc_weights = {}
fc_initializer = tf.contrib.layers.xavier_initializer(dtype=dtype)
if FLAGS.phase == 'pre':
fc_weights['w5'] = tf.get_variable('fc_w5', [512, FLAGS.pretrain_class_num], initializer=fc_initializer)
fc_weights['b5'] = tf.Va... | ['def', 'construct_fc_weights(self):', 'dtype', '=', 'tf.float32', 'fc_weights', '=', '{}', 'fc_initializer', '=', 'tf.contrib.layers.xavier_initializer(dtype=dtype)', 'if', 'FLAGS.phase', '==', "'pre':", "fc_weights['w5']", '=', "tf.get_variable('fc_w5',", '[512,', 'FLAGS.pretrain_class_num],', 'initializer=fc_initial... | 633,129 |
ChenhongyiYang/PPAL | utils.py | get_loading_pipeline | get_loading_pipeline | Only keep loading image and annotations related configuration. | [
"Only",
"keep",
"loading",
"image",
"and",
"annotations",
"related",
"configuration."
] | def get_loading_pipeline(pipeline):
loading_pipeline_cfg = []
for cfg in pipeline:
obj_cls = PIPELINES.get(cfg['type'])
if obj_cls is not None and obj_cls in (LoadImageFromFile, LoadAnnotations):
loading_pipeline_cfg.append(cfg)
assert len(loading_pipeline_cfg) == 2, 'The data pi... | ['def', 'get_loading_pipeline(pipeline):', 'loading_pipeline_cfg', '=', '[]', 'for', 'cfg', 'in', 'pipeline:', 'obj_cls', '=', "PIPELINES.get(cfg['type'])", 'if', 'obj_cls', 'is', 'not', 'None', 'and', 'obj_cls', 'in', '(LoadImageFromFile,', 'LoadAnnotations):', 'loading_pipeline_cfg.append(cfg)', 'assert', 'len(loadin... | 821,393 |
myothida/Supervised-Machine-Learning | test_isomap.py | test_isomap_dtype_equivalence | test_isomap_dtype_equivalence | Check the equivalence of the results with 32 and 64 bits input. | [
"Check",
"the",
"equivalence",
"of",
"the",
"results",
"with",
"32",
"and",
"64",
"bits",
"input."
] | def test_isomap_dtype_equivalence():
iso_32 = manifold.Isomap(n_neighbors=2)
X_32 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32)
iso_32.fit(X_32)
iso_64 = manifold.Isomap(n_neighbors=2)
X_64 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float64)
iso_64.fit(X_64)
assert_allclose(iso_3... | ['def', 'test_isomap_dtype_equivalence():', 'iso_32', '=', 'manifold.Isomap(n_neighbors=2)', 'X_32', '=', 'np.array([[1,', '2],', '[3,', '4],', '[5,', '6]],', 'dtype=np.float32)', 'iso_32.fit(X_32)', 'iso_64', '=', 'manifold.Isomap(n_neighbors=2)', 'X_64', '=', 'np.array([[1,', '2],', '[3,', '4],', '[5,', '6]],', 'dtyp... | 364,233 |
sunishsheth2009/ChatterBot | site.py | execsitecustomize | execsitecustomize | Run custom site specific code, if available. | [
"Run",
"custom",
"site",
"specific",
"code,",
"if",
"available."
] | def execsitecustomize():
try:
import sitecustomize
except ImportError:
pass | ['def', 'execsitecustomize():', 'try:', 'import', 'sitecustomize', 'except', 'ImportError:', 'pass'] | 528,088 |
enuguru/artificial_intelligence_and_machine_learning | classification.py | RandomForest.use | use | Outputs the class predictions for ``dataset`` and the class probabilities. | [
"Outputs",
"the",
"class",
"predictions",
"for",
"``dataset``",
"and",
"the",
"class",
"probabilities."
] | def use(self, dataset):
for (i, xy) in enumerate(dataset):
(x, y) = xy
if i == 0:
features = np.zeros((len(dataset), dataset.metadata['input_size']), dtype=x.dtype)
features[i] = x
outputs_cl = self.forest.predict(features)
outputs_probs = self.forest.predict_proba(featur... | ['def', 'use(self,', 'dataset):', 'for', '(i,', 'xy)', 'in', 'enumerate(dataset):', '(x,', 'y)', '=', 'xy', 'if', 'i', '==', '0:', 'features', '=', 'np.zeros((len(dataset),', "dataset.metadata['input_size']),", 'dtype=x.dtype)', 'features[i]', '=', 'x', 'outputs_cl', '=', 'self.forest.predict(features)', 'outputs_probs... | 135,271 |
Katja-M/Python_NaturalLanguageProcessing | perceptron.py | AveragedPerceptron.predict | predict | Dot-product the features and current weights and return the best label. | [
"Dot-product",
"the",
"features",
"and",
"current",
"weights",
"and",
"return",
"the",
"best",
"label."
] | def predict(self, features, return_conf=False):
scores = defaultdict(float)
for (feat, value) in features.items():
if feat not in self.weights or value == 0:
continue
weights = self.weights[feat]
for (label, weight) in weights.items():
scores[label] += value * wei... | ['def', 'predict(self,', 'features,', 'return_conf=False):', 'scores', '=', 'defaultdict(float)', 'for', '(feat,', 'value)', 'in', 'features.items():', 'if', 'feat', 'not', 'in', 'self.weights', 'or', 'value', '==', '0:', 'continue', 'weights', '=', 'self.weights[feat]', 'for', '(label,', 'weight)', 'in', 'weights.item... | 867,017 |
datamadness/Time-signal-classification-using---Network | CNN_TFR_discharge_detection_Model2.py | cnn_model_fn | cnn_model_fn | Model function for CNN. | [
"Model",
"function",
"for",
"CNN."
] | def cnn_model_fn(features, labels, mode):
if mode == tf.estimator.ModeKeys.PREDICT:
pass
else:
labels = tf.reshape(labels, [-1, 1])
input_layer = tf.reshape(features['signal_data'], [-1, 240, 200, 1])
print(input_layer)
conv1 = tf.layers.conv2d(inputs=input_layer, filters=16, kernel_... | ['def', 'cnn_model_fn(features,', 'labels,', 'mode):', 'if', 'mode', '==', 'tf.estimator.ModeKeys.PREDICT:', 'pass', 'else:', 'labels', '=', 'tf.reshape(labels,', '[-1,', '1])', 'input_layer', '=', "tf.reshape(features['signal_data'],", '[-1,', '240,', '200,', '1])', 'print(input_layer)', 'conv1', '=', 'tf.layers.conv2... | 355,339 |
atulkum/object_detection | nn.py | fully_connected | fully_connected | Apply a fully-connected layer (with bias). | [
"Apply",
"a",
"fully-connected",
"layer",
"(with",
"bias)."
] | def fully_connected(x, output_size, name, init_w='normal', init_b=0, stddev=0.001, group_id=0):
x_shape = _get_shape(x)
input_dim = x_shape[-1]
with tf.variable_scope(name) as scope:
w = weight('weights', [input_dim, output_size], init=init_w, stddev=stddev, group_id=group_id)
b = bias('bias... | ['def', 'fully_connected(x,', 'output_size,', 'name,', "init_w='normal',", 'init_b=0,', 'stddev=0.001,', 'group_id=0):', 'x_shape', '=', '_get_shape(x)', 'input_dim', '=', 'x_shape[-1]', 'with', 'tf.variable_scope(name)', 'as', 'scope:', 'w', '=', "weight('weights',", '[input_dim,', 'output_size],', 'init=init_w,', 'st... | 793,163 |
Kvatsx/Artificial-Intelligence-Assignments | textpath.py | TextToPath.get_glyphs_with_font | get_glyphs_with_font | Convert string *s* to vertices and codes using the provided ttf font. | [
"Convert",
"string",
"*s*",
"to",
"vertices",
"and",
"codes",
"using",
"the",
"provided",
"ttf",
"font."
] | def get_glyphs_with_font(self, font, s, glyph_map=None, return_new_glyphs_only=False):
lastgind = None
currx = 0
xpositions = []
glyph_ids = []
if glyph_map is None:
glyph_map = OrderedDict()
if return_new_glyphs_only:
glyph_map_new = OrderedDict()
else:
glyph_map_new... | ['def', 'get_glyphs_with_font(self,', 'font,', 's,', 'glyph_map=None,', 'return_new_glyphs_only=False):', 'lastgind', '=', 'None', 'currx', '=', '0', 'xpositions', '=', '[]', 'glyph_ids', '=', '[]', 'if', 'glyph_map', 'is', 'None:', 'glyph_map', '=', 'OrderedDict()', 'if', 'return_new_glyphs_only:', 'glyph_map_new', '=... | 894 |
Westlake-AI/openmixup | ema_hook.py | SwitchEMAHook.after_train_epoch | after_train_epoch | We load parameter values from ema backup to model before the EvalHook. | [
"We",
"load",
"parameter",
"values",
"from",
"ema",
"backup",
"to",
"model",
"before",
"the",
"EvalHook."
] | def after_train_epoch(self, runner):
if self.switch_end < runner.epoch:
return
self._swap_ema_parameters() | ['def', 'after_train_epoch(self,', 'runner):', 'if', 'self.switch_end', '<', 'runner.epoch:', 'return', 'self._swap_ema_parameters()'] | 252,306 |
sarnsdev/social-alignment-data-mining | opt.py | get_clients2 | get_clients2 | Used by erf/erfc opt to track less frequent op. | [
"Used",
"by",
"erf/erfc",
"opt",
"to",
"track",
"less",
"frequent",
"op."
] | def get_clients2(node):
l = []
for (c, i) in node.outputs[0].clients:
if c != 'output':
for var in c.outputs:
l.extend([cc for (cc, ii) in var.clients if cc != 'output'])
return l | ['def', 'get_clients2(node):', 'l', '=', '[]', 'for', '(c,', 'i)', 'in', 'node.outputs[0].clients:', 'if', 'c', '!=', "'output':", 'for', 'var', 'in', 'c.outputs:', 'l.extend([cc', 'for', '(cc,', 'ii)', 'in', 'var.clients', 'if', 'cc', '!=', "'output'])", 'return', 'l'] | 393,179 |
Ruturaj123/Flowchart-Detection | fused_conv2d_bias_activation_benchmark.py | build_conv_bias_relu_graph | build_conv_bias_relu_graph | builds a graph containing a sequence of conv2d operations. | [
"builds",
"a",
"graph",
"containing",
"a",
"sequence",
"of",
"conv2d",
"operations."
] | def build_conv_bias_relu_graph(device, input_shape, filter_shape, strides, padding, num_iters, data_format):
if data_format == 'NCHW':
input_shape = [input_shape[0], input_shape[3], input_shape[1], input_shape[2]]
with ops.device('/%s:0' % device):
inp = variables.Variable(random_ops.truncated_n... | ['def', 'build_conv_bias_relu_graph(device,', 'input_shape,', 'filter_shape,', 'strides,', 'padding,', 'num_iters,', 'data_format):', 'if', 'data_format', '==', "'NCHW':", 'input_shape', '=', '[input_shape[0],', 'input_shape[3],', 'input_shape[1],', 'input_shape[2]]', 'with', "ops.device('/%s:0'", '%', 'device):', 'inp... | 603,099 |
rudranil723/mini-main | test_datetimelike.py | freqstr | freqstr | Fixture returning parametrized frequency in string format. | [
"Fixture",
"returning",
"parametrized",
"frequency",
"in",
"string",
"format."
] | def freqstr(request):
return request.param | ['def', 'freqstr(request):', 'return', 'request.param'] | 267,372 |
dvlab-research/FocalsConv | waymo_decoder.py | extract_points_from_range_image | extract_points_from_range_image | Decode points from lidar. | [
"Decode",
"points",
"from",
"lidar."
] | def extract_points_from_range_image(laser, calibration, frame_pose):
if laser.name != calibration.name:
raise ValueError('Laser and calibration do not match')
if laser.name == dataset_pb2.LaserName.TOP:
frame_pose = tf.convert_to_tensor(np.reshape(np.array(frame_pose.transform), [4, 4]))
... | ['def', 'extract_points_from_range_image(laser,', 'calibration,', 'frame_pose):', 'if', 'laser.name', '!=', 'calibration.name:', 'raise', "ValueError('Laser", 'and', 'calibration', 'do', 'not', "match')", 'if', 'laser.name', '==', 'dataset_pb2.LaserName.TOP:', 'frame_pose', '=', 'tf.convert_to_tensor(np.reshape(np.arra... | 608,118 |
xuanlinli17/CS285_Fa19_Deep_Reinforcement_Learning | logger.py | Logger.log_scalars | log_scalars | Will log all scalars in the same plot. | [
"Will",
"log",
"all",
"scalars",
"in",
"the",
"same",
"plot."
] | def log_scalars(self, scalar_dict, group_name, step, phase):
self._summ_writer.add_scalars('{}_{}'.format(group_name, phase), scalar_dict, step) | ['def', 'log_scalars(self,', 'scalar_dict,', 'group_name,', 'step,', 'phase):', "self._summ_writer.add_scalars('{}_{}'.format(group_name,", 'phase),', 'scalar_dict,', 'step)'] | 227,751 |
bayer-science-for-a-better-life/contrastive-reconstruction | contrastive.py | color_jitter_rand | color_jitter_rand | Distorts the color of the image (jittering order is random). | [
"Distorts",
"the",
"color",
"of",
"the",
"image",
"(jittering",
"order",
"is",
"random)."
] | def color_jitter_rand(image, brightness=0, contrast=0, saturation=0, hue=0, impl='simclrv2'):
with tf.name_scope('distort_color'):
def apply_transform(i, x):
def brightness_foo():
if brightness == 0:
return x
else:
return ... | ['def', 'color_jitter_rand(image,', 'brightness=0,', 'contrast=0,', 'saturation=0,', 'hue=0,', "impl='simclrv2'):", 'with', "tf.name_scope('distort_color'):", 'def', 'apply_transform(i,', 'x):', 'def', 'brightness_foo():', 'if', 'brightness', '==', '0:', 'return', 'x', 'else:', 'return', 'random_brightness(x,', 'max_de... | 136,599 |
navneet-nmk/Hierarchical-Meta-Reinforcement-Learning | eval_util.py | get_generic_path_information | get_generic_path_information | Get an OrderedDict with a bunch of statistic names and values. | [
"Get",
"an",
"OrderedDict",
"with",
"a",
"bunch",
"of",
"statistic",
"names",
"and",
"values."
] | def get_generic_path_information(paths, stat_prefix=''):
statistics = OrderedDict()
returns = [sum(path['rewards']) for path in paths]
rewards = np.vstack([path['rewards'] for path in paths])
statistics.update(create_stats_ordered_dict('Rewards', rewards, stat_prefix=stat_prefix))
statistics.update(... | ['def', 'get_generic_path_information(paths,', "stat_prefix=''):", 'statistics', '=', 'OrderedDict()', 'returns', '=', "[sum(path['rewards'])", 'for', 'path', 'in', 'paths]', 'rewards', '=', "np.vstack([path['rewards']", 'for', 'path', 'in', 'paths])', "statistics.update(create_stats_ordered_dict('Rewards',", 'rewards,... | 592,936 |
paulorauber/rl | tensor_specs.py | TensorSpec.implements_for_spec | implements_for_spec | Register a torch function override for TensorSpec. | [
"Register",
"a",
"torch",
"function",
"override",
"for",
"TensorSpec."
] | def implements_for_spec(cls, torch_function: Callable) -> Callable:
@wraps(torch_function)
def decorator(func):
cls.SPEC_HANDLED_FUNCTIONS[torch_function] = func
return func
return decorator | ['def', 'implements_for_spec(cls,', 'torch_function:', 'Callable)', '->', 'Callable:', '@wraps(torch_function)', 'def', 'decorator(func):', 'cls.SPEC_HANDLED_FUNCTIONS[torch_function]', '=', 'func', 'return', 'func', 'return', 'decorator'] | 858,702 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | base.py | LocalTree.dump | dump | Writes a debug representation of this tree to the given file. | [
"Writes",
"a",
"debug",
"representation",
"of",
"this",
"tree",
"to",
"the",
"given",
"file."
] | def dump(self, fd, level=0):
extras = lambda x, y: x and x != y
(seen, nform) = (set(), '{0}{1}{2}{3}')
def innerDump(root, offset):
(token, indent) = (root.token, ' ' * offset)
(start, stop) = (root.tokenStartIndex, root.tokenStopIndex)
(idxes, ttyp) = ('', tokens.map.get(token.... | ['def', 'dump(self,', 'fd,', 'level=0):', 'extras', '=', 'lambda', 'x,', 'y:', 'x', 'and', 'x', '!=', 'y', '(seen,', 'nform)', '=', '(set(),', "'{0}{1}{2}{3}')", 'def', 'innerDump(root,', 'offset):', '(token,', 'indent)', '=', '(root.token,', "'", "'", '*', 'offset)', '(start,', 'stop)', '=', '(root.tokenStartIndex,', ... | 11,343 |
Kvatsx/Artificial-Intelligence-Assignments | channels.py | ZMQSocketChannel.get_msgs | get_msgs | Get all messages that are currently ready. | [
"Get",
"all",
"messages",
"that",
"are",
"currently",
"ready."
] | def get_msgs(self):
msgs = []
while True:
try:
msgs.append(self.get_msg(block=False))
except Empty:
break
return msgs | ['def', 'get_msgs(self):', 'msgs', '=', '[]', 'while', 'True:', 'try:', 'msgs.append(self.get_msg(block=False))', 'except', 'Empty:', 'break', 'return', 'msgs'] | 39,574 |
danamyu/hedgehog_detector | graph_builder_test.py | GraphBuilderTest.testAttachDataReader | testAttachDataReader | Checks that train['run'] and 'annotations' call AttachDataReader. | [
"Checks",
"that",
"train['run']",
"and",
"'annotations'",
"call",
"AttachDataReader."
] | def testAttachDataReader(self):
test_name = 'attach-data-reader'
with tf.Graph().as_default():
(builder, target) = self.getBuilderAndTarget(test_name)
train = builder.add_training_from_config(target)
anno = builder.add_annotation(test_name)
self.checkOpOrder('train', train['run']... | ['def', 'testAttachDataReader(self):', 'test_name', '=', "'attach-data-reader'", 'with', 'tf.Graph().as_default():', '(builder,', 'target)', '=', 'self.getBuilderAndTarget(test_name)', 'train', '=', 'builder.add_training_from_config(target)', 'anno', '=', 'builder.add_annotation(test_name)', "self.checkOpOrder('train',... | 590,587 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | stat.py | S_ISDIR | S_ISDIR | Return True if mode is from a directory. | [
"Return",
"True",
"if",
"mode",
"is",
"from",
"a",
"directory."
] | def S_ISDIR(mode):
return S_IFMT(mode) == S_IFDIR | ['def', 'S_ISDIR(mode):', 'return', 'S_IFMT(mode)', '==', 'S_IFDIR'] | 429,564 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | softplus | softplus | Let m = max(0, x), then, sofplus(x) = log(1 + e(x)) = log(e(0) + e(x)) = log(e(m)(e(-m) + e(x-m))) = m + log(e(-m) + e(x - m)) The term inside of the log is guaranteed to be between 1 and 2. | [
"Let",
"m",
"=",
"max(0,",
"x),",
"then,",
"sofplus(x)",
"=",
"log(1",
"+",
"e(x))",
"=",
"log(e(0)",
"+",
"e(x))",
"=",
"log(e(m)(e(-m)",
"+",
"e(x-m)))",
"=",
"m",
"+",
"log(e(-m)",
"+",
"e(x",
"-",
"m))",
"The",
"term",
"inside",
"of",
"the",
"log",... | def softplus(x):
m = tf.maximum(tf.zeros_like(x), x)
return m + tf.log(tf.exp(-m) + tf.exp(x - m)) | ['def', 'softplus(x):', 'm', '=', 'tf.maximum(tf.zeros_like(x),', 'x)', 'return', 'm', '+', 'tf.log(tf.exp(-m)', '+', 'tf.exp(x', '-', 'm))'] | 26,707 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.