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 |
|---|---|---|---|---|---|---|---|---|
huawei-noah/xingtian | model_zoo.py | ModelZoo.select_compressed_models | select_compressed_models | Select compressed model by model filter. | [
"Select",
"compressed",
"model",
"by",
"model",
"filter."
] | def select_compressed_models(cls, model_zoo_file, standard, num):
from zeus.model_zoo.compressed_model_filter import CompressedModelFilter
model_filter = CompressedModelFilter(model_zoo_file)
model_desc_list = model_filter.select_satisfied_model(standard, num)
return model_desc_list | ['def', 'select_compressed_models(cls,', 'model_zoo_file,', 'standard,', 'num):', 'from', 'zeus.model_zoo.compressed_model_filter', 'import', 'CompressedModelFilter', 'model_filter', '=', 'CompressedModelFilter(model_zoo_file)', 'model_desc_list', '=', 'model_filter.select_satisfied_model(standard,', 'num)', 'return', ... | 962,694 |
huawei-noah/xingtian | torch_vision_model.py | import_all_torchvision_models | import_all_torchvision_models | Import all torchvision networks and models. | [
"Import",
"all",
"torchvision",
"networks",
"and",
"models."
] | def import_all_torchvision_models():
def _register_models_from_current_module_scope(module):
for _name in dir(module):
if _name.startswith('_'):
continue
_cls = getattr(module, _name)
if isinstance(_cls, ModuleType):
continue
i... | ['def', 'import_all_torchvision_models():', 'def', '_register_models_from_current_module_scope(module):', 'for', '_name', 'in', 'dir(module):', 'if', "_name.startswith('_'):", 'continue', '_cls', '=', 'getattr(module,', '_name)', 'if', 'isinstance(_cls,', 'ModuleType):', 'continue', 'if', 'ClassFactory.is_exists(ClassT... | 962,695 |
huawei-noah/xingtian | __init__.py | register_modelzoo | register_modelzoo | Import and register modelzoo automatically. | [
"Import",
"and",
"register",
"modelzoo",
"automatically."
] | def register_modelzoo(backend):
if backend != 'pytorch':
return
from .torch_vision_model import import_all_torchvision_models
import logging
try:
import_all_torchvision_models()
except Exception as e:
logging.warn('Failed to import torchvision models, msg={}'.format(str(e))) | ['def', 'register_modelzoo(backend):', 'if', 'backend', '!=', "'pytorch':", 'return', 'from', '.torch_vision_model', 'import', 'import_all_torchvision_models', 'import', 'logging', 'try:', 'import_all_torchvision_models()', 'except', 'Exception', 'as', 'e:', "logging.warn('Failed", 'to', 'import', 'torchvision', 'model... | 962,696 |
huawei-noah/xingtian | module.py | Module.set_module | set_module | Set Models by name. | [
"Set",
"Models",
"by",
"name."
] | def set_module(self, names, layer):
parent_model = self
if not isinstance(names, list):
names_path = names.split('.')
else:
names_path = deepcopy(names)
next_names = names_path.pop(0)
if not names_path:
self.add_module(names[0], layer)
else:
next_model = getattr(p... | ['def', 'set_module(self,', 'names,', 'layer):', 'parent_model', '=', 'self', 'if', 'not', 'isinstance(names,', 'list):', 'names_path', '=', "names.split('.')", 'else:', 'names_path', '=', 'deepcopy(names)', 'next_names', '=', 'names_path.pop(0)', 'if', 'not', 'names_path:', 'self.add_module(names[0],', 'layer)', 'else... | 962,698 |
huawei-noah/xingtian | module.py | Module.add_loss | add_loss | Add a loss function into module. | [
"Add",
"a",
"loss",
"function",
"into",
"module."
] | def add_loss(self, loss):
self._losses[loss.__class__.__name__] = loss | ['def', 'add_loss(self,', 'loss):', 'self._losses[loss.__class__.__name__]', '=', 'loss'] | 962,699 |
huawei-noah/xingtian | module.py | Module.pretrained_hook | pretrained_hook | Define pretrained hook function or pertrained file path. | [
"Define",
"pretrained",
"hook",
"function",
"or",
"pertrained",
"file",
"path."
] | def pretrained_hook(self):
return None | ['def', 'pretrained_hook(self):', 'return', 'None'] | 962,700 |
huawei-noah/xingtian | module.py | Module.overall_loss | overall_loss | Call loss function, default sum all losses. | [
"Call",
"loss",
"function,",
"default",
"sum",
"all",
"losses."
] | def overall_loss(self):
self._create_loss()
from zeus.modules.loss.multiloss import MultiLoss
return MultiLoss(*list(self._losses.values())) | ['def', 'overall_loss(self):', 'self._create_loss()', 'from', 'zeus.modules.loss.multiloss', 'import', 'MultiLoss', 'return', 'MultiLoss(*list(self._losses.values()))'] | 962,703 |
huawei-noah/xingtian | __init__.py | register_modules | register_modules | Import and register modules automatically. | [
"Import",
"and",
"register",
"modules",
"automatically."
] | def register_modules():
from . import blocks
from . import cells
from . import connections
from . import operators
from . import preprocess
from . import loss | ['def', 'register_modules():', 'from', '.', 'import', 'blocks', 'from', '.', 'import', 'cells', 'from', '.', 'import', 'connections', 'from', '.', 'import', 'operators', 'from', '.', 'import', 'preprocess', 'from', '.', 'import', 'loss'] | 962,704 |
huawei-noah/xingtian | micro_decoder.py | InvertedResidual.call | call | Do an inference on InvertedResidual. | [
"Do",
"an",
"inference",
"on",
"InvertedResidual."
] | def call(self, inputs):
if self.user_res_connect:
return inputs + self.conv(inputs)
else:
return self.conv(inputs) | ['def', 'call(self,', 'inputs):', 'if', 'self.user_res_connect:', 'return', 'inputs', '+', 'self.conv(inputs)', 'else:', 'return', 'self.conv(inputs)'] | 962,707 |
huawei-noah/xingtian | connections.py | create_module | create_module | Create search space from model or desc. | [
"Create",
"search",
"space",
"from",
"model",
"or",
"desc."
] | def create_module(model):
if isinstance(model, Module):
return (model.__class__.__name__, model)
elif isinstance(model, dict):
module_type = model.get('type')
module_param = deepcopy(model)
module_param.pop('type')
module = ClassFactory.get_cls(ClassType.NETWORK, module_t... | ['def', 'create_module(model):', 'if', 'isinstance(model,', 'Module):', 'return', '(model.__class__.__name__,', 'model)', 'elif', 'isinstance(model,', 'dict):', 'module_type', '=', "model.get('type')", 'module_param', '=', 'deepcopy(model)', "module_param.pop('type')", 'module', '=', 'ClassFactory.get_cls(ClassType.NET... | 962,709 |
huawei-noah/xingtian | connections.py | MultiOutputGetter.call | call | Override call function, connect models into a OrderedDict. | [
"Override",
"call",
"function,",
"connect",
"models",
"into",
"a",
"OrderedDict."
] | def call(self, inputs):
output = inputs
outs = OrderedDict()
for (name, model) in self.named_children():
output = model(output)
if name in self.output_layers:
outs[self.output_layers[name]] = output
return outs | ['def', 'call(self,', 'inputs):', 'output', '=', 'inputs', 'outs', '=', 'OrderedDict()', 'for', '(name,', 'model)', 'in', 'self.named_children():', 'output', '=', 'model(output)', 'if', 'name', 'in', 'self.output_layers:', 'outs[self.output_layers[name]]', '=', 'output', 'return', 'outs'] | 962,711 |
huawei-noah/xingtian | connections.py | OutlistSequential.call | call | Override compile function, conect models into a seq. | [
"Override",
"compile",
"function,",
"conect",
"models",
"into",
"a",
"seq."
] | def call(self, inputs):
output = inputs
models = self.children()
outputs = []
for (idx, model) in enumerate(models):
output = model(output)
if idx in self.out_list:
outputs.append(output)
return outputs | ['def', 'call(self,', 'inputs):', 'output', '=', 'inputs', 'models', '=', 'self.children()', 'outputs', '=', '[]', 'for', '(idx,', 'model)', 'in', 'enumerate(models):', 'output', '=', 'model(output)', 'if', 'idx', 'in', 'self.out_list:', 'outputs.append(output)', 'return', 'outputs'] | 962,712 |
huawei-noah/xingtian | connections.py | MultiOutput.add | add | Add a module into MultiOutput. | [
"Add",
"a",
"module",
"into",
"MultiOutput."
] | def add(self, module):
self.add_module(str(len(self._modules.values())), module) | ['def', 'add(self,', 'module):', 'self.add_module(str(len(self._modules.values())),', 'module)'] | 962,713 |
huawei-noah/xingtian | connections.py | MultiOutput.call | call | Override compile function, connect models into a seq. | [
"Override",
"compile",
"function,",
"connect",
"models",
"into",
"a",
"seq."
] | def call(self, inputs):
models = list(self.children())
if not models:
return None
input_model = models.pop(0)
x = input_model(inputs)
outputs = []
for (idx, model) in enumerate(models):
outputs.append(model(x))
if self.out_func is not None:
outputs = self.out_func(out... | ['def', 'call(self,', 'inputs):', 'models', '=', 'list(self.children())', 'if', 'not', 'models:', 'return', 'None', 'input_model', '=', 'models.pop(0)', 'x', '=', 'input_model(inputs)', 'outputs', '=', '[]', 'for', '(idx,', 'model)', 'in', 'enumerate(models):', 'outputs.append(model(x))', 'if', 'self.out_func', 'is', '... | 962,714 |
huawei-noah/xingtian | multiloss.py | MultiLoss.call | call | Sum all loss of predict and groundtruth. | [
"Sum",
"all",
"loss",
"of",
"predict",
"and",
"groundtruth."
] | def call(self, output, target):
outputs = None
for model in self.loss_fn:
if outputs is None:
outputs = model(output, target)
else:
outputs = outputs + model(output, target)
return outputs | ['def', 'call(self,', 'output,', 'target):', 'outputs', '=', 'None', 'for', 'model', 'in', 'self.loss_fn:', 'if', 'outputs', 'is', 'None:', 'outputs', '=', 'model(output,', 'target)', 'else:', 'outputs', '=', 'outputs', '+', 'model(output,', 'target)', 'return', 'outputs'] | 962,720 |
huawei-noah/xingtian | conv.py | conv_bn_relu6 | conv_bn_relu6 | Create group of Convolution + BN + Relu6 function. | [
"Create",
"group",
"of",
"Convolution",
"+",
"BN",
"+",
"Relu6",
"function."
] | def conv_bn_relu6(C_in, C_out, kernel_size=3, stride=1, padding=0, affine=True):
return ConvBnRelu(C_in, C_out, kernel_size, stride, padding, affine=affine, use_relu6=True) | ['def', 'conv_bn_relu6(C_in,', 'C_out,', 'kernel_size=3,', 'stride=1,', 'padding=0,', 'affine=True):', 'return', 'ConvBnRelu(C_in,', 'C_out,', 'kernel_size,', 'stride,', 'padding,', 'affine=affine,', 'use_relu6=True)'] | 962,726 |
huawei-noah/xingtian | conv.py | FactorizedReduce.call | call | Do an inference on FactorizedReduce. | [
"Do",
"an",
"inference",
"on",
"FactorizedReduce."
] | def call(self, x):
x = self.relu(x)
out = ops.concat(tuple([self.conv_1(x), self.conv_2(x[:, :, 1:, 1:])]))
out = self.bn(out)
return out | ['def', 'call(self,', 'x):', 'x', '=', 'self.relu(x)', 'out', '=', 'ops.concat(tuple([self.conv_1(x),', 'self.conv_2(x[:,', ':,', '1:,', '1:])]))', 'out', '=', 'self.bn(out)', 'return', 'out'] | 962,728 |
huawei-noah/xingtian | prune.py | parse_module_name | parse_module_name | Parse the module name of mindspore. | [
"Parse",
"the",
"module",
"name",
"of",
"mindspore."
] | def parse_module_name(name, module):
if zeus.is_ms_backend():
while list(module.cells()) != []:
module = list(module.cells())[0]
name_list = name.split('/')[1:]
new_name = ''
for name in name_list:
name = '.' + name.split('-')[0]
new_name += name
... | ['def', 'parse_module_name(name,', 'module):', 'if', 'zeus.is_ms_backend():', 'while', 'list(module.cells())', '!=', '[]:', 'module', '=', 'list(module.cells())[0]', 'name_list', '=', "name.split('/')[1:]", 'new_name', '=', "''", 'for', 'name', 'in', 'name_list:', 'name', '=', "'.'", '+', "name.split('-')[0]", 'new_nam... | 962,730 |
huawei-noah/xingtian | prune.py | PruneConv2D.apply | apply | Apply mask to weight. | [
"Apply",
"mask",
"to",
"weight."
] | def apply(self, end_mask_code, start_mask_code=None):
end_mask_code = np.array(end_mask_code)
if start_mask_code is not None:
start_mask_code = np.array(start_mask_code)
start_channel_idx = None
end_channel_idx = np.squeeze(np.argwhere(np.asarray(np.ones(end_mask_code.shape) - end_mask_code))).t... | ['def', 'apply(self,', 'end_mask_code,', 'start_mask_code=None):', 'end_mask_code', '=', 'np.array(end_mask_code)', 'if', 'start_mask_code', 'is', 'not', 'None:', 'start_mask_code', '=', 'np.array(start_mask_code)', 'start_channel_idx', '=', 'None', 'end_channel_idx', '=', 'np.squeeze(np.argwhere(np.asarray(np.ones(end... | 962,731 |
huawei-noah/xingtian | prune.py | PruneLinear.apply | apply | Apply mask to linear. | [
"Apply",
"mask",
"to",
"linear."
] | def apply(self, mask_code):
mask_code = np.asarray(mask_code)
idx = np.squeeze(np.argwhere(np.asarray(np.ones(mask_code.shape) - mask_code))).tolist()
self._make_mask(idx)
if zeus.is_tf_backend():
import tensorflow as tf
return tf.assign(self.layer, self.layer * tf.constant(self.mask, dt... | ['def', 'apply(self,', 'mask_code):', 'mask_code', '=', 'np.asarray(mask_code)', 'idx', '=', 'np.squeeze(np.argwhere(np.asarray(np.ones(mask_code.shape)', '-', 'mask_code))).tolist()', 'self._make_mask(idx)', 'if', 'zeus.is_tf_backend():', 'import', 'tensorflow', 'as', 'tf', 'return', 'tf.assign(self.layer,', 'self.lay... | 962,733 |
huawei-noah/xingtian | mindspore_fn.py | zeros | zeros | Create zeros like shape. | [
"Create",
"zeros",
"like",
"shape."
] | def zeros(shape):
return Tensor(np.zeros(tuple(shape), np.float32)) | ['def', 'zeros(shape):', 'return', 'Tensor(np.zeros(tuple(shape),', 'np.float32))'] | 962,739 |
huawei-noah/xingtian | mindspore_fn.py | mul | mul | Call mul according to backends. | [
"Call",
"mul",
"according",
"to",
"backends."
] | def mul(a, b):
return P.Mul()(a, b) | ['def', 'mul(a,', 'b):', 'return', 'P.Mul()(a,', 'b)'] | 962,741 |
huawei-noah/xingtian | mindspore_fn.py | random_normal | random_normal | Apply random values from a normal distribution. | [
"Apply",
"random",
"values",
"from",
"a",
"normal",
"distribution."
] | def random_normal(*size):
return Tensor(np.random.randn(*size).astype(np.float32)) | ['def', 'random_normal(*size):', 'return', 'Tensor(np.random.randn(*size).astype(np.float32))'] | 962,743 |
huawei-noah/xingtian | mindspore_fn.py | softmax | softmax | Apply a softmax function. | [
"Apply",
"a",
"softmax",
"function."
] | def softmax(input, dim=-1):
return nn.Softmax(axis=dim)(input) | ['def', 'softmax(input,', 'dim=-1):', 'return', 'nn.Softmax(axis=dim)(input)'] | 962,744 |
huawei-noah/xingtian | mindspore_fn.py | gumbel_softmax | gumbel_softmax | Apply a gumbel softmax function. | [
"Apply",
"a",
"gumbel",
"softmax",
"function."
] | def gumbel_softmax(input, dim=-1, tau=1, hard=True, eps=1e-20):
raise NotImplementedError | ['def', 'gumbel_softmax(input,', 'dim=-1,', 'tau=1,', 'hard=True,', 'eps=1e-20):', 'raise', 'NotImplementedError'] | 962,745 |
huawei-noah/xingtian | mindspore_fn.py | Conv2d.initial | initial | Initialize weight and bias. | [
"Initialize",
"weight",
"and",
"bias."
] | def initial(self, kernel_mode='he', bias_mode='zero', kernel_scale=1.0, bias_scale=1.0):
return | ['def', 'initial(self,', "kernel_mode='he',", "bias_mode='zero',", 'kernel_scale=1.0,', 'bias_scale=1.0):', 'return'] | 962,765 |
huawei-noah/xingtian | mindspore_fn.py | Dropout.construct | construct | Do an inference on Dropout. | [
"Do",
"an",
"inference",
"on",
"Dropout."
] | def construct(self, x, **kwargs):
return x | ['def', 'construct(self,', 'x,', '**kwargs):', 'return', 'x'] | 962,767 |
huawei-noah/xingtian | pytorch_fn.py | where | where | Return index by condition. | [
"Return",
"index",
"by",
"condition."
] | def where(cond):
return torch.nonzero(cond) | ['def', 'where(cond):', 'return', 'torch.nonzero(cond)'] | 962,781 |
huawei-noah/xingtian | pytorch_fn.py | compare_where | compare_where | Return item by condition. | [
"Return",
"item",
"by",
"condition."
] | def compare_where(cond, x, y):
return torch.where(cond, x, y) | ['def', 'compare_where(cond,', 'x,', 'y):', 'return', 'torch.where(cond,', 'x,', 'y)'] | 962,787 |
huawei-noah/xingtian | pytorch_fn.py | pow | pow | Calculate the exponent value of the input by element and returns the result tensor. | [
"Calculate",
"the",
"exponent",
"value",
"of",
"the",
"input",
"by",
"element",
"and",
"returns",
"the",
"result",
"tensor."
] | def pow(input, exponent, out=None):
return torch.pow(input, exponent, out=out) | ['def', 'pow(input,', 'exponent,', 'out=None):', 'return', 'torch.pow(input,', 'exponent,', 'out=out)'] | 962,788 |
huawei-noah/xingtian | pytorch_fn.py | Module.load_state_dict | load_state_dict | Load state dict from state_dict or file. | [
"Load",
"state",
"dict",
"from",
"state_dict",
"or",
"file."
] | def load_state_dict(self, state_dict=None, strict=None, file_path=None):
state_dict = torch.load(file_path) if file_path is not None else state_dict
self.strict = strict if strict is not None else self.strict
super().load_state_dict(state_dict, self.strict) | ['def', 'load_state_dict(self,', 'state_dict=None,', 'strict=None,', 'file_path=None):', 'state_dict', '=', 'torch.load(file_path)', 'if', 'file_path', 'is', 'not', 'None', 'else', 'state_dict', 'self.strict', '=', 'strict', 'if', 'strict', 'is', 'not', 'None', 'else', 'self.strict', 'super().load_state_dict(state_dict... | 962,795 |
huawei-noah/xingtian | pytorch_fn.py | QuantizeConv2d.forward | forward | Do an inference on Identity. | [
"Do",
"an",
"inference",
"on",
"Identity."
] | def forward(self, input):
input = input.cpu()
input = torch.quantize_per_tensor(input, 1.0, 0, self._quant_type[self.quant_bit])
output = super().forward(input)
output = torch.dequantize(output).cuda()
return output | ['def', 'forward(self,', 'input):', 'input', '=', 'input.cpu()', 'input', '=', 'torch.quantize_per_tensor(input,', '1.0,', '0,', 'self._quant_type[self.quant_bit])', 'output', '=', 'super().forward(input)', 'output', '=', 'torch.dequantize(output).cuda()', 'return', 'output'] | 962,796 |
huawei-noah/xingtian | pytorch_fn.py | Relu6.forward | forward | Do an inference on Relu6. | [
"Do",
"an",
"inference",
"on",
"Relu6."
] | def forward(self, x):
return super().forward(x) | ['def', 'forward(self,', 'x):', 'return', 'super().forward(x)'] | 962,803 |
huawei-noah/xingtian | pytorch_fn.py | AdaptiveAvgPool2d.forward | forward | Do an inference on AdaptiveAvgPool2d. | [
"Do",
"an",
"inference",
"on",
"AdaptiveAvgPool2d."
] | def forward(self, x):
return super().forward(x) | ['def', 'forward(self,', 'x):', 'return', 'super().forward(x)'] | 962,804 |
huawei-noah/xingtian | pytorch_fn.py | Linear.forward | forward | Do an inference on Linear. | [
"Do",
"an",
"inference",
"on",
"Linear."
] | def forward(self, x):
out = super().forward(x)
if self.activation == 'softmax':
return F.softmax(out)
return out | ['def', 'forward(self,', 'x):', 'out', '=', 'super().forward(x)', 'if', 'self.activation', '==', "'softmax':", 'return', 'F.softmax(out)', 'return', 'out'] | 962,805 |
huawei-noah/xingtian | pytorch_fn.py | Transpose.forward | forward | Forward function of Transpose. | [
"Forward",
"function",
"of",
"Transpose."
] | def forward(self, inputs):
return torch.transpose(inputs, self.dim1, self.dim2).contiguous() | ['def', 'forward(self,', 'inputs):', 'return', 'torch.transpose(inputs,', 'self.dim1,', 'self.dim2).contiguous()'] | 962,809 |
huawei-noah/xingtian | pytorch_fn.py | ConvWS2d.forward | forward | Forward function of conv2d with weight standarlization. | [
"Forward",
"function",
"of",
"conv2d",
"with",
"weight",
"standarlization."
] | def forward(self, x):
return conv_ws_2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups, self.eps) | ['def', 'forward(self,', 'x):', 'return', 'conv_ws_2d(x,', 'self.weight,', 'self.bias,', 'self.stride,', 'self.padding,', 'self.dilation,', 'self.groups,', 'self.eps)'] | 962,813 |
huawei-noah/xingtian | pytorch_to_tf.py | assign_pytorch_weights | assign_pytorch_weights | Assign pytorch weights to tf model. | [
"Assign",
"pytorch",
"weights",
"to",
"tf",
"model."
] | def assign_pytorch_weights(pretrained_model_file, pretrained_prefix=None):
import torch
checkpoint = torch.load(pretrained_model_file)
return assign_weights(checkpoint, pretrained_prefix) | ['def', 'assign_pytorch_weights(pretrained_model_file,', 'pretrained_prefix=None):', 'import', 'torch', 'checkpoint', '=', 'torch.load(pretrained_model_file)', 'return', 'assign_weights(checkpoint,', 'pretrained_prefix)'] | 962,814 |
huawei-noah/xingtian | pytorch_to_tf.py | assign_weights | assign_weights | Load pytorch state_dict and assign to tensorflow model. | [
"Load",
"pytorch",
"state_dict",
"and",
"assign",
"to",
"tensorflow",
"model."
] | def assign_weights(pt_state_dict, pretrained_prefix=None):
import tensorflow as tf
vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
vars.pop(0)
pt_state_dict = {k: v for (k, v) in pt_state_dict.items() if 'num_batches_tracked' not in k}
def _filter_vars_by_keys(var):
for key in pretr... | ['def', 'assign_weights(pt_state_dict,', 'pretrained_prefix=None):', 'import', 'tensorflow', 'as', 'tf', 'vars', '=', 'tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)', 'vars.pop(0)', 'pt_state_dict', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'pt_state_dict.items()', 'if', "'num_batches_tracked'", 'not', 'in', 'k}', ... | 962,815 |
huawei-noah/xingtian | pytorch_to_tf.py | convert_name | convert_name | Convert a TF variable name in a pytorch model weight name. | [
"Convert",
"a",
"TF",
"variable",
"name",
"in",
"a",
"pytorch",
"model",
"weight",
"name."
] | def convert_name(tf_name, start_prefix_to_remove=''):
tf_name = tf_name.replace(':0', '')
tf_name = re.sub('/[^/]*___([^/]*)/', '/\\1/', tf_name)
tf_name = tf_name.replace('_._', '/')
tf_name = re.sub('//+', '/', tf_name)
tf_name = tf_name.split('/')
tf_name = tf_name[1:]
transpose = bool(tf... | ['def', 'convert_name(tf_name,', "start_prefix_to_remove=''):", 'tf_name', '=', "tf_name.replace(':0',", "'')", 'tf_name', '=', "re.sub('/[^/]*___([^/]*)/',", "'/\\\\1/',", 'tf_name)', 'tf_name', '=', "tf_name.replace('_._',", "'/')", 'tf_name', '=', "re.sub('//+',", "'/',", 'tf_name)', 'tf_name', '=', "tf_name.split('... | 962,816 |
huawei-noah/xingtian | serializable.py | OperatorSerializable.from_desc | from_desc | Create Operator class by desc. | [
"Create",
"Operator",
"class",
"by",
"desc."
] | def from_desc(cls, desc):
return ClassFactory.get_instance(ClassType.NETWORK, desc) | ['def', 'from_desc(cls,', 'desc):', 'return', 'ClassFactory.get_instance(ClassType.NETWORK,', 'desc)'] | 962,823 |
huawei-noah/xingtian | serializable.py | ModuleSerializable.update_from_desc | update_from_desc | Update desc according to desc. | [
"Update",
"desc",
"according",
"to",
"desc."
] | def update_from_desc(self, desc):
for (key, value) in desc.items():
if key == 'type' or not hasattr(self, key):
continue
child_module = getattr(self, key)
if hasattr(child_module, 'add_module'):
self.add_module(key, value)
else:
child_module.update... | ['def', 'update_from_desc(self,', 'desc):', 'for', '(key,', 'value)', 'in', 'desc.items():', 'if', 'key', '==', "'type'", 'or', 'not', 'hasattr(self,', 'key):', 'continue', 'child_module', '=', 'getattr(self,', 'key)', 'if', 'hasattr(child_module,', "'add_module'):", 'self.add_module(key,', 'value)', 'else:', 'child_mo... | 962,825 |
huawei-noah/xingtian | serializable.py | ModuleSerializable.from_desc | from_desc | Create Model from desc. | [
"Create",
"Model",
"from",
"desc."
] | def from_desc(cls, desc):
desc = deepcopy(desc)
module_groups = desc.get('modules', [])
module_type = desc.get('type', 'Sequential')
loss = desc.get('loss')
if 'props' in desc:
Props.update(desc.pop('props'))
modules = OrderedDict()
for group_name in module_groups:
module_des... | ['def', 'from_desc(cls,', 'desc):', 'desc', '=', 'deepcopy(desc)', 'module_groups', '=', "desc.get('modules',", '[])', 'module_type', '=', "desc.get('type',", "'Sequential')", 'loss', '=', "desc.get('loss')", 'if', "'props'", 'in', 'desc:', "Props.update(desc.pop('props'))", 'modules', '=', 'OrderedDict()', 'for', 'gro... | 962,826 |
huawei-noah/xingtian | tensorflow_fn.py | gumbel_softmax_sample | gumbel_softmax_sample | Draw a sample from the Gumbel-Softmax distribution. | [
"Draw",
"a",
"sample",
"from",
"the",
"Gumbel-Softmax",
"distribution."
] | def gumbel_softmax_sample(input, temperature, eps=1e-20):
shape = tf.shape(input)
U = tf.random_uniform(shape, minval=0, maxval=1)
U = -tf.log(-tf.log(U + eps) + eps)
y = input + U
return tf.nn.softmax(y / temperature) | ['def', 'gumbel_softmax_sample(input,', 'temperature,', 'eps=1e-20):', 'shape', '=', 'tf.shape(input)', 'U', '=', 'tf.random_uniform(shape,', 'minval=0,', 'maxval=1)', 'U', '=', '-tf.log(-tf.log(U', '+', 'eps)', '+', 'eps)', 'y', '=', 'input', '+', 'U', 'return', 'tf.nn.softmax(y', '/', 'temperature)'] | 962,832 |
huawei-noah/xingtian | tensorflow_fn.py | Module.children | children | Get child models of current Module. | [
"Get",
"child",
"models",
"of",
"current",
"Module."
] | def children(self):
for model in self._modules.values():
if isinstance(model, Module):
model._scope_name = '{}.{}'.format(self._scope_name, model.parent_scope_name) if self._scope_name else model.parent_scope_name
yield model | ['def', 'children(self):', 'for', 'model', 'in', 'self._modules.values():', 'if', 'isinstance(model,', 'Module):', 'model._scope_name', '=', "'{}.{}'.format(self._scope_name,", 'model.parent_scope_name)', 'if', 'self._scope_name', 'else', 'model.parent_scope_name', 'yield', 'model'] | 962,853 |
huawei-noah/xingtian | tensorflow_fn.py | Module.get_weights | get_weights | Get weights by name. | [
"Get",
"weights",
"by",
"name."
] | def get_weights(self, name):
return tf.get_default_graph().get_tensor_by_name('{}:0'.format(name)) | ['def', 'get_weights(self,', 'name):', 'return', "tf.get_default_graph().get_tensor_by_name('{}:0'.format(name))"] | 962,854 |
huawei-noah/xingtian | pytorch_quant.py | QuantConv.reset_custome_parameters | reset_custome_parameters | Reset the parameters customely. | [
"Reset",
"the",
"parameters",
"customely."
] | def reset_custome_parameters(self):
nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
nn.init.constant_(self.bias, 0) | ['def', 'reset_custome_parameters(self):', 'nn.init.kaiming_uniform_(self.weight,', 'a=math.sqrt(5))', 'if', 'self.bias', 'is', 'not', 'None:', 'nn.init.constant_(self.bias,', '0)'] | 962,881 |
huawei-noah/xingtian | output.py | BertSelfOutput.call | call | Call Bert Self Output. | [
"Call",
"Bert",
"Self",
"Output."
] | def call(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states | ['def', 'call(self,', 'hidden_states,', 'input_tensor):', 'hidden_states', '=', 'self.dense(hidden_states)', 'hidden_states', '=', 'self.dropout(hidden_states)', 'hidden_states', '=', 'self.LayerNorm(hidden_states', '+', 'input_tensor)', 'return', 'hidden_states'] | 962,899 |
huawei-noah/xingtian | pooler.py | Pooler.call | call | Get token and pooling. | [
"Get",
"token",
"and",
"pooling."
] | def call(self, hidden_states):
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output | ['def', 'call(self,', 'hidden_states):', 'first_token_tensor', '=', 'hidden_states[:,', '0]', 'pooled_output', '=', 'self.dense(first_token_tensor)', 'pooled_output', '=', 'self.activation(pooled_output)', 'return', 'pooled_output'] | 962,902 |
huawei-noah/xingtian | adelaide.py | AdelaideFastNAS.call | call | Do an inference on AdelaideFastNAS model. | [
"Do",
"an",
"inference",
"on",
"AdelaideFastNAS",
"model."
] | def call(self, inputs):
self.head.size = ops.get_shape(inputs)[2:]
return super().call(inputs) | ['def', 'call(self,', 'inputs):', 'self.head.size', '=', 'ops.get_shape(inputs)[2:]', 'return', 'super().call(inputs)'] | 962,903 |
huawei-noah/xingtian | model_config.py | ModelConfig.from_json | from_json | Restore config from a dictionary or a file. | [
"Restore",
"config",
"from",
"a",
"dictionary",
"or",
"a",
"file."
] | def from_json(cls, data, skip_check=True):
t_cls = super(ModelConfig, cls).from_json(data, skip_check)
if data.get('models_folder') and (not data.get('model_desc')):
folder = data.models_folder.replace('{local_base_path}', os.path.join(TaskConfig.local_base_path, TaskConfig.task_id))
pattern = F... | ['def', 'from_json(cls,', 'data,', 'skip_check=True):', 't_cls', '=', 'super(ModelConfig,', 'cls).from_json(data,', 'skip_check)', 'if', "data.get('models_folder')", 'and', '(not', "data.get('model_desc')):", 'folder', '=', "data.models_folder.replace('{local_base_path}',", 'os.path.join(TaskConfig.local_base_path,', '... | 962,911 |
huawei-noah/xingtian | network_desc.py | NetworkDesc.to_model | to_model | Transform a NetworkDesc to a special model. | [
"Transform",
"a",
"NetworkDesc",
"to",
"a",
"special",
"model."
] | def to_model(self):
logging.debug('Start to Create a Network.')
model = Module.from_desc(self._desc)
if not model:
raise Exception('Failed to create model, model desc={}'.format(self._desc))
model.desc = self._desc
return model | ['def', 'to_model(self):', "logging.debug('Start", 'to', 'Create', 'a', "Network.')", 'model', '=', 'Module.from_desc(self._desc)', 'if', 'not', 'model:', 'raise', "Exception('Failed", 'to', 'create', 'model,', 'model', "desc={}'.format(self._desc))", 'model.desc', '=', 'self._desc', 'return', 'model'] | 962,921 |
huawei-noah/xingtian | quant.py | Quantizer.custom_hooks | custom_hooks | Calculate flops and params. | [
"Calculate",
"flops",
"and",
"params."
] | def custom_hooks(self):
return quant.quant_custom_ops() | ['def', 'custom_hooks(self):', 'return', 'quant.quant_custom_ops()'] | 962,922 |
huawei-noah/xingtian | resnet_det.py | ResNetDet.call | call | Forward compute of resnet for detection. | [
"Forward",
"compute",
"of",
"resnet",
"for",
"detection."
] | def call(self, x, **kwargs):
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = self.res_layers_seq(x)
return tuple(outs) | ['def', 'call(self,', 'x,', '**kwargs):', 'x', '=', 'self.conv1(x)', 'x', '=', 'self.norm1(x)', 'x', '=', 'self.relu(x)', 'x', '=', 'self.maxpool(x)', 'outs', '=', 'self.res_layers_seq(x)', 'return', 'tuple(outs)'] | 962,923 |
huawei-noah/xingtian | resnet_general.py | ResNetGeneral.prune_setting | prune_setting | Prune setting if possible. | [
"Prune",
"setting",
"if",
"possible."
] | def prune_setting(self):
node_channels = self.desc.get('chn_node', None)
if node_channels is None:
return None
self.inner_channels = self.desc.get('chn', None)
self.block_type = 'PruneBasicBlock'
return node_channels | ['def', 'prune_setting(self):', 'node_channels', '=', "self.desc.get('chn_node',", 'None)', 'if', 'node_channels', 'is', 'None:', 'return', 'None', 'self.inner_channels', '=', "self.desc.get('chn',", 'None)', 'self.block_type', '=', "'PruneBasicBlock'", 'return', 'node_channels'] | 962,924 |
huawei-noah/xingtian | sgas_network.py | SGASNetwork.learnable_params | learnable_params | Get learnable params of alphas. | [
"Get",
"learnable",
"params",
"of",
"alphas."
] | def learnable_params(self):
return self.alphas_normal + self.alphas_reduce | ['def', 'learnable_params(self):', 'return', 'self.alphas_normal', '+', 'self.alphas_reduce'] | 962,928 |
huawei-noah/xingtian | text_cnn.py | TextCells.out_channels | out_channels | Output Channel for ResNet backbone. | [
"Output",
"Channel",
"for",
"ResNet",
"backbone."
] | def out_channels(self):
last_channel = super().out_channels
return len(self.kernels) * last_channel | ['def', 'out_channels(self):', 'last_channel', '=', 'super().out_channels', 'return', 'len(self.kernels)', '*', 'last_channel'] | 962,937 |
huawei-noah/xingtian | __init__.py | register_networks | register_networks | Import and register network automatically. | [
"Import",
"and",
"register",
"network",
"automatically."
] | def register_networks(backend):
from .network_desc import NetworkDesc
from .adelaide import AdelaideFastNAS
from .erdb_esr import ESRN
from .mobilenet import MobileNetV3Tiny, MobileNetV2Tiny
from .mobilenetv3 import MobileNetV3Small, MobileNetV3Large
from .sgas_network import SGASNetwork
fro... | ['def', 'register_networks(backend):', 'from', '.network_desc', 'import', 'NetworkDesc', 'from', '.adelaide', 'import', 'AdelaideFastNAS', 'from', '.erdb_esr', 'import', 'ESRN', 'from', '.mobilenet', 'import', 'MobileNetV3Tiny,', 'MobileNetV2Tiny', 'from', '.mobilenetv3', 'import', 'MobileNetV3Small,', 'MobileNetV3Larg... | 962,938 |
huawei-noah/xingtian | load_official_model.py | OffcialModelLoader.construct | construct | Forward of the network. | [
"Forward",
"of",
"the",
"network."
] | def construct(self, inputs):
output = inputs
for (name, module) in self.model.name_cells().items():
output = module(output)
if name == self.output_layer_names:
return output
return output | ['def', 'construct(self,', 'inputs):', 'output', '=', 'inputs', 'for', '(name,', 'module)', 'in', 'self.model.name_cells().items():', 'output', '=', 'module(output)', 'if', 'name', '==', 'self.output_layer_names:', 'return', 'output', 'return', 'output'] | 962,939 |
huawei-noah/xingtian | load_official_model.py | OffcialModelLoader.get_all_layer_names | get_all_layer_names | Get all the layers name excluding the parent. | [
"Get",
"all",
"the",
"layers",
"name",
"excluding",
"the",
"parent."
] | def get_all_layer_names(self):
names_list = [name for (name, _) in self.model.cells_and_names()]
valid_names = []
for index in range(len(names_list) - 1):
cur_name = names_list[index]
next_name = names_list[index + 1]
if cur_name != '' and (not self.is_sub_list(cur_name.split('.'), n... | ['def', 'get_all_layer_names(self):', 'names_list', '=', '[name', 'for', '(name,', '_)', 'in', 'self.model.cells_and_names()]', 'valid_names', '=', '[]', 'for', 'index', 'in', 'range(len(names_list)', '-', '1):', 'cur_name', '=', 'names_list[index]', 'next_name', '=', 'names_list[index', '+', '1]', 'if', 'cur_name', '!... | 962,942 |
huawei-noah/xingtian | simple_cnn.py | conv | conv | Conv layer weight initial. | [
"Conv",
"layer",
"weight",
"initial."
] | def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
weight = weight_variable()
return nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, weight_init=weight, has_bias=False, pad_mode='same') | ['def', 'conv(in_channels,', 'out_channels,', 'kernel_size,', 'stride=1,', 'padding=0):', 'weight', '=', 'weight_variable()', 'return', 'nn.Conv2d(in_channels,', 'out_channels,', 'kernel_size=kernel_size,', 'stride=stride,', 'padding=padding,', 'weight_init=weight,', 'has_bias=False,', "pad_mode='same')"] | 962,945 |
huawei-noah/xingtian | conv_module.py | ConvModule.init_weight | init_weight | Init weight of Conv Module with Normalization. | [
"Init",
"weight",
"of",
"Conv",
"Module",
"with",
"Normalization."
] | def init_weight(self):
nonlinearity = 'relu' if self.activation is None else self.activation
nn.init.kaiming_normal_(self.conv.weight, nonlinearity=nonlinearity)
if hasattr(self.conv, 'bias') and self.conv.bias is not None:
nn.init.constant_(self.conv.bias, 0)
if self.with_norm:
nn.init.... | ['def', 'init_weight(self):', 'nonlinearity', '=', "'relu'", 'if', 'self.activation', 'is', 'None', 'else', 'self.activation', 'nn.init.kaiming_normal_(self.conv.weight,', 'nonlinearity=nonlinearity)', 'if', 'hasattr(self.conv,', "'bias')", 'and', 'self.conv.bias', 'is', 'not', 'None:', 'nn.init.constant_(self.conv.bia... | 962,963 |
huawei-noah/xingtian | evolveresnet.py | build_spatial_path | build_spatial_path | Call the function to build spatial layers. | [
"Call",
"the",
"function",
"to",
"build",
"spatial",
"layers."
] | def build_spatial_path(string, Conv2d=nn.Conv2d, norm_layer='BN', **kwargs):
return AutoSpatialPath(ConvBnRelu, string, norm_layer=norm_layer, Conv2d=Conv2d, **kwargs) | ['def', 'build_spatial_path(string,', 'Conv2d=nn.Conv2d,', "norm_layer='BN',", '**kwargs):', 'return', 'AutoSpatialPath(ConvBnRelu,', 'string,', 'norm_layer=norm_layer,', 'Conv2d=Conv2d,', '**kwargs)'] | 962,987 |
huawei-noah/xingtian | layer.py | diff_size | diff_size | Return size is same as shape or not. | [
"Return",
"size",
"is",
"same",
"as",
"shape",
"or",
"not."
] | def diff_size(x, size):
return x.shape[2] != size | ['def', 'diff_size(x,', 'size):', 'return', 'x.shape[2]', '!=', 'size'] | 962,995 |
huawei-noah/xingtian | layer.py | get_operation | get_operation | Set up conv and pool operations. | [
"Set",
"up",
"conv",
"and",
"pool",
"operations."
] | def get_operation(op, inplanes, outplanes, stride, conv_type):
kernel_size = Ops.ops_to_kernel_size[op]
padding = [(k - 1) // 2 for k in kernel_size]
if op in Ops.pooling_ops:
if inplanes == outplanes:
return nn.AvgPool2d(kernel_size, stride=stride, padding=padding)
else:
... | ['def', 'get_operation(op,', 'inplanes,', 'outplanes,', 'stride,', 'conv_type):', 'kernel_size', '=', 'Ops.ops_to_kernel_size[op]', 'padding', '=', '[(k', '-', '1)', '//', '2', 'for', 'k', 'in', 'kernel_size]', 'if', 'op', 'in', 'Ops.pooling_ops:', 'if', 'inplanes', '==', 'outplanes:', 'return', 'nn.AvgPool2d(kernel_si... | 962,996 |
huawei-noah/xingtian | logical_graph.py | build_graph | build_graph | Build a graph using network x based on graphparamters. | [
"Build",
"a",
"graph",
"using",
"network",
"x",
"based",
"on",
"graphparamters."
] | def build_graph(graphparam, seed):
graph_model_name = graphparam[0]
if graph_model_name == 'ER':
(graph_model, nodes, P) = graphparam
return nx.random_graphs.erdos_renyi_graph(int(nodes), P, seed)
elif graph_model_name == 'BA':
(graph_model, nodes, M) = graphparam
return nx.r... | ['def', 'build_graph(graphparam,', 'seed):', 'graph_model_name', '=', 'graphparam[0]', 'if', 'graph_model_name', '==', "'ER':", '(graph_model,', 'nodes,', 'P)', '=', 'graphparam', 'return', 'nx.random_graphs.erdos_renyi_graph(int(nodes),', 'P,', 'seed)', 'elif', 'graph_model_name', '==', "'BA':", '(graph_model,', 'node... | 963,000 |
huawei-noah/xingtian | logical_graph.py | sample_merging_strategy | sample_merging_strategy | Sample merging options from a categorical distribution. | [
"Sample",
"merging",
"options",
"from",
"a",
"categorical",
"distribution."
] | def sample_merging_strategy(inputs, merge_distribution, role):
if role == NodeRoles.INPUT or len(inputs) == 1:
return EdgeMerge.SINGLE
return np.random.choice(EdgeMerge.merging_options, p=merge_distribution) | ['def', 'sample_merging_strategy(inputs,', 'merge_distribution,', 'role):', 'if', 'role', '==', 'NodeRoles.INPUT', 'or', 'len(inputs)', '==', '1:', 'return', 'EdgeMerge.SINGLE', 'return', 'np.random.choice(EdgeMerge.merging_options,', 'p=merge_distribution)'] | 963,001 |
huawei-noah/xingtian | cyclesr_net.py | CycleSRModel.set_mode | set_mode | Set the mode of model to train. | [
"Set",
"the",
"mode",
"of",
"model",
"to",
"train."
] | def set_mode(self, mode):
for name in self.model_names:
if isinstance(name, str):
net = getattr(self, 'net' + name)
if mode == 'eval':
net.eval()
elif mode == 'train':
net.train()
else:
raise ValueError('Not recognize mode %s.'.format(m... | ['def', 'set_mode(self,', 'mode):', 'for', 'name', 'in', 'self.model_names:', 'if', 'isinstance(name,', 'str):', 'net', '=', 'getattr(self,', "'net'", '+', 'name)', 'if', 'mode', '==', "'eval':", 'net.eval()', 'elif', 'mode', '==', "'train':", 'net.train()', 'else:', 'raise', "ValueError('Not", 'recognize', 'mode', "%s... | 963,004 |
huawei-noah/xingtian | auto_lane_detector.py | huber_fun | huber_fun | Implement of hunber function. | [
"Implement",
"of",
"hunber",
"function."
] | def huber_fun(x):
absx = torch.abs(x)
r = torch.where(absx < 1, x * x / 2, absx - 0.5)
return r | ['def', 'huber_fun(x):', 'absx', '=', 'torch.abs(x)', 'r', '=', 'torch.where(absx', '<', '1,', 'x', '*', 'x', '/', '2,', 'absx', '-', '0.5)', 'return', 'r'] | 963,022 |
huawei-noah/xingtian | auto_lane_detector.py | AutoLaneDetector.forward_calc_params_and_flops | forward_calc_params_and_flops | Just for calc paramters. | [
"Just",
"for",
"calc",
"paramters."
] | def forward_calc_params_and_flops(self, input, **kwargs):
feat = self.extract_feat(input)
predict = self.head(feat)
return predict | ['def', 'forward_calc_params_and_flops(self,', 'input,', '**kwargs):', 'feat', '=', 'self.extract_feat(input)', 'predict', '=', 'self.head(feat)', 'return', 'predict'] | 963,025 |
huawei-noah/xingtian | prune_getter.py | PruneGetter.state_dict | state_dict | Call subclass state_dict function. | [
"Call",
"subclass",
"state_dict",
"function."
] | def state_dict(self, destination=None, prefix='', keep_vars=False):
return self.model.state_dict(destination, prefix, keep_vars) | ['def', 'state_dict(self,', 'destination=None,', "prefix='',", 'keep_vars=False):', 'return', 'self.model.state_dict(destination,', 'prefix,', 'keep_vars)'] | 963,029 |
huawei-noah/xingtian | ffm.py | FeatureFusionModule.forward | forward | Get the result of ffm. | [
"Get",
"the",
"result",
"of",
"ffm."
] | def forward(self, inputs):
out = self.neck(inputs[0:4])
return out | ['def', 'forward(self,', 'inputs):', 'out', '=', 'self.neck(inputs[0:4])', 'return', 'out'] | 963,043 |
huawei-noah/xingtian | faster_rcnn.py | FasterRCNN.get_real_model | get_real_model | Get or init real model. | [
"Get",
"or",
"init",
"real",
"model."
] | def get_real_model(self, training):
if self.model:
return self.model
else:
self._init_model(training)
return self.model | ['def', 'get_real_model(self,', 'training):', 'if', 'self.model:', 'return', 'self.model', 'else:', 'self._init_model(training)', 'return', 'self.model'] | 963,045 |
huawei-noah/xingtian | faster_rcnn.py | FasterRCNN.loss | loss | Get loss function of faster-rcnn. | [
"Get",
"loss",
"function",
"of",
"faster-rcnn."
] | def loss(self, predict_results, true_image_shapes):
return self.get_real_model(True).loss(predict_results, true_image_shapes) | ['def', 'loss(self,', 'predict_results,', 'true_image_shapes):', 'return', 'self.get_real_model(True).loss(predict_results,', 'true_image_shapes)'] | 963,046 |
huawei-noah/xingtian | faster_rcnn.py | FasterRCNN.regularization_losses | regularization_losses | Get regularization loss of faster-rcnn. | [
"Get",
"regularization",
"loss",
"of",
"faster-rcnn."
] | def regularization_losses(self):
return self.get_real_model(True).regularization_losses() | ['def', 'regularization_losses(self):', 'return', 'self.get_real_model(True).regularization_losses()'] | 963,047 |
huawei-noah/xingtian | faster_rcnn.py | FasterRCNN.restore_map | restore_map | Restore map of faster-rcnn. | [
"Restore",
"map",
"of",
"faster-rcnn."
] | def restore_map(self, fine_tune_checkpoint_type, load_all_detection_checkpoint_vars):
return self.get_real_model(True).restore_map(fine_tune_checkpoint_type=fine_tune_checkpoint_type, load_all_detection_checkpoint_vars=load_all_detection_checkpoint_vars) | ['def', 'restore_map(self,', 'fine_tune_checkpoint_type,', 'load_all_detection_checkpoint_vars):', 'return', 'self.get_real_model(True).restore_map(fine_tune_checkpoint_type=fine_tune_checkpoint_type,', 'load_all_detection_checkpoint_vars=load_all_detection_checkpoint_vars)'] | 963,048 |
huawei-noah/xingtian | faster_rcnn_trainer_callback.py | FasterRCNNTrainerCallback.model_fn | model_fn | Define Faster R-CNN model_fn used by TensorFlow Estimator. | [
"Define",
"Faster",
"R-CNN",
"model_fn",
"used",
"by",
"TensorFlow",
"Estimator."
] | def model_fn(self, features, labels, mode):
logging.info('Faster R-CNN model function action')
self.model = self.trainer.model
self.config = self.trainer.config
predict_result_dict = self.model(features, labels, mode == tf.estimator.ModeKeys.TRAIN)
self.fine_tune_checkpoint_type = self.config.fine_t... | ['def', 'model_fn(self,', 'features,', 'labels,', 'mode):', "logging.info('Faster", 'R-CNN', 'model', 'function', "action')", 'self.model', '=', 'self.trainer.model', 'self.config', '=', 'self.trainer.config', 'predict_result_dict', '=', 'self.model(features,', 'labels,', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN)', '... | 963,049 |
huawei-noah/xingtian | mask_rcnn_box.py | MaskRCNNBox.get_real_model | get_real_model | Get real model of maskRcnnBox. | [
"Get",
"real",
"model",
"of",
"maskRcnnBox."
] | def get_real_model(self, training):
if self.model:
return self.model
else:
self.box_prediction_head = box_head.MaskRCNNBoxHead(is_training=training, num_classes=self.num_classes, fc_hyperparams_fn=self.fc_hyperparams, use_dropout=self.use_dropout, dropout_keep_prob=self.dropout_keep_prob, box_co... | ['def', 'get_real_model(self,', 'training):', 'if', 'self.model:', 'return', 'self.model', 'else:', 'self.box_prediction_head', '=', 'box_head.MaskRCNNBoxHead(is_training=training,', 'num_classes=self.num_classes,', 'fc_hyperparams_fn=self.fc_hyperparams,', 'use_dropout=self.use_dropout,', 'dropout_keep_prob=self.dropo... | 963,051 |
huawei-noah/xingtian | initializer.py | Initializer.get_real_model | get_real_model | Get real model of initializer. | [
"Get",
"real",
"model",
"of",
"initializer."
] | def get_real_model(self):
if self.model:
return self.model
else:
if self.type == 'truncated_normal_initializer':
self.model = tf.truncated_normal_initializer(mean=self.mean, stddev=self.stddev)
elif self.type == 'random_normal_initializer':
self.model = tf.random_... | ['def', 'get_real_model(self):', 'if', 'self.model:', 'return', 'self.model', 'else:', 'if', 'self.type', '==', "'truncated_normal_initializer':", 'self.model', '=', 'tf.truncated_normal_initializer(mean=self.mean,', 'stddev=self.stddev)', 'elif', 'self.type', '==', "'random_normal_initializer':", 'self.model', '=', 't... | 963,053 |
huawei-noah/xingtian | scope_generator.py | get_hyper_params_scope | get_hyper_params_scope | Get hyper params scope. | [
"Get",
"hyper",
"params",
"scope."
] | def get_hyper_params_scope(desc):
op = desc.op
affected_ops = [slim.conv2d, slim.separable_conv2d, slim.conv2d_transpose]
if op and op == hyperparams_pb2.Hyperparams.FC:
affected_ops = [slim.fully_connected]
def scope_fn():
with context_manager.IdentityContextManager():
with... | ['def', 'get_hyper_params_scope(desc):', 'op', '=', 'desc.op', 'affected_ops', '=', '[slim.conv2d,', 'slim.separable_conv2d,', 'slim.conv2d_transpose]', 'if', 'op', 'and', 'op', '==', 'hyperparams_pb2.Hyperparams.FC:', 'affected_ops', '=', '[slim.fully_connected]', 'def', 'scope_fn():', 'with', 'context_manager.Identit... | 963,055 |
huawei-noah/xingtian | post_processing_util.py | get_post_processing_fn | get_post_processing_fn | Get post processing function. | [
"Get",
"post",
"processing",
"function."
] | def get_post_processing_fn(desc):
nms_config = desc.batch_non_max_suppression
score_converter_type = desc.score_converter
non_max_suppressor_fn = _get_non_max_suppressor_fn(nms_config)
score_converter_fn = _get_score_converter_fn(score_converter_type)
return (non_max_suppressor_fn, score_converter_f... | ['def', 'get_post_processing_fn(desc):', 'nms_config', '=', 'desc.batch_non_max_suppression', 'score_converter_type', '=', 'desc.score_converter', 'non_max_suppressor_fn', '=', '_get_non_max_suppressor_fn(nms_config)', 'score_converter_fn', '=', '_get_score_converter_fn(score_converter_type)', 'return', '(non_max_suppr... | 963,057 |
huawei-noah/xingtian | flops_params_filter.py | FlopsParamsFilter.is_filtered | is_filtered | Filter function of Flops and Params. | [
"Filter",
"function",
"of",
"Flops",
"and",
"Params."
] | def is_filtered(self, desc=None):
if self.flops_range is None and self.params_range is None:
return False
(model, count_input) = self.get_model_input(desc)
(flops, params) = calc_model_flops_params(model, count_input)
(flops, params) = (flops * 1e-09, params * 0.001)
if self.flops_range is n... | ['def', 'is_filtered(self,', 'desc=None):', 'if', 'self.flops_range', 'is', 'None', 'and', 'self.params_range', 'is', 'None:', 'return', 'False', '(model,', 'count_input)', '=', 'self.get_model_input(desc)', '(flops,', 'params)', '=', 'calc_model_flops_params(model,', 'count_input)', '(flops,', 'params)', '=', '(flops'... | 963,059 |
loyalzc/transfer_learning | Network.py | DANN.hidden_representation | hidden_representation | Compute and return the network hidden layer values for X. | [
"Compute",
"and",
"return",
"the",
"network",
"hidden",
"layer",
"values",
"for",
"X."
] | def hidden_representation(self, X):
hidden_layer = self.sigmoid(np.dot(self.W, X.T) + self.b[:, np.newaxis])
return hidden_layer.T | ['def', 'hidden_representation(self,', 'X):', 'hidden_layer', '=', 'self.sigmoid(np.dot(self.W,', 'X.T)', '+', 'self.b[:,', 'np.newaxis])', 'return', 'hidden_layer.T'] | 963,319 |
THUAML/Transfer_Learning_Enhanced_Water-Enabled_Electricity_Generation | dataloader.py | Dataloader.preprocessor | preprocessor | Logarithmic transformation of each characteristic parameter. | [
"Logarithmic",
"transformation",
"of",
"each",
"characteristic",
"parameter."
] | def preprocessor(self):
log_features = []
for index in range(8):
param = np.log(np.abs(self._data[:, index]))
param = param[:, np.newaxis]
log_features.append(param)
log_features = np.concatenate(log_features, axis=1)
self._data = np.concatenate((self._data[:, :8], log_features, ... | ['def', 'preprocessor(self):', 'log_features', '=', '[]', 'for', 'index', 'in', 'range(8):', 'param', '=', 'np.log(np.abs(self._data[:,', 'index]))', 'param', '=', 'param[:,', 'np.newaxis]', 'log_features.append(param)', 'log_features', '=', 'np.concatenate(log_features,', 'axis=1)', 'self._data', '=', 'np.concatenate(... | 964,430 |
THUAML/Transfer_Learning_Enhanced_Water-Enabled_Electricity_Generation | models_def.py | SingleConnectionFunction.forward | forward | Forward propagation implementation of NormLayer. | [
"Forward",
"propagation",
"implementation",
"of",
"NormLayer."
] | def forward(ctx, inputs, weight, bias):
ctx.save_for_backward(inputs, weight, bias)
output = torch.mul(inputs, weight)
output += bias.unsqueeze(0).expand_as(output)
return output | ['def', 'forward(ctx,', 'inputs,', 'weight,', 'bias):', 'ctx.save_for_backward(inputs,', 'weight,', 'bias)', 'output', '=', 'torch.mul(inputs,', 'weight)', 'output', '+=', 'bias.unsqueeze(0).expand_as(output)', 'return', 'output'] | 964,431 |
THUAML/Transfer_Learning_Enhanced_Water-Enabled_Electricity_Generation | models_def.py | SingleConnectionFunction.backward | backward | Backpropagation implementation of NormLayer. | [
"Backpropagation",
"implementation",
"of",
"NormLayer."
] | def backward(ctx, grad_output):
(inputs, weight, bias) = ctx.saved_tensors
grad_input = torch.mul(grad_output, weight)
grad_weight = torch.sum(torch.mul(grad_output, inputs), dim=0).unsqueeze(0)
grad_bias = torch.sum(grad_output, dim=0)
return (grad_input, grad_weight, grad_bias) | ['def', 'backward(ctx,', 'grad_output):', '(inputs,', 'weight,', 'bias)', '=', 'ctx.saved_tensors', 'grad_input', '=', 'torch.mul(grad_output,', 'weight)', 'grad_weight', '=', 'torch.sum(torch.mul(grad_output,', 'inputs),', 'dim=0).unsqueeze(0)', 'grad_bias', '=', 'torch.sum(grad_output,', 'dim=0)', 'return', '(grad_in... | 964,432 |
THUAML/Transfer_Learning_Enhanced_Water-Enabled_Electricity_Generation | noise_utils.py | get_random_fluctuation | get_random_fluctuation | Return generation performance data with random noise. | [
"Return",
"generation",
"performance",
"data",
"with",
"random",
"noise."
] | def get_random_fluctuation(values, noise_std, device):
noise = torch.normal(mean=0, std=noise_std, size=values.shape).to(device)
return values + noise | ['def', 'get_random_fluctuation(values,', 'noise_std,', 'device):', 'noise', '=', 'torch.normal(mean=0,', 'std=noise_std,', 'size=values.shape).to(device)', 'return', 'values', '+', 'noise'] | 964,433 |
antriv/Transfer_Learning_Text | spacy_tokenizer.py | pos_regex_matches | pos_regex_matches | Extract sequences of consecutive tokens from a spacy-parsed doc whose part-of-speech tags match the specified regex pattern. | [
"Extract",
"sequences",
"of",
"consecutive",
"tokens",
"from",
"a",
"spacy-parsed",
"doc",
"whose",
"part-of-speech",
"tags",
"match",
"the",
"specified",
"regex",
"pattern."
] | def pos_regex_matches(doc, pattern):
pattern = re.sub('\\s', '', pattern)
pattern = re.sub('<([A-Z]+)\\|([A-Z]+)>', '( (\\1|\\2))', pattern)
pattern = re.sub('<([A-Z]+)\\|([A-Z]+)\\|([A-Z]+)>', '( (\\1|\\2|\\3))', pattern)
pattern = re.sub('<([A-Z]+)\\|([A-Z]+)\\|([A-Z]+)\\|([A-Z]+)>', '( (\\1|\\2|\\3|\... | ['def', 'pos_regex_matches(doc,', 'pattern):', 'pattern', '=', "re.sub('\\\\s',", "'',", 'pattern)', 'pattern', '=', "re.sub('<([A-Z]+)\\\\|([A-Z]+)>',", "'(", "(\\\\1|\\\\2))',", 'pattern)', 'pattern', '=', "re.sub('<([A-Z]+)\\\\|([A-Z]+)\\\\|([A-Z]+)>',", "'(", "(\\\\1|\\\\2|\\\\3))',", 'pattern)', 'pattern', '=', "r... | 964,473 |
dstallmann/transfer_learning_twinvae | DeepView.py | DeepView.reset | reset | Resets the state of DeepView to the point of initialization. | [
"Resets",
"the",
"state",
"of",
"DeepView",
"to",
"the",
"point",
"of",
"initialization."
] | def reset(self):
self.discr_distances = np.array([])
self.eucl_distances = np.array([])
self.samples = np.empty([0, *self.data_shape])
self.embedded = np.empty([0, 2])
self.y_true = np.array([])
self.y_pred = np.array([])
self.classifier_view = np.array([]) | ['def', 'reset(self):', 'self.discr_distances', '=', 'np.array([])', 'self.eucl_distances', '=', 'np.array([])', 'self.samples', '=', 'np.empty([0,', '*self.data_shape])', 'self.embedded', '=', 'np.empty([0,', '2])', 'self.y_true', '=', 'np.array([])', 'self.y_pred', '=', 'np.array([])', 'self.classifier_view', '=', 'n... | 964,682 |
dstallmann/transfer_learning_twinvae | DeepView.py | DeepView.close | close | Closes the matplotlib window, terminates DeepView. | [
"Closes",
"the",
"matplotlib",
"window,",
"terminates",
"DeepView."
] | def close(self):
plt.close() | ['def', 'close(self):', 'plt.close()'] | 964,683 |
dstallmann/transfer_learning_twinvae | DeepView.py | DeepView.set_lambda | set_lambda | Dynamically sets a new lambda and recomputes the embeddings, as the distances will also change. | [
"Dynamically",
"sets",
"a",
"new",
"lambda",
"and",
"recomputes",
"the",
"embeddings,",
"as",
"the",
"distances",
"will",
"also",
"change."
] | def set_lambda(self, lam):
if self.lam == lam:
return
self.lam = lam
self.update_mappings() | ['def', 'set_lambda(self,', 'lam):', 'if', 'self.lam', '==', 'lam:', 'return', 'self.lam', '=', 'lam', 'self.update_mappings()'] | 964,684 |
dstallmann/transfer_learning_twinvae | learner.py | evaluate | evaluate | Evaluates the current state of the inner representation by random sampling and sampling another time close by (noise) to allow for a check of visual consistency. | [
"Evaluates",
"the",
"current",
"state",
"of",
"the",
"inner",
"representation",
"by",
"random",
"sampling",
"and",
"sampling",
"another",
"time",
"close",
"by",
"(noise)",
"to",
"allow",
"for",
"a",
"check",
"of",
"visual",
"consistency."
] | def evaluate():
model.eval()
stddev = 1
for (batch_idx, (data, _)) in enumerate(syn_test_loader):
data = data.cuda()
if batch_idx == 0:
noise = torch.autograd.Variable(torch.randn(batch_size, bottleneck).cuda() * stddev)
sample_representation('orig_nat', data, noise)
... | ['def', 'evaluate():', 'model.eval()', 'stddev', '=', '1', 'for', '(batch_idx,', '(data,', '_))', 'in', 'enumerate(syn_test_loader):', 'data', '=', 'data.cuda()', 'if', 'batch_idx', '==', '0:', 'noise', '=', 'torch.autograd.Variable(torch.randn(batch_size,', 'bottleneck).cuda()', '*', 'stddev)', "sample_representation(... | 964,709 |
dstallmann/transfer_learning_twinvae | bayesian_optimization.py | Queue.add | add | Add object to end of queue. | [
"Add",
"object",
"to",
"end",
"of",
"queue."
] | def add(self, obj):
self._queue.append(obj) | ['def', 'add(self,', 'obj):', 'self._queue.append(obj)'] | 964,728 |
dstallmann/transfer_learning_twinvae | target_space.py | TargetSpace.max | max | Get maximum target value found and corresponding parametes. | [
"Get",
"maximum",
"target",
"value",
"found",
"and",
"corresponding",
"parametes."
] | def max(self):
try:
res = {'target': self.target.max(), 'params': dict(zip(self.keys, self.params[self.target.argmax()]))}
except ValueError:
res = {}
return res | ['def', 'max(self):', 'try:', 'res', '=', "{'target':", 'self.target.max(),', "'params':", 'dict(zip(self.keys,', 'self.params[self.target.argmax()]))}', 'except', 'ValueError:', 'res', '=', '{}', 'return', 'res'] | 964,736 |
dstallmann/transfer_learning_twinvae | util.py | Colours.black | black | Wrap text in blue. | [
"Wrap",
"text",
"in",
"blue."
] | def black(cls, s):
return cls._wrap_colour(s, cls.END) | ['def', 'black(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.END)'] | 964,741 |
dstallmann/transfer_learning_twinvae | util.py | Colours.bold | bold | Wrap text in bold. | [
"Wrap",
"text",
"in",
"bold."
] | def bold(cls, s):
return cls._wrap_colour(s, cls.BOLD) | ['def', 'bold(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.BOLD)'] | 964,743 |
dstallmann/transfer_learning_twinvae | util.py | Colours.cyan | cyan | Wrap text in cyan. | [
"Wrap",
"text",
"in",
"cyan."
] | def cyan(cls, s):
return cls._wrap_colour(s, cls.CYAN) | ['def', 'cyan(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.CYAN)'] | 964,744 |
dstallmann/transfer_learning_twinvae | util.py | Colours.darkcyan | darkcyan | Wrap text in darkcyan. | [
"Wrap",
"text",
"in",
"darkcyan."
] | def darkcyan(cls, s):
return cls._wrap_colour(s, cls.DARKCYAN) | ['def', 'darkcyan(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.DARKCYAN)'] | 964,745 |
dstallmann/transfer_learning_twinvae | util.py | Colours.green | green | Wrap text in green. | [
"Wrap",
"text",
"in",
"green."
] | def green(cls, s):
return cls._wrap_colour(s, cls.GREEN) | ['def', 'green(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.GREEN)'] | 964,746 |
dstallmann/transfer_learning_twinvae | util.py | Colours.purple | purple | Wrap text in purple. | [
"Wrap",
"text",
"in",
"purple."
] | def purple(cls, s):
return cls._wrap_colour(s, cls.PURPLE) | ['def', 'purple(cls,', 's):', 'return', 'cls._wrap_colour(s,', 'cls.PURPLE)'] | 964,747 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.