id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,000 | Microsoft/nni | examples/trials/kaggle-tgs-salt/predict.py | do_tta_predict | def do_tta_predict(args, model, ckp_path, tta_num=4):
'''
return 18000x128x128 np array
'''
model.eval()
preds = []
meta = None
# i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both
for flip_index in range(tta_num):
print('flip_index:', flip_index)
... | python | def do_tta_predict(args, model, ckp_path, tta_num=4):
'''
return 18000x128x128 np array
'''
model.eval()
preds = []
meta = None
# i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both
for flip_index in range(tta_num):
print('flip_index:', flip_index)
... | [
"def",
"do_tta_predict",
"(",
"args",
",",
"model",
",",
"ckp_path",
",",
"tta_num",
"=",
"4",
")",
":",
"model",
".",
"eval",
"(",
")",
"preds",
"=",
"[",
"]",
"meta",
"=",
"None",
"# i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both",
... | return 18000x128x128 np array | [
"return",
"18000x128x128",
"np",
"array"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/predict.py#L37-L83 |
27,001 | Microsoft/nni | examples/trials/mnist-distributed-pytorch/dist_mnist.py | average_gradients | def average_gradients(model):
""" Gradient averaging. """
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM, group=0)
param.grad.data /= size | python | def average_gradients(model):
""" Gradient averaging. """
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM, group=0)
param.grad.data /= size | [
"def",
"average_gradients",
"(",
"model",
")",
":",
"size",
"=",
"float",
"(",
"dist",
".",
"get_world_size",
"(",
")",
")",
"for",
"param",
"in",
"model",
".",
"parameters",
"(",
")",
":",
"dist",
".",
"all_reduce",
"(",
"param",
".",
"grad",
".",
"... | Gradient averaging. | [
"Gradient",
"averaging",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-distributed-pytorch/dist_mnist.py#L113-L118 |
27,002 | Microsoft/nni | examples/trials/mnist-distributed-pytorch/dist_mnist.py | run | def run(params):
""" Distributed Synchronous SGD Example """
rank = dist.get_rank()
torch.manual_seed(1234)
train_set, bsz = partition_dataset()
model = Net()
model = model
optimizer = optim.SGD(model.parameters(), lr=params['learning_rate'], momentum=params['momentum'])
num_batches = c... | python | def run(params):
""" Distributed Synchronous SGD Example """
rank = dist.get_rank()
torch.manual_seed(1234)
train_set, bsz = partition_dataset()
model = Net()
model = model
optimizer = optim.SGD(model.parameters(), lr=params['learning_rate'], momentum=params['momentum'])
num_batches = c... | [
"def",
"run",
"(",
"params",
")",
":",
"rank",
"=",
"dist",
".",
"get_rank",
"(",
")",
"torch",
".",
"manual_seed",
"(",
"1234",
")",
"train_set",
",",
"bsz",
"=",
"partition_dataset",
"(",
")",
"model",
"=",
"Net",
"(",
")",
"model",
"=",
"model",
... | Distributed Synchronous SGD Example | [
"Distributed",
"Synchronous",
"SGD",
"Example"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-distributed-pytorch/dist_mnist.py#L121-L150 |
27,003 | Microsoft/nni | examples/trials/ga_squad/graph.py | Layer.set_size | def set_size(self, graph_id, size):
'''
Set size.
'''
if self.graph_type == LayerType.attention.value:
if self.input[0] == graph_id:
self.size = size
if self.graph_type == LayerType.rnn.value:
self.size = size
if self.graph_type == ... | python | def set_size(self, graph_id, size):
'''
Set size.
'''
if self.graph_type == LayerType.attention.value:
if self.input[0] == graph_id:
self.size = size
if self.graph_type == LayerType.rnn.value:
self.size = size
if self.graph_type == ... | [
"def",
"set_size",
"(",
"self",
",",
"graph_id",
",",
"size",
")",
":",
"if",
"self",
".",
"graph_type",
"==",
"LayerType",
".",
"attention",
".",
"value",
":",
"if",
"self",
".",
"input",
"[",
"0",
"]",
"==",
"graph_id",
":",
"self",
".",
"size",
... | Set size. | [
"Set",
"size",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/graph.py#L69-L83 |
27,004 | Microsoft/nni | examples/trials/ga_squad/graph.py | Graph.is_topology | def is_topology(self, layers=None):
'''
valid the topology
'''
if layers is None:
layers = self.layers
layers_nodle = []
result = []
for i, layer in enumerate(layers):
if layer.is_delete is False:
layers_nodle.append(i)
... | python | def is_topology(self, layers=None):
'''
valid the topology
'''
if layers is None:
layers = self.layers
layers_nodle = []
result = []
for i, layer in enumerate(layers):
if layer.is_delete is False:
layers_nodle.append(i)
... | [
"def",
"is_topology",
"(",
"self",
",",
"layers",
"=",
"None",
")",
":",
"if",
"layers",
"is",
"None",
":",
"layers",
"=",
"self",
".",
"layers",
"layers_nodle",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"i",
",",
"layer",
"in",
"enumerate",
"... | valid the topology | [
"valid",
"the",
"topology"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/graph.py#L133-L168 |
27,005 | Microsoft/nni | examples/trials/ga_squad/graph.py | Graph.is_legal | def is_legal(self, layers=None):
'''
Judge whether is legal for layers
'''
if layers is None:
layers = self.layers
for layer in layers:
if layer.is_delete is False:
if len(layer.input) != layer.input_size:
return False
... | python | def is_legal(self, layers=None):
'''
Judge whether is legal for layers
'''
if layers is None:
layers = self.layers
for layer in layers:
if layer.is_delete is False:
if len(layer.input) != layer.input_size:
return False
... | [
"def",
"is_legal",
"(",
"self",
",",
"layers",
"=",
"None",
")",
":",
"if",
"layers",
"is",
"None",
":",
"layers",
"=",
"self",
".",
"layers",
"for",
"layer",
"in",
"layers",
":",
"if",
"layer",
".",
"is_delete",
"is",
"False",
":",
"if",
"len",
"(... | Judge whether is legal for layers | [
"Judge",
"whether",
"is",
"legal",
"for",
"layers"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/graph.py#L183-L205 |
27,006 | Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | lovasz_grad | def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts - gt_sorted.float().cumsum(0)
union = gts + (1 - gt_sorted).float().cumsum(0)
jaccard = 1. - intersection ... | python | def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper
"""
p = len(gt_sorted)
gts = gt_sorted.sum()
intersection = gts - gt_sorted.float().cumsum(0)
union = gts + (1 - gt_sorted).float().cumsum(0)
jaccard = 1. - intersection ... | [
"def",
"lovasz_grad",
"(",
"gt_sorted",
")",
":",
"p",
"=",
"len",
"(",
"gt_sorted",
")",
"gts",
"=",
"gt_sorted",
".",
"sum",
"(",
")",
"intersection",
"=",
"gts",
"-",
"gt_sorted",
".",
"float",
"(",
")",
".",
"cumsum",
"(",
"0",
")",
"union",
"=... | Computes gradient of the Lovasz extension w.r.t sorted errors
See Alg. 1 in paper | [
"Computes",
"gradient",
"of",
"the",
"Lovasz",
"extension",
"w",
".",
"r",
".",
"t",
"sorted",
"errors",
"See",
"Alg",
".",
"1",
"in",
"paper"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L36-L48 |
27,007 | Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | flatten_probas | def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (lab... | python | def flatten_probas(probas, labels, ignore=None):
"""
Flattens predictions in the batch
"""
B, C, H, W = probas.size()
probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C
labels = labels.view(-1)
if ignore is None:
return probas, labels
valid = (lab... | [
"def",
"flatten_probas",
"(",
"probas",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"B",
",",
"C",
",",
"H",
",",
"W",
"=",
"probas",
".",
"size",
"(",
")",
"probas",
"=",
"probas",
".",
"permute",
"(",
"0",
",",
"2",
",",
"3",
",",
... | Flattens predictions in the batch | [
"Flattens",
"predictions",
"in",
"the",
"batch"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L211-L223 |
27,008 | Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | xloss | def xloss(logits, labels, ignore=None):
"""
Cross entropy loss
"""
return F.cross_entropy(logits, Variable(labels), ignore_index=255) | python | def xloss(logits, labels, ignore=None):
"""
Cross entropy loss
"""
return F.cross_entropy(logits, Variable(labels), ignore_index=255) | [
"def",
"xloss",
"(",
"logits",
",",
"labels",
",",
"ignore",
"=",
"None",
")",
":",
"return",
"F",
".",
"cross_entropy",
"(",
"logits",
",",
"Variable",
"(",
"labels",
")",
",",
"ignore_index",
"=",
"255",
")"
] | Cross entropy loss | [
"Cross",
"entropy",
"loss"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L225-L229 |
27,009 | Microsoft/nni | examples/trials/kaggle-tgs-salt/lovasz_losses.py | mean | def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | python | def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | [
"def",
"mean",
"(",
"l",
",",
"ignore_nan",
"=",
"False",
",",
"empty",
"=",
"0",
")",
":",
"l",
"=",
"iter",
"(",
"l",
")",
"if",
"ignore_nan",
":",
"l",
"=",
"ifilterfalse",
"(",
"np",
".",
"isnan",
",",
"l",
")",
"try",
":",
"n",
"=",
"1",... | nanmean compatible with generators. | [
"nanmean",
"compatible",
"with",
"generators",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/lovasz_losses.py#L234-L252 |
27,010 | Microsoft/nni | tools/nni_trial_tool/trial_keeper.py | main_loop | def main_loop(args):
'''main loop logic for trial keeper'''
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
stdout_file = open(STDOUT_FULL_PATH, 'a+')
stderr_file = open(STDERR_FULL_PATH, 'a+')
trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'tr... | python | def main_loop(args):
'''main loop logic for trial keeper'''
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
stdout_file = open(STDOUT_FULL_PATH, 'a+')
stderr_file = open(STDERR_FULL_PATH, 'a+')
trial_keeper_syslogger = RemoteLogger(args.nnimanager_ip, args.nnimanager_port, 'tr... | [
"def",
"main_loop",
"(",
"args",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"LOG_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"LOG_DIR",
")",
"stdout_file",
"=",
"open",
"(",
"STDOUT_FULL_PATH",
",",
"'a+'",
")",
"stderr_file",
"=",
... | main loop logic for trial keeper | [
"main",
"loop",
"logic",
"for",
"trial",
"keeper"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/trial_keeper.py#L43-L105 |
27,011 | Microsoft/nni | examples/trials/ga_squad/trial.py | load_embedding | def load_embedding(path):
'''
return embedding for a specific file by given file path.
'''
EMBEDDING_DIM = 300
embedding_dict = {}
with open(path, 'r', encoding='utf-8') as file:
pairs = [line.strip('\r\n').split() for line in file.readlines()]
for pair in pairs:
if l... | python | def load_embedding(path):
'''
return embedding for a specific file by given file path.
'''
EMBEDDING_DIM = 300
embedding_dict = {}
with open(path, 'r', encoding='utf-8') as file:
pairs = [line.strip('\r\n').split() for line in file.readlines()]
for pair in pairs:
if l... | [
"def",
"load_embedding",
"(",
"path",
")",
":",
"EMBEDDING_DIM",
"=",
"300",
"embedding_dict",
"=",
"{",
"}",
"with",
"open",
"(",
"path",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"pairs",
"=",
"[",
"line",
".",
"strip",
"... | return embedding for a specific file by given file path. | [
"return",
"embedding",
"for",
"a",
"specific",
"file",
"by",
"given",
"file",
"path",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/trial.py#L87-L99 |
27,012 | Microsoft/nni | examples/trials/ga_squad/trial.py | generate_predict_json | def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
'''
Generate json by prediction.
'''
predict_len = len(position1_result)
logger.debug('total prediction num is %s', str(predict_len))
answers = {}
for i in range(predict_len):
sample_id = ids[i]
... | python | def generate_predict_json(position1_result, position2_result, ids, passage_tokens):
'''
Generate json by prediction.
'''
predict_len = len(position1_result)
logger.debug('total prediction num is %s', str(predict_len))
answers = {}
for i in range(predict_len):
sample_id = ids[i]
... | [
"def",
"generate_predict_json",
"(",
"position1_result",
",",
"position2_result",
",",
"ids",
",",
"passage_tokens",
")",
":",
"predict_len",
"=",
"len",
"(",
"position1_result",
")",
"logger",
".",
"debug",
"(",
"'total prediction num is %s'",
",",
"str",
"(",
"p... | Generate json by prediction. | [
"Generate",
"json",
"by",
"prediction",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/trial.py#L252-L269 |
27,013 | Microsoft/nni | examples/trials/ga_squad/evaluate.py | f1_score | def f1_score(prediction, ground_truth):
'''
Calculate the f1 score.
'''
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
... | python | def f1_score(prediction, ground_truth):
'''
Calculate the f1 score.
'''
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
... | [
"def",
"f1_score",
"(",
"prediction",
",",
"ground_truth",
")",
":",
"prediction_tokens",
"=",
"normalize_answer",
"(",
"prediction",
")",
".",
"split",
"(",
")",
"ground_truth_tokens",
"=",
"normalize_answer",
"(",
"ground_truth",
")",
".",
"split",
"(",
")",
... | Calculate the f1 score. | [
"Calculate",
"the",
"f1",
"score",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L63-L76 |
27,014 | Microsoft/nni | examples/trials/ga_squad/evaluate.py | _evaluate | def _evaluate(dataset, predictions):
'''
Evaluate function.
'''
f1_result = exact_match = total = 0
count = 0
for article in dataset:
for paragraph in article['paragraphs']:
for qa_pair in paragraph['qas']:
total += 1
if qa_pair['id'] not in pr... | python | def _evaluate(dataset, predictions):
'''
Evaluate function.
'''
f1_result = exact_match = total = 0
count = 0
for article in dataset:
for paragraph in article['paragraphs']:
for qa_pair in paragraph['qas']:
total += 1
if qa_pair['id'] not in pr... | [
"def",
"_evaluate",
"(",
"dataset",
",",
"predictions",
")",
":",
"f1_result",
"=",
"exact_match",
"=",
"total",
"=",
"0",
"count",
"=",
"0",
"for",
"article",
"in",
"dataset",
":",
"for",
"paragraph",
"in",
"article",
"[",
"'paragraphs'",
"]",
":",
"for... | Evaluate function. | [
"Evaluate",
"function",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/evaluate.py#L94-L116 |
27,015 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | json2space | def json2space(in_x, name=ROOT):
"""
Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
... | python | def json2space(in_x, name=ROOT):
"""
Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
... | [
"def",
"json2space",
"(",
"in_x",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(",
")",
":",
"_type"... | Change json to search space in hyperopt.
Parameters
----------
in_x : dict/list/str/int/float
The part of json.
name : str
name could be ROOT, TYPE, VALUE or INDEX. | [
"Change",
"json",
"to",
"search",
"space",
"in",
"hyperopt",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L52-L85 |
27,016 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | json2parameter | def json2parameter(in_x, parameter, name=ROOT):
"""
Change json to parameters.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + '-' + _type
if _type == 'choice':
_index = pa... | python | def json2parameter(in_x, parameter, name=ROOT):
"""
Change json to parameters.
"""
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + '-' + _type
if _type == 'choice':
_index = pa... | [
"def",
"json2parameter",
"(",
"in_x",
",",
"parameter",
",",
"name",
"=",
"ROOT",
")",
":",
"out_y",
"=",
"copy",
".",
"deepcopy",
"(",
"in_x",
")",
"if",
"isinstance",
"(",
"in_x",
",",
"dict",
")",
":",
"if",
"TYPE",
"in",
"in_x",
".",
"keys",
"(... | Change json to parameters. | [
"Change",
"json",
"to",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L88-L116 |
27,017 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | _split_index | def _split_index(params):
"""
Delete index infromation from params
"""
if isinstance(params, list):
return [params[0], _split_index(params[1])]
elif isinstance(params, dict):
if INDEX in params.keys():
return _split_index(params[VALUE])
result = dict()
for... | python | def _split_index(params):
"""
Delete index infromation from params
"""
if isinstance(params, list):
return [params[0], _split_index(params[1])]
elif isinstance(params, dict):
if INDEX in params.keys():
return _split_index(params[VALUE])
result = dict()
for... | [
"def",
"_split_index",
"(",
"params",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"list",
")",
":",
"return",
"[",
"params",
"[",
"0",
"]",
",",
"_split_index",
"(",
"params",
"[",
"1",
"]",
")",
"]",
"elif",
"isinstance",
"(",
"params",
",",
... | Delete index infromation from params | [
"Delete",
"index",
"infromation",
"from",
"params"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L171-L185 |
27,018 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.update_search_space | def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | python | def update_search_space(self, search_space):
"""
Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict
"""
self.json = sea... | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"json",
"=",
"search_space",
"search_space_instance",
"=",
"json2space",
"(",
"self",
".",
"json",
")",
"rstate",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
... | Update search space definition in tuner by search_space in parameters.
Will called when first setup experiemnt or update search space in WebUI.
Parameters
----------
search_space : dict | [
"Update",
"search",
"space",
"definition",
"in",
"tuner",
"by",
"search_space",
"in",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L223-L242 |
27,019 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.receive_trial_result | def receive_trial_result(self, parameter_id, parameters, value):
"""
Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
... | python | def receive_trial_result(self, parameter_id, parameters, value):
"""
Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"# restore the paramsters contains '_index'",
"if",
"parameter_id",
"not",
"in",
"self",
".",
"tota... | Record an observation of the objective function
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
value is final metrics of the trial. | [
"Record",
"an",
"observation",
"of",
"the",
"objective",
"function"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L265-L319 |
27,020 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.miscs_update_idxs_vals | def miscs_update_idxs_vals(self, miscs, idxs, vals,
assert_all_vals_used=True,
idxs_map=None):
"""
Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dic... | python | def miscs_update_idxs_vals(self, miscs, idxs, vals,
assert_all_vals_used=True,
idxs_map=None):
"""
Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dic... | [
"def",
"miscs_update_idxs_vals",
"(",
"self",
",",
"miscs",
",",
"idxs",
",",
"vals",
",",
"assert_all_vals_used",
"=",
"True",
",",
"idxs_map",
"=",
"None",
")",
":",
"if",
"idxs_map",
"is",
"None",
":",
"idxs_map",
"=",
"{",
"}",
"assert",
"set",
"(",
... | Unpack the idxs-vals format into the list of dictionaries that is
`misc`.
Parameters
----------
idxs_map : dict
idxs_map is a dictionary of id->id mappings so that the misc['idxs'] can
contain different numbers than the idxs argument. | [
"Unpack",
"the",
"idxs",
"-",
"vals",
"format",
"into",
"the",
"list",
"of",
"dictionaries",
"that",
"is",
"misc",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L321-L350 |
27,021 | Microsoft/nni | src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py | HyperoptTuner.get_suggestion | def get_suggestion(self, random_search=False):
"""get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion... | python | def get_suggestion(self, random_search=False):
"""get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion... | [
"def",
"get_suggestion",
"(",
"self",
",",
"random_search",
"=",
"False",
")",
":",
"rval",
"=",
"self",
".",
"rval",
"trials",
"=",
"rval",
".",
"trials",
"algorithm",
"=",
"rval",
".",
"algo",
"new_ids",
"=",
"rval",
".",
"trials",
".",
"new_trial_ids"... | get suggestion from hyperopt
Parameters
----------
random_search : bool
flag to indicate random search or not (default: {False})
Returns
----------
total_params : dict
parameter suggestion | [
"get",
"suggestion",
"from",
"hyperopt"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperopt_tuner/hyperopt_tuner.py#L352-L387 |
27,022 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py | next_hyperparameter_lowest_mu | def next_hyperparameter_lowest_mu(fun_prediction,
fun_prediction_args,
x_bounds, x_types,
minimize_starting_points,
minimize_constraints_fun=None):
'''
"Lowest Mu" acquisition ... | python | def next_hyperparameter_lowest_mu(fun_prediction,
fun_prediction_args,
x_bounds, x_types,
minimize_starting_points,
minimize_constraints_fun=None):
'''
"Lowest Mu" acquisition ... | [
"def",
"next_hyperparameter_lowest_mu",
"(",
"fun_prediction",
",",
"fun_prediction_args",
",",
"x_bounds",
",",
"x_types",
",",
"minimize_starting_points",
",",
"minimize_constraints_fun",
"=",
"None",
")",
":",
"best_x",
"=",
"None",
"best_acquisition_value",
"=",
"No... | "Lowest Mu" acquisition function | [
"Lowest",
"Mu",
"acquisition",
"function"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py#L154-L187 |
27,023 | Microsoft/nni | src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py | _lowest_mu | def _lowest_mu(x, fun_prediction, fun_prediction_args,
x_bounds, x_types, minimize_constraints_fun):
'''
Calculate the lowest mu
'''
# This is only for step-wise optimization
x = lib_data.match_val_type(x, x_bounds, x_types)
mu = sys.maxsize
if (minimize_constraints_fun is No... | python | def _lowest_mu(x, fun_prediction, fun_prediction_args,
x_bounds, x_types, minimize_constraints_fun):
'''
Calculate the lowest mu
'''
# This is only for step-wise optimization
x = lib_data.match_val_type(x, x_bounds, x_types)
mu = sys.maxsize
if (minimize_constraints_fun is No... | [
"def",
"_lowest_mu",
"(",
"x",
",",
"fun_prediction",
",",
"fun_prediction_args",
",",
"x_bounds",
",",
"x_types",
",",
"minimize_constraints_fun",
")",
":",
"# This is only for step-wise optimization",
"x",
"=",
"lib_data",
".",
"match_val_type",
"(",
"x",
",",
"x_... | Calculate the lowest mu | [
"Calculate",
"the",
"lowest",
"mu"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/lib_acquisition_function.py#L190-L201 |
27,024 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/train_model.py | GAG.build_char_states | def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths):
"""Build char embedding network for the QA model."""
max_char_length = self.cfg.max_char_length
inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids),
self.cfg.dropout, is_train... | python | def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths):
"""Build char embedding network for the QA model."""
max_char_length = self.cfg.max_char_length
inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids),
self.cfg.dropout, is_train... | [
"def",
"build_char_states",
"(",
"self",
",",
"char_embed",
",",
"is_training",
",",
"reuse",
",",
"char_ids",
",",
"char_lengths",
")",
":",
"max_char_length",
"=",
"self",
".",
"cfg",
".",
"max_char_length",
"inputs",
"=",
"dropout",
"(",
"tf",
".",
"nn",
... | Build char embedding network for the QA model. | [
"Build",
"char",
"embedding",
"network",
"for",
"the",
"QA",
"model",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/train_model.py#L234-L263 |
27,025 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._handle_final_metric_data | def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | python | def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | [
"def",
"_handle_final_metric_data",
"(",
"self",
",",
"data",
")",
":",
"id_",
"=",
"data",
"[",
"'parameter_id'",
"]",
"value",
"=",
"data",
"[",
"'value'",
"]",
"if",
"id_",
"in",
"_customized_parameter_ids",
":",
"self",
".",
"tuner",
".",
"receive_custom... | Call tuner to process final results | [
"Call",
"tuner",
"to",
"process",
"final",
"results"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L157-L165 |
27,026 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._handle_intermediate_metric_data | def _handle_intermediate_metric_data(self, data):
"""Call assessor to process intermediate results
"""
if data['type'] != 'PERIODICAL':
return
if self.assessor is None:
return
trial_job_id = data['trial_job_id']
if trial_job_id in _ended_trials:
... | python | def _handle_intermediate_metric_data(self, data):
"""Call assessor to process intermediate results
"""
if data['type'] != 'PERIODICAL':
return
if self.assessor is None:
return
trial_job_id = data['trial_job_id']
if trial_job_id in _ended_trials:
... | [
"def",
"_handle_intermediate_metric_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"[",
"'type'",
"]",
"!=",
"'PERIODICAL'",
":",
"return",
"if",
"self",
".",
"assessor",
"is",
"None",
":",
"return",
"trial_job_id",
"=",
"data",
"[",
"'trial_job_id... | Call assessor to process intermediate results | [
"Call",
"assessor",
"to",
"process",
"intermediate",
"results"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L167-L204 |
27,027 | Microsoft/nni | src/sdk/pynni/nni/msg_dispatcher.py | MsgDispatcher._earlystop_notify_tuner | def _earlystop_notify_tuner(self, data):
"""Send last intermediate result as final result to tuner in case the
trial is early stopped.
"""
_logger.debug('Early stop notify tuner data: [%s]', data)
data['type'] = 'FINAL'
if multi_thread_enabled():
self._handle_... | python | def _earlystop_notify_tuner(self, data):
"""Send last intermediate result as final result to tuner in case the
trial is early stopped.
"""
_logger.debug('Early stop notify tuner data: [%s]', data)
data['type'] = 'FINAL'
if multi_thread_enabled():
self._handle_... | [
"def",
"_earlystop_notify_tuner",
"(",
"self",
",",
"data",
")",
":",
"_logger",
".",
"debug",
"(",
"'Early stop notify tuner data: [%s]'",
",",
"data",
")",
"data",
"[",
"'type'",
"]",
"=",
"'FINAL'",
"if",
"multi_thread_enabled",
"(",
")",
":",
"self",
".",
... | Send last intermediate result as final result to tuner in case the
trial is early stopped. | [
"Send",
"last",
"intermediate",
"result",
"as",
"final",
"result",
"to",
"tuner",
"in",
"case",
"the",
"trial",
"is",
"early",
"stopped",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/msg_dispatcher.py#L206-L215 |
27,028 | Microsoft/nni | examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py | train_eval | def train_eval():
""" train and eval the model
"""
global trainloader
global testloader
global net
(x_train, y_train) = trainloader
(x_test, y_test) = testloader
# train procedure
net.fit(
x=x_train,
y=y_train,
batch_size=args.batch_size,
validation... | python | def train_eval():
""" train and eval the model
"""
global trainloader
global testloader
global net
(x_train, y_train) = trainloader
(x_test, y_test) = testloader
# train procedure
net.fit(
x=x_train,
y=y_train,
batch_size=args.batch_size,
validation... | [
"def",
"train_eval",
"(",
")",
":",
"global",
"trainloader",
"global",
"testloader",
"global",
"net",
"(",
"x_train",
",",
"y_train",
")",
"=",
"trainloader",
"(",
"x_test",
",",
"y_test",
")",
"=",
"testloader",
"# train procedure",
"net",
".",
"fit",
"(",
... | train and eval the model | [
"train",
"and",
"eval",
"the",
"model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/network_morphism/FashionMNIST/FashionMNIST_keras.py#L159-L188 |
27,029 | Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.get_n_r | def get_n_r(self):
"""return the values of n and r for the next round"""
return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon) | python | def get_n_r(self):
"""return the values of n and r for the next round"""
return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon) | [
"def",
"get_n_r",
"(",
"self",
")",
":",
"return",
"math",
".",
"floor",
"(",
"self",
".",
"n",
"/",
"self",
".",
"eta",
"**",
"self",
".",
"i",
"+",
"_epsilon",
")",
",",
"math",
".",
"floor",
"(",
"self",
".",
"r",
"*",
"self",
".",
"eta",
... | return the values of n and r for the next round | [
"return",
"the",
"values",
"of",
"n",
"and",
"r",
"for",
"the",
"next",
"round"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L159-L161 |
27,030 | Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.increase_i | def increase_i(self):
"""i means the ith round. Increase i by 1"""
self.i += 1
if self.i > self.bracket_id:
self.no_more_trial = True | python | def increase_i(self):
"""i means the ith round. Increase i by 1"""
self.i += 1
if self.i > self.bracket_id:
self.no_more_trial = True | [
"def",
"increase_i",
"(",
"self",
")",
":",
"self",
".",
"i",
"+=",
"1",
"if",
"self",
".",
"i",
">",
"self",
".",
"bracket_id",
":",
"self",
".",
"no_more_trial",
"=",
"True"
] | i means the ith round. Increase i by 1 | [
"i",
"means",
"the",
"ith",
"round",
".",
"Increase",
"i",
"by",
"1"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L163-L167 |
27,031 | Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket.get_hyperparameter_configurations | def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name
"""Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
... | python | def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name
"""Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
... | [
"def",
"get_hyperparameter_configurations",
"(",
"self",
",",
"num",
",",
"r",
",",
"searchspace_json",
",",
"random_state",
")",
":",
"# pylint: disable=invalid-name",
"global",
"_KEY",
"# pylint: disable=global-statement",
"assert",
"self",
".",
"i",
"==",
"0",
"hyp... | Randomly generate num hyperparameter configurations from search space
Parameters
----------
num: int
the number of hyperparameter configurations
Returns
-------
list
a list of hyperparameter configurations. Format: [[key1, value1], [key2,... | [
"Randomly",
"generate",
"num",
"hyperparameter",
"configurations",
"from",
"search",
"space"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L231-L253 |
27,032 | Microsoft/nni | src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py | Bracket._record_hyper_configs | def _record_hyper_configs(self, hyper_configs):
"""after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase th... | python | def _record_hyper_configs(self, hyper_configs):
"""after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase th... | [
"def",
"_record_hyper_configs",
"(",
"self",
",",
"hyper_configs",
")",
":",
"self",
".",
"hyper_configs",
".",
"append",
"(",
"hyper_configs",
")",
"self",
".",
"configs_perf",
".",
"append",
"(",
"dict",
"(",
")",
")",
"self",
".",
"num_finished_configs",
... | after generating one round of hyperconfigs, this function records the generated hyperconfigs,
creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs
in this round to be 0, and increase the round number.
Parameters
----------
... | [
"after",
"generating",
"one",
"round",
"of",
"hyperconfigs",
"this",
"function",
"records",
"the",
"generated",
"hyperconfigs",
"creates",
"a",
"dict",
"to",
"record",
"the",
"performance",
"when",
"those",
"hyperconifgs",
"are",
"running",
"set",
"the",
"number",... | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/hyperband_advisor/hyperband_advisor.py#L255-L269 |
27,033 | Microsoft/nni | tools/nni_trial_tool/url_utils.py | gen_send_stdout_url | def gen_send_stdout_url(ip, port):
'''Generate send stdout url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | python | def gen_send_stdout_url(ip, port):
'''Generate send stdout url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | [
"def",
"gen_send_stdout_url",
"(",
"ip",
",",
"port",
")",
":",
"return",
"'{0}:{1}{2}{3}/{4}/{5}'",
".",
"format",
"(",
"BASE_URL",
".",
"format",
"(",
"ip",
")",
",",
"port",
",",
"API_ROOT_URL",
",",
"STDOUT_API",
",",
"NNI_EXP_ID",
",",
"NNI_TRIAL_JOB_ID",... | Generate send stdout url | [
"Generate",
"send",
"stdout",
"url"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/url_utils.py#L23-L25 |
27,034 | Microsoft/nni | tools/nni_trial_tool/url_utils.py | gen_send_version_url | def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | python | def gen_send_version_url(ip, port):
'''Generate send error url'''
return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | [
"def",
"gen_send_version_url",
"(",
"ip",
",",
"port",
")",
":",
"return",
"'{0}:{1}{2}{3}/{4}/{5}'",
".",
"format",
"(",
"BASE_URL",
".",
"format",
"(",
"ip",
")",
",",
"port",
",",
"API_ROOT_URL",
",",
"VERSION_API",
",",
"NNI_EXP_ID",
",",
"NNI_TRIAL_JOB_ID... | Generate send error url | [
"Generate",
"send",
"error",
"url"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/url_utils.py#L27-L29 |
27,035 | Microsoft/nni | tools/nni_cmd/updater.py | validate_digit | def validate_digit(value, start, end):
'''validate if a digit is valid'''
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | python | def validate_digit(value, start, end):
'''validate if a digit is valid'''
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | [
"def",
"validate_digit",
"(",
"value",
",",
"start",
",",
"end",
")",
":",
"if",
"not",
"str",
"(",
"value",
")",
".",
"isdigit",
"(",
")",
"or",
"int",
"(",
"value",
")",
"<",
"start",
"or",
"int",
"(",
"value",
")",
">",
"end",
":",
"raise",
... | validate if a digit is valid | [
"validate",
"if",
"a",
"digit",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L32-L35 |
27,036 | Microsoft/nni | tools/nni_cmd/updater.py | validate_dispatcher | def validate_dispatcher(args):
'''validate if the dispatcher of the experiment supports importing data'''
nni_config = Config(get_config_filename(args)).get_config('experimentConfig')
if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'):
dispatcher_name = nni_config['tuner']['b... | python | def validate_dispatcher(args):
'''validate if the dispatcher of the experiment supports importing data'''
nni_config = Config(get_config_filename(args)).get_config('experimentConfig')
if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'):
dispatcher_name = nni_config['tuner']['b... | [
"def",
"validate_dispatcher",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
".",
"get_config",
"(",
"'experimentConfig'",
")",
"if",
"nni_config",
".",
"get",
"(",
"'tuner'",
")",
"and",
"nni_config",
... | validate if the dispatcher of the experiment supports importing data | [
"validate",
"if",
"the",
"dispatcher",
"of",
"the",
"experiment",
"supports",
"importing",
"data"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L42-L57 |
27,037 | Microsoft/nni | tools/nni_cmd/updater.py | load_search_space | def load_search_space(path):
'''load search space content'''
content = json.dumps(get_json_content(path))
if not content:
raise ValueError('searchSpace file should not be empty')
return content | python | def load_search_space(path):
'''load search space content'''
content = json.dumps(get_json_content(path))
if not content:
raise ValueError('searchSpace file should not be empty')
return content | [
"def",
"load_search_space",
"(",
"path",
")",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
"get_json_content",
"(",
"path",
")",
")",
"if",
"not",
"content",
":",
"raise",
"ValueError",
"(",
"'searchSpace file should not be empty'",
")",
"return",
"content"
] | load search space content | [
"load",
"search",
"space",
"content"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L59-L64 |
27,038 | Microsoft/nni | tools/nni_cmd/updater.py | update_experiment_profile | def update_experiment_profile(args, key, value):
'''call restful server to update experiment profile'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_get(experimen... | python | def update_experiment_profile(args, key, value):
'''call restful server to update experiment profile'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_get(experimen... | [
"def",
"update_experiment_profile",
"(",
"args",
",",
"key",
",",
"value",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
","... | call restful server to update experiment profile | [
"call",
"restful",
"server",
"to",
"update",
"experiment",
"profile"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L77-L92 |
27,039 | Microsoft/nni | tools/nni_cmd/updater.py | import_data | def import_data(args):
'''import additional data to the experiment'''
validate_file(args.filename)
validate_dispatcher(args)
content = load_search_space(args.filename)
args.port = get_experiment_port(args)
if args.port is not None:
if import_data_to_restful_server(args, content):
... | python | def import_data(args):
'''import additional data to the experiment'''
validate_file(args.filename)
validate_dispatcher(args)
content = load_search_space(args.filename)
args.port = get_experiment_port(args)
if args.port is not None:
if import_data_to_restful_server(args, content):
... | [
"def",
"import_data",
"(",
"args",
")",
":",
"validate_file",
"(",
"args",
".",
"filename",
")",
"validate_dispatcher",
"(",
"args",
")",
"content",
"=",
"load_search_space",
"(",
"args",
".",
"filename",
")",
"args",
".",
"port",
"=",
"get_experiment_port",
... | import additional data to the experiment | [
"import",
"additional",
"data",
"to",
"the",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L131-L141 |
27,040 | Microsoft/nni | tools/nni_cmd/updater.py | import_data_to_restful_server | def import_data_to_restful_server(args, content):
'''call restful server to import data to the experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(imp... | python | def import_data_to_restful_server(args, content):
'''call restful server to import data to the experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(imp... | [
"def",
"import_data_to_restful_server",
"(",
"args",
",",
"content",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
",",
"_",
... | call restful server to import data to the experiment | [
"call",
"restful",
"server",
"to",
"import",
"data",
"to",
"the",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/updater.py#L143-L154 |
27,041 | Microsoft/nni | tools/nni_cmd/config_schema.py | setType | def setType(key, type):
'''check key type'''
return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__)) | python | def setType(key, type):
'''check key type'''
return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__)) | [
"def",
"setType",
"(",
"key",
",",
"type",
")",
":",
"return",
"And",
"(",
"type",
",",
"error",
"=",
"SCHEMA_TYPE_ERROR",
"%",
"(",
"key",
",",
"type",
".",
"__name__",
")",
")"
] | check key type | [
"check",
"key",
"type"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_schema.py#L26-L28 |
27,042 | Microsoft/nni | tools/nni_cmd/config_schema.py | setNumberRange | def setNumberRange(key, keyType, start, end):
'''check number range'''
return And(
And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
) | python | def setNumberRange(key, keyType, start, end):
'''check number range'''
return And(
And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
) | [
"def",
"setNumberRange",
"(",
"key",
",",
"keyType",
",",
"start",
",",
"end",
")",
":",
"return",
"And",
"(",
"And",
"(",
"keyType",
",",
"error",
"=",
"SCHEMA_TYPE_ERROR",
"%",
"(",
"key",
",",
"keyType",
".",
"__name__",
")",
")",
",",
"And",
"(",... | check number range | [
"check",
"number",
"range"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_schema.py#L34-L39 |
27,043 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | keras_dropout | def keras_dropout(layer, rate):
'''keras dropout layer.
'''
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return laye... | python | def keras_dropout(layer, rate):
'''keras dropout layer.
'''
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return laye... | [
"def",
"keras_dropout",
"(",
"layer",
",",
"rate",
")",
":",
"from",
"keras",
"import",
"layers",
"input_dim",
"=",
"len",
"(",
"layer",
".",
"input",
".",
"shape",
")",
"if",
"input_dim",
"==",
"2",
":",
"return",
"layers",
".",
"SpatialDropout1D",
"(",... | keras dropout layer. | [
"keras",
"dropout",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L530-L544 |
27,044 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | to_real_keras_layer | def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_layer(layer, "Conv"):
return layers.Conv2D(
layer.filters,
layer.kernel_si... | python | def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_layer(layer, "Conv"):
return layers.Conv2D(
layer.filters,
layer.kernel_si... | [
"def",
"to_real_keras_layer",
"(",
"layer",
")",
":",
"from",
"keras",
"import",
"layers",
"if",
"is_layer",
"(",
"layer",
",",
"\"Dense\"",
")",
":",
"return",
"layers",
".",
"Dense",
"(",
"layer",
".",
"units",
",",
"input_shape",
"=",
"(",
"layer",
".... | real keras layer. | [
"real",
"keras",
"layer",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L547-L578 |
27,045 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_description_extractor | def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | python | def layer_description_extractor(layer, node_to_id):
'''get layer description.
'''
layer_input = layer.input
layer_output = layer.output
if layer_input is not None:
if isinstance(layer_input, Iterable):
layer_input = list(map(lambda x: node_to_id[x], layer_input))
else:
... | [
"def",
"layer_description_extractor",
"(",
"layer",
",",
"node_to_id",
")",
":",
"layer_input",
"=",
"layer",
".",
"input",
"layer_output",
"=",
"layer",
".",
"output",
"if",
"layer_input",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"layer_input",
",",... | get layer description. | [
"get",
"layer",
"description",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L613-L661 |
27,046 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_description_builder | def layer_description_builder(layer_information, id_to_node):
'''build layer from description.
'''
# pylint: disable=W0123
layer_type = layer_information[0]
layer_input_ids = layer_information[1]
if isinstance(layer_input_ids, Iterable):
layer_input = list(map(lambda x: id_to_node[x], l... | python | def layer_description_builder(layer_information, id_to_node):
'''build layer from description.
'''
# pylint: disable=W0123
layer_type = layer_information[0]
layer_input_ids = layer_information[1]
if isinstance(layer_input_ids, Iterable):
layer_input = list(map(lambda x: id_to_node[x], l... | [
"def",
"layer_description_builder",
"(",
"layer_information",
",",
"id_to_node",
")",
":",
"# pylint: disable=W0123",
"layer_type",
"=",
"layer_information",
"[",
"0",
"]",
"layer_input_ids",
"=",
"layer_information",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"layer_inp... | build layer from description. | [
"build",
"layer",
"from",
"description",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L664-L700 |
27,047 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/layers.py | layer_width | def layer_width(layer):
'''get layer width.
'''
if is_layer(layer, "Dense"):
return layer.units
if is_layer(layer, "Conv"):
return layer.filters
raise TypeError("The layer should be either Dense or Conv layer.") | python | def layer_width(layer):
'''get layer width.
'''
if is_layer(layer, "Dense"):
return layer.units
if is_layer(layer, "Conv"):
return layer.filters
raise TypeError("The layer should be either Dense or Conv layer.") | [
"def",
"layer_width",
"(",
"layer",
")",
":",
"if",
"is_layer",
"(",
"layer",
",",
"\"Dense\"",
")",
":",
"return",
"layer",
".",
"units",
"if",
"is_layer",
"(",
"layer",
",",
"\"Conv\"",
")",
":",
"return",
"layer",
".",
"filters",
"raise",
"TypeError",... | get layer width. | [
"get",
"layer",
"width",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layers.py#L703-L711 |
27,048 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.define_params | def define_params(self):
'''
Define parameters.
'''
input_dim = self.input_dim
hidden_dim = self.hidden_dim
prefix = self.name
self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1),
name='/'.join(... | python | def define_params(self):
'''
Define parameters.
'''
input_dim = self.input_dim
hidden_dim = self.hidden_dim
prefix = self.name
self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1),
name='/'.join(... | [
"def",
"define_params",
"(",
"self",
")",
":",
"input_dim",
"=",
"self",
".",
"input_dim",
"hidden_dim",
"=",
"self",
".",
"hidden_dim",
"prefix",
"=",
"self",
".",
"name",
"self",
".",
"w_matrix",
"=",
"tf",
".",
"Variable",
"(",
"tf",
".",
"random_norm... | Define parameters. | [
"Define",
"parameters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L38-L51 |
27,049 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.build | def build(self, x, h, mask=None):
'''
Build the GRU cell.
'''
xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
hu = tf.split(tf.matmul(h, self.U), 3, 1)
r = tf.sigmoid(xw[0] + hu[0])
z = tf.sigmoid(xw[1] + hu[1])
h1 = tf.tanh(xw[2] + r * hu[2])... | python | def build(self, x, h, mask=None):
'''
Build the GRU cell.
'''
xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
hu = tf.split(tf.matmul(h, self.U), 3, 1)
r = tf.sigmoid(xw[0] + hu[0])
z = tf.sigmoid(xw[1] + hu[1])
h1 = tf.tanh(xw[2] + r * hu[2])... | [
"def",
"build",
"(",
"self",
",",
"x",
",",
"h",
",",
"mask",
"=",
"None",
")",
":",
"xw",
"=",
"tf",
".",
"split",
"(",
"tf",
".",
"matmul",
"(",
"x",
",",
"self",
".",
"w_matrix",
")",
"+",
"self",
".",
"bias",
",",
"3",
",",
"1",
")",
... | Build the GRU cell. | [
"Build",
"the",
"GRU",
"cell",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L53-L65 |
27,050 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/rnn.py | GRU.build_sequence | def build_sequence(self, xs, masks, init, is_left_to_right):
'''
Build GRU sequence.
'''
states = []
last = init
if is_left_to_right:
for i, xs_i in enumerate(xs):
h = self.build(xs_i, last, masks[i])
states.append(h)
... | python | def build_sequence(self, xs, masks, init, is_left_to_right):
'''
Build GRU sequence.
'''
states = []
last = init
if is_left_to_right:
for i, xs_i in enumerate(xs):
h = self.build(xs_i, last, masks[i])
states.append(h)
... | [
"def",
"build_sequence",
"(",
"self",
",",
"xs",
",",
"masks",
",",
"init",
",",
"is_left_to_right",
")",
":",
"states",
"=",
"[",
"]",
"last",
"=",
"init",
"if",
"is_left_to_right",
":",
"for",
"i",
",",
"xs_i",
"in",
"enumerate",
"(",
"xs",
")",
":... | Build GRU sequence. | [
"Build",
"GRU",
"sequence",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/rnn.py#L67-L83 |
27,051 | Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | conv2d | def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | python | def conv2d(x_input, w_matrix):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | [
"def",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x_input",
",",
"w_matrix",
",",
"strides",
"=",
"[",
"1",
",",
"1",
",",
"1",
",",
"1",
"]",
",",
"padding",
"=",
"'SAME'",
")"
] | conv2d returns a 2d convolution layer with full stride. | [
"conv2d",
"returns",
"a",
"2d",
"convolution",
"layer",
"with",
"full",
"stride",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L149-L151 |
27,052 | Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | max_pool | def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | python | def max_pool(x_input, pool_size):
"""max_pool downsamples a feature map by 2X."""
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | [
"def",
"max_pool",
"(",
"x_input",
",",
"pool_size",
")",
":",
"return",
"tf",
".",
"nn",
".",
"max_pool",
"(",
"x_input",
",",
"ksize",
"=",
"[",
"1",
",",
"pool_size",
",",
"pool_size",
",",
"1",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"pool_siz... | max_pool downsamples a feature map by 2X. | [
"max_pool",
"downsamples",
"a",
"feature",
"map",
"by",
"2X",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L154-L157 |
27,053 | Microsoft/nni | tools/nni_annotation/examples/mnist_without_annotation.py | main | def main(params):
'''
Main function, build mnist network, run and send result to NNI.
'''
# Import data
mnist = download_mnist_retry(params['data_dir'])
print('Mnist download data done.')
logger.debug('Mnist download data done.')
# Create the model
# Build the graph for the deep net... | python | def main(params):
'''
Main function, build mnist network, run and send result to NNI.
'''
# Import data
mnist = download_mnist_retry(params['data_dir'])
print('Mnist download data done.')
logger.debug('Mnist download data done.')
# Create the model
# Build the graph for the deep net... | [
"def",
"main",
"(",
"params",
")",
":",
"# Import data",
"mnist",
"=",
"download_mnist_retry",
"(",
"params",
"[",
"'data_dir'",
"]",
")",
"print",
"(",
"'Mnist download data done.'",
")",
"logger",
".",
"debug",
"(",
"'Mnist download data done.'",
")",
"# Create ... | Main function, build mnist network, run and send result to NNI. | [
"Main",
"function",
"build",
"mnist",
"network",
"run",
"and",
"send",
"result",
"to",
"NNI",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/examples/mnist_without_annotation.py#L185-L237 |
27,054 | Microsoft/nni | tools/nni_cmd/command_utils.py | check_output_command | def check_output_command(file_path, head=None, tail=None):
'''call check_output command to read content from a file'''
if os.path.exists(file_path):
if sys.platform == 'win32':
cmds = ['powershell.exe', 'type', file_path]
if head:
cmds += ['|', 'select', '-first',... | python | def check_output_command(file_path, head=None, tail=None):
'''call check_output command to read content from a file'''
if os.path.exists(file_path):
if sys.platform == 'win32':
cmds = ['powershell.exe', 'type', file_path]
if head:
cmds += ['|', 'select', '-first',... | [
"def",
"check_output_command",
"(",
"file_path",
",",
"head",
"=",
"None",
",",
"tail",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"cmds",
"=",
"[",
... | call check_output command to read content from a file | [
"call",
"check_output",
"command",
"to",
"read",
"content",
"from",
"a",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L8-L27 |
27,055 | Microsoft/nni | tools/nni_cmd/command_utils.py | install_package_command | def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | python | def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | [
"def",
"install_package_command",
"(",
"package_name",
")",
":",
"#TODO refactor python logic",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"cmds",
"=",
"'python -m pip install --user {0}'",
".",
"format",
"(",
"package_name",
")",
"else",
":",
"cmds",
"="... | install python package from pip | [
"install",
"python",
"package",
"from",
"pip"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L38-L45 |
27,056 | Microsoft/nni | tools/nni_cmd/command_utils.py | install_requirements_command | def install_requirements_command(requirements_path):
'''install requirements.txt'''
cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt'
#TODO refactor python logic
if sys.platform == "win32":
cmds = cmds.format('python')
else:
cmds = cmds.format('py... | python | def install_requirements_command(requirements_path):
'''install requirements.txt'''
cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt'
#TODO refactor python logic
if sys.platform == "win32":
cmds = cmds.format('python')
else:
cmds = cmds.format('py... | [
"def",
"install_requirements_command",
"(",
"requirements_path",
")",
":",
"cmds",
"=",
"'cd '",
"+",
"requirements_path",
"+",
"' && {0} -m pip install --user -r requirements.txt'",
"#TODO refactor python logic",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"cmds"... | install requirements.txt | [
"install",
"requirements",
".",
"txt"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/command_utils.py#L47-L55 |
27,057 | Microsoft/nni | examples/trials/mnist-advisor/mnist.py | get_params | def get_params():
''' Get parameters from command line '''
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory")
parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate")
parser.add_... | python | def get_params():
''' Get parameters from command line '''
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory")
parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate")
parser.add_... | [
"def",
"get_params",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--data_dir\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'/tmp/tensorflow/mnist/input_data'",
",",
"help",
"=",
"\"data ... | Get parameters from command line | [
"Get",
"parameters",
"from",
"command",
"line"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-advisor/mnist.py#L211-L226 |
27,058 | Microsoft/nni | examples/trials/mnist-advisor/mnist.py | MnistNetwork.build_network | def build_network(self):
'''
Building network for mnist
'''
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.n... | python | def build_network(self):
'''
Building network for mnist
'''
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.n... | [
"def",
"build_network",
"(",
"self",
")",
":",
"# Reshape to use within a convolutional neural net.",
"# Last dimension is for \"features\" - there is only one here, since images are",
"# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.",
"with",
"tf",
".",
"name_scope",
"(",
... | Building network for mnist | [
"Building",
"network",
"for",
"mnist"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-advisor/mnist.py#L48-L122 |
27,059 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_experiment_time | def get_experiment_time(port):
'''get the startTime and endTime of an experiment'''
response = rest_get(experiment_url(port), REST_TIME_OUT)
if response and check_response(response):
content = convert_time_stamp_to_date(json.loads(response.text))
return content.get('startTime'), content.get(... | python | def get_experiment_time(port):
'''get the startTime and endTime of an experiment'''
response = rest_get(experiment_url(port), REST_TIME_OUT)
if response and check_response(response):
content = convert_time_stamp_to_date(json.loads(response.text))
return content.get('startTime'), content.get(... | [
"def",
"get_experiment_time",
"(",
"port",
")",
":",
"response",
"=",
"rest_get",
"(",
"experiment_url",
"(",
"port",
")",
",",
"REST_TIME_OUT",
")",
"if",
"response",
"and",
"check_response",
"(",
"response",
")",
":",
"content",
"=",
"convert_time_stamp_to_dat... | get the startTime and endTime of an experiment | [
"get",
"the",
"startTime",
"and",
"endTime",
"of",
"an",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L36-L42 |
27,060 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_experiment_status | def get_experiment_status(port):
'''get the status of an experiment'''
result, response = check_rest_server_quick(port)
if result:
return json.loads(response.text).get('status')
return None | python | def get_experiment_status(port):
'''get the status of an experiment'''
result, response = check_rest_server_quick(port)
if result:
return json.loads(response.text).get('status')
return None | [
"def",
"get_experiment_status",
"(",
"port",
")",
":",
"result",
",",
"response",
"=",
"check_rest_server_quick",
"(",
"port",
")",
"if",
"result",
":",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
".",
"get",
"(",
"'status'",
")",
... | get the status of an experiment | [
"get",
"the",
"status",
"of",
"an",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L44-L49 |
27,061 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | update_experiment | def update_experiment():
'''Update the experiment status in config file'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
return None
for key in experiment_dict.keys():
if isinstance(experiment_dict[key], dict):
... | python | def update_experiment():
'''Update the experiment status in config file'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
return None
for key in experiment_dict.keys():
if isinstance(experiment_dict[key], dict):
... | [
"def",
"update_experiment",
"(",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"return",
"None",
"for",
"key",
"in",
"experiment_... | Update the experiment status in config file | [
"Update",
"the",
"experiment",
"status",
"in",
"config",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L51-L73 |
27,062 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | check_experiment_id | def check_experiment_id(args):
'''check if the id is valid
'''
update_experiment()
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print_normal('There is no experiment running...')
return None
if not args.id:... | python | def check_experiment_id(args):
'''check if the id is valid
'''
update_experiment()
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print_normal('There is no experiment running...')
return None
if not args.id:... | [
"def",
"check_experiment_id",
"(",
"args",
")",
":",
"update_experiment",
"(",
")",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"print_norm... | check if the id is valid | [
"check",
"if",
"the",
"id",
"is",
"valid"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L75-L110 |
27,063 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_config_filename | def get_config_filename(args):
'''get the file name of config file'''
experiment_id = check_experiment_id(args)
if experiment_id is None:
print_error('Please set the experiment id!')
exit(1)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
... | python | def get_config_filename(args):
'''get the file name of config file'''
experiment_id = check_experiment_id(args)
if experiment_id is None:
print_error('Please set the experiment id!')
exit(1)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
... | [
"def",
"get_config_filename",
"(",
"args",
")",
":",
"experiment_id",
"=",
"check_experiment_id",
"(",
"args",
")",
"if",
"experiment_id",
"is",
"None",
":",
"print_error",
"(",
"'Please set the experiment id!'",
")",
"exit",
"(",
"1",
")",
"experiment_config",
"=... | get the file name of config file | [
"get",
"the",
"file",
"name",
"of",
"config",
"file"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L168-L176 |
27,064 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | convert_time_stamp_to_date | def convert_time_stamp_to_date(content):
'''Convert time stamp to date time format'''
start_time_stamp = content.get('startTime')
end_time_stamp = content.get('endTime')
if start_time_stamp:
start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S")
... | python | def convert_time_stamp_to_date(content):
'''Convert time stamp to date time format'''
start_time_stamp = content.get('startTime')
end_time_stamp = content.get('endTime')
if start_time_stamp:
start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S")
... | [
"def",
"convert_time_stamp_to_date",
"(",
"content",
")",
":",
"start_time_stamp",
"=",
"content",
".",
"get",
"(",
"'startTime'",
")",
"end_time_stamp",
"=",
"content",
".",
"get",
"(",
"'endTime'",
")",
"if",
"start_time_stamp",
":",
"start_time",
"=",
"dateti... | Convert time stamp to date time format | [
"Convert",
"time",
"stamp",
"to",
"date",
"time",
"format"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L188-L198 |
27,065 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | check_rest | def check_rest(args):
'''check if restful server is running'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if not running:
print_normal('Restful server is running...')
else:
pri... | python | def check_rest(args):
'''check if restful server is running'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if not running:
print_normal('Restful server is running...')
else:
pri... | [
"def",
"check_rest",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"running",
",",
"_",
"=",
"check_rest_server_quick",
"(... | check if restful server is running | [
"check",
"if",
"restful",
"server",
"is",
"running"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L200-L208 |
27,066 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | stop_experiment | def stop_experiment(args):
'''Stop the experiment which is running'''
experiment_id_list = parse_ids(args)
if experiment_id_list:
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
for experiment_id in experiment_id_list:
print_nor... | python | def stop_experiment(args):
'''Stop the experiment which is running'''
experiment_id_list = parse_ids(args)
if experiment_id_list:
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
for experiment_id in experiment_id_list:
print_nor... | [
"def",
"stop_experiment",
"(",
"args",
")",
":",
"experiment_id_list",
"=",
"parse_ids",
"(",
"args",
")",
"if",
"experiment_id_list",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(... | Stop the experiment which is running | [
"Stop",
"the",
"experiment",
"which",
"is",
"running"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L210-L234 |
27,067 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | list_experiment | def list_experiment(args):
'''Get experiment information'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not running...')
... | python | def list_experiment(args):
'''Get experiment information'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not running...')
... | [
"def",
"list_experiment",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"rest_pid",
"=",
"nni_config",
".",
"get_config",
... | Get experiment information | [
"Get",
"experiment",
"information"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L275-L292 |
27,068 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | experiment_status | def experiment_status(args):
'''Show the status of experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
result, response = check_rest_server_quick(rest_port)
if not result:
print_normal('Restful server is not running...')
else:
... | python | def experiment_status(args):
'''Show the status of experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
result, response = check_rest_server_quick(rest_port)
if not result:
print_normal('Restful server is not running...')
else:
... | [
"def",
"experiment_status",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"result",
",",
"response",
"=",
"check_rest_server... | Show the status of experiment | [
"Show",
"the",
"status",
"of",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L294-L302 |
27,069 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | log_internal | def log_internal(args, filetype):
'''internal function to call get_log_content'''
file_name = get_config_filename(args)
if filetype == 'stdout':
file_full_path = os.path.join(NNICTL_HOME_DIR, file_name, 'stdout')
else:
file_full_path = os.path.join(NNICTL_HOME_DIR, file_name, 'stderr')
... | python | def log_internal(args, filetype):
'''internal function to call get_log_content'''
file_name = get_config_filename(args)
if filetype == 'stdout':
file_full_path = os.path.join(NNICTL_HOME_DIR, file_name, 'stdout')
else:
file_full_path = os.path.join(NNICTL_HOME_DIR, file_name, 'stderr')
... | [
"def",
"log_internal",
"(",
"args",
",",
"filetype",
")",
":",
"file_name",
"=",
"get_config_filename",
"(",
"args",
")",
"if",
"filetype",
"==",
"'stdout'",
":",
"file_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"NNICTL_HOME_DIR",
",",
"file_name"... | internal function to call get_log_content | [
"internal",
"function",
"to",
"call",
"get_log_content"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L304-L311 |
27,070 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | log_trial | def log_trial(args):
''''get trial log path'''
trial_id_path_dict = {}
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not runn... | python | def log_trial(args):
''''get trial log path'''
trial_id_path_dict = {}
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not runn... | [
"def",
"log_trial",
"(",
"args",
")",
":",
"trial_id_path_dict",
"=",
"{",
"}",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"rest_pid",
"=",
... | get trial log path | [
"get",
"trial",
"log",
"path"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L321-L352 |
27,071 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | webui_url | def webui_url(args):
'''show the url of web ui'''
nni_config = Config(get_config_filename(args))
print_normal('{0} {1}'.format('Web UI url:', ' '.join(nni_config.get_config('webuiUrl')))) | python | def webui_url(args):
'''show the url of web ui'''
nni_config = Config(get_config_filename(args))
print_normal('{0} {1}'.format('Web UI url:', ' '.join(nni_config.get_config('webuiUrl')))) | [
"def",
"webui_url",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"print_normal",
"(",
"'{0} {1}'",
".",
"format",
"(",
"'Web UI url:'",
",",
"' '",
".",
"join",
"(",
"nni_config",
".",
"get_config",
... | show the url of web ui | [
"show",
"the",
"url",
"of",
"web",
"ui"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L359-L362 |
27,072 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | experiment_list | def experiment_list(args):
'''get the information of all experiments'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1)
update_experiment()
experiment_id_list = ... | python | def experiment_list(args):
'''get the information of all experiments'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1)
update_experiment()
experiment_id_list = ... | [
"def",
"experiment_list",
"(",
"args",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"print",
"(",
"'There is no experiment running..... | get the information of all experiments | [
"get",
"the",
"information",
"of",
"all",
"experiments"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L364-L387 |
27,073 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | get_time_interval | def get_time_interval(time1, time2):
'''get the interval of two times'''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2)... | python | def get_time_interval(time1, time2):
'''get the interval of two times'''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2)... | [
"def",
"get_time_interval",
"(",
"time1",
",",
"time2",
")",
":",
"try",
":",
"#convert time to timestamp",
"time1",
"=",
"time",
".",
"mktime",
"(",
"time",
".",
"strptime",
"(",
"time1",
",",
"'%Y/%m/%d %H:%M:%S'",
")",
")",
"time2",
"=",
"time",
".",
"m... | get the interval of two times | [
"get",
"the",
"interval",
"of",
"two",
"times"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L389-L405 |
27,074 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | show_experiment_info | def show_experiment_info():
'''show experiment information in monitor'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1)
update_experiment()
experiment_id_list =... | python | def show_experiment_info():
'''show experiment information in monitor'''
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
if not experiment_dict:
print('There is no experiment running...')
exit(1)
update_experiment()
experiment_id_list =... | [
"def",
"show_experiment_info",
"(",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"if",
"not",
"experiment_dict",
":",
"print",
"(",
"'There is no experiment running...'",
... | show experiment information in monitor | [
"show",
"experiment",
"information",
"in",
"monitor"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L407-L434 |
27,075 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | monitor_experiment | def monitor_experiment(args):
'''monitor the experiment'''
if args.time <= 0:
print_error('please input a positive integer as time interval, the unit is second.')
exit(1)
while True:
try:
os.system('clear')
update_experiment()
show_experiment_info(... | python | def monitor_experiment(args):
'''monitor the experiment'''
if args.time <= 0:
print_error('please input a positive integer as time interval, the unit is second.')
exit(1)
while True:
try:
os.system('clear')
update_experiment()
show_experiment_info(... | [
"def",
"monitor_experiment",
"(",
"args",
")",
":",
"if",
"args",
".",
"time",
"<=",
"0",
":",
"print_error",
"(",
"'please input a positive integer as time interval, the unit is second.'",
")",
"exit",
"(",
"1",
")",
"while",
"True",
":",
"try",
":",
"os",
".",... | monitor the experiment | [
"monitor",
"the",
"experiment"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L436-L451 |
27,076 | Microsoft/nni | tools/nni_cmd/nnictl_utils.py | export_trials_data | def export_trials_data(args):
"""export experiment metadata to csv
"""
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not runn... | python | def export_trials_data(args):
"""export experiment metadata to csv
"""
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not runn... | [
"def",
"export_trials_data",
"(",
"args",
")",
":",
"nni_config",
"=",
"Config",
"(",
"get_config_filename",
"(",
"args",
")",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"rest_pid",
"=",
"nni_config",
".",
"get_config",... | export experiment metadata to csv | [
"export",
"experiment",
"metadata",
"to",
"csv"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L474-L507 |
27,077 | Microsoft/nni | tools/nni_cmd/ssh_utils.py | copy_remote_directory_to_local | def copy_remote_directory_to_local(sftp, remote_path, local_path):
'''copy remote directory to local machine'''
try:
os.makedirs(local_path, exist_ok=True)
files = sftp.listdir(remote_path)
for file in files:
remote_full_path = os.path.join(remote_path, file)
loca... | python | def copy_remote_directory_to_local(sftp, remote_path, local_path):
'''copy remote directory to local machine'''
try:
os.makedirs(local_path, exist_ok=True)
files = sftp.listdir(remote_path)
for file in files:
remote_full_path = os.path.join(remote_path, file)
loca... | [
"def",
"copy_remote_directory_to_local",
"(",
"sftp",
",",
"remote_path",
",",
"local_path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"local_path",
",",
"exist_ok",
"=",
"True",
")",
"files",
"=",
"sftp",
".",
"listdir",
"(",
"remote_path",
")",
"... | copy remote directory to local machine | [
"copy",
"remote",
"directory",
"to",
"local",
"machine"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/ssh_utils.py#L33-L47 |
27,078 | Microsoft/nni | tools/nni_cmd/ssh_utils.py | create_ssh_sftp_client | def create_ssh_sftp_client(host_ip, port, username, password):
'''create ssh client'''
try:
check_environment()
import paramiko
conn = paramiko.Transport(host_ip, port)
conn.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(conn)
... | python | def create_ssh_sftp_client(host_ip, port, username, password):
'''create ssh client'''
try:
check_environment()
import paramiko
conn = paramiko.Transport(host_ip, port)
conn.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(conn)
... | [
"def",
"create_ssh_sftp_client",
"(",
"host_ip",
",",
"port",
",",
"username",
",",
"password",
")",
":",
"try",
":",
"check_environment",
"(",
")",
"import",
"paramiko",
"conn",
"=",
"paramiko",
".",
"Transport",
"(",
"host_ip",
",",
"port",
")",
"conn",
... | create ssh client | [
"create",
"ssh",
"client"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/ssh_utils.py#L49-L59 |
27,079 | Microsoft/nni | src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py | json2space | def json2space(x, oldy=None, name=NodeType.Root.value):
"""Change search space from json format to hyperopt format
"""
y = list()
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
name = name + '-' + _type
if _type == '... | python | def json2space(x, oldy=None, name=NodeType.Root.value):
"""Change search space from json format to hyperopt format
"""
y = list()
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
name = name + '-' + _type
if _type == '... | [
"def",
"json2space",
"(",
"x",
",",
"oldy",
"=",
"None",
",",
"name",
"=",
"NodeType",
".",
"Root",
".",
"value",
")",
":",
"y",
"=",
"list",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"if",
"NodeType",
".",
"Type",
".",
"va... | Change search space from json format to hyperopt format | [
"Change",
"search",
"space",
"from",
"json",
"format",
"to",
"hyperopt",
"format"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L61-L87 |
27,080 | Microsoft/nni | src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py | json2paramater | def json2paramater(x, is_rand, random_state, oldy=None, Rand=False, name=NodeType.Root.value):
"""Json to pramaters.
"""
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
_value = x[NodeType.Value.value]
name = name + '-' +... | python | def json2paramater(x, is_rand, random_state, oldy=None, Rand=False, name=NodeType.Root.value):
"""Json to pramaters.
"""
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
_value = x[NodeType.Value.value]
name = name + '-' +... | [
"def",
"json2paramater",
"(",
"x",
",",
"is_rand",
",",
"random_state",
",",
"oldy",
"=",
"None",
",",
"Rand",
"=",
"False",
",",
"name",
"=",
"NodeType",
".",
"Root",
".",
"value",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"if... | Json to pramaters. | [
"Json",
"to",
"pramaters",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L90-L128 |
27,081 | Microsoft/nni | src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py | _split_index | def _split_index(params):
"""Delete index information from params
Parameters
----------
params : dict
Returns
-------
result : dict
"""
result = {}
for key in params:
if isinstance(params[key], dict):
value = params[key]['_value']
else:
v... | python | def _split_index(params):
"""Delete index information from params
Parameters
----------
params : dict
Returns
-------
result : dict
"""
result = {}
for key in params:
if isinstance(params[key], dict):
value = params[key]['_value']
else:
v... | [
"def",
"_split_index",
"(",
"params",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"params",
":",
"if",
"isinstance",
"(",
"params",
"[",
"key",
"]",
",",
"dict",
")",
":",
"value",
"=",
"params",
"[",
"key",
"]",
"[",
"'_value'",
"]",
... | Delete index information from params
Parameters
----------
params : dict
Returns
-------
result : dict | [
"Delete",
"index",
"information",
"from",
"params"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L131-L149 |
27,082 | Microsoft/nni | src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py | EvolutionTuner.update_search_space | def update_search_space(self, search_space):
"""Update search space.
Search_space contains the information that user pre-defined.
Parameters
----------
search_space : dict
"""
self.searchspace_json = search_space
self.space = json2space(self.searchspace_... | python | def update_search_space(self, search_space):
"""Update search space.
Search_space contains the information that user pre-defined.
Parameters
----------
search_space : dict
"""
self.searchspace_json = search_space
self.space = json2space(self.searchspace_... | [
"def",
"update_search_space",
"(",
"self",
",",
"search_space",
")",
":",
"self",
".",
"searchspace_json",
"=",
"search_space",
"self",
".",
"space",
"=",
"json2space",
"(",
"self",
".",
"searchspace_json",
")",
"self",
".",
"random_state",
"=",
"np",
".",
"... | Update search space.
Search_space contains the information that user pre-defined.
Parameters
----------
search_space : dict | [
"Update",
"search",
"space",
".",
"Search_space",
"contains",
"the",
"information",
"that",
"user",
"pre",
"-",
"defined",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L215-L234 |
27,083 | Microsoft/nni | src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py | EvolutionTuner.receive_trial_result | def receive_trial_result(self, parameter_id, parameters, value):
'''Record the result from a trial
Parameters
----------
parameters: dict
value : dict/float
if value is dict, it should have "default" key.
value is final metrics of the trial.
'''
... | python | def receive_trial_result(self, parameter_id, parameters, value):
'''Record the result from a trial
Parameters
----------
parameters: dict
value : dict/float
if value is dict, it should have "default" key.
value is final metrics of the trial.
'''
... | [
"def",
"receive_trial_result",
"(",
"self",
",",
"parameter_id",
",",
"parameters",
",",
"value",
")",
":",
"reward",
"=",
"extract_scalar_reward",
"(",
"value",
")",
"if",
"parameter_id",
"not",
"in",
"self",
".",
"total_data",
":",
"raise",
"RuntimeError",
"... | Record the result from a trial
Parameters
----------
parameters: dict
value : dict/float
if value is dict, it should have "default" key.
value is final metrics of the trial. | [
"Record",
"the",
"result",
"from",
"a",
"trial"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L280-L300 |
27,084 | Microsoft/nni | examples/trials/auto-gbdt/main.py | load_data | def load_data(train_path='./data/regression.train', test_path='./data/regression.test'):
'''
Load or create dataset
'''
print('Load data...')
df_train = pd.read_csv(train_path, header=None, sep='\t')
df_test = pd.read_csv(test_path, header=None, sep='\t')
num = len(df_train)
split_num = ... | python | def load_data(train_path='./data/regression.train', test_path='./data/regression.test'):
'''
Load or create dataset
'''
print('Load data...')
df_train = pd.read_csv(train_path, header=None, sep='\t')
df_test = pd.read_csv(test_path, header=None, sep='\t')
num = len(df_train)
split_num = ... | [
"def",
"load_data",
"(",
"train_path",
"=",
"'./data/regression.train'",
",",
"test_path",
"=",
"'./data/regression.test'",
")",
":",
"print",
"(",
"'Load data...'",
")",
"df_train",
"=",
"pd",
".",
"read_csv",
"(",
"train_path",
",",
"header",
"=",
"None",
",",... | Load or create dataset | [
"Load",
"or",
"create",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/auto-gbdt/main.py#L48-L72 |
27,085 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | layer_distance | def layer_distance(a, b):
"""The distance between two layers."""
# pylint: disable=unidiomatic-typecheck
if type(a) != type(b):
return 1.0
if is_layer(a, "Conv"):
att_diff = [
(a.filters, b.filters),
(a.kernel_size, b.kernel_size),
(a.stride, b.stride)... | python | def layer_distance(a, b):
"""The distance between two layers."""
# pylint: disable=unidiomatic-typecheck
if type(a) != type(b):
return 1.0
if is_layer(a, "Conv"):
att_diff = [
(a.filters, b.filters),
(a.kernel_size, b.kernel_size),
(a.stride, b.stride)... | [
"def",
"layer_distance",
"(",
"a",
",",
"b",
")",
":",
"# pylint: disable=unidiomatic-typecheck",
"if",
"type",
"(",
"a",
")",
"!=",
"type",
"(",
"b",
")",
":",
"return",
"1.0",
"if",
"is_layer",
"(",
"a",
",",
"\"Conv\"",
")",
":",
"att_diff",
"=",
"[... | The distance between two layers. | [
"The",
"distance",
"between",
"two",
"layers",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L37-L56 |
27,086 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | attribute_difference | def attribute_difference(att_diff):
''' The attribute distance.
'''
ret = 0
for a_value, b_value in att_diff:
if max(a_value, b_value) == 0:
ret += 0
else:
ret += abs(a_value - b_value) * 1.0 / max(a_value, b_value)
return ret * 1.0 / len(att_diff) | python | def attribute_difference(att_diff):
''' The attribute distance.
'''
ret = 0
for a_value, b_value in att_diff:
if max(a_value, b_value) == 0:
ret += 0
else:
ret += abs(a_value - b_value) * 1.0 / max(a_value, b_value)
return ret * 1.0 / len(att_diff) | [
"def",
"attribute_difference",
"(",
"att_diff",
")",
":",
"ret",
"=",
"0",
"for",
"a_value",
",",
"b_value",
"in",
"att_diff",
":",
"if",
"max",
"(",
"a_value",
",",
"b_value",
")",
"==",
"0",
":",
"ret",
"+=",
"0",
"else",
":",
"ret",
"+=",
"abs",
... | The attribute distance. | [
"The",
"attribute",
"distance",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L59-L69 |
27,087 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | layers_distance | def layers_distance(list_a, list_b):
"""The distance between the layers of two neural networks."""
len_a = len(list_a)
len_b = len(list_b)
f = np.zeros((len_a + 1, len_b + 1))
f[-1][-1] = 0
for i in range(-1, len_a):
f[i][-1] = i + 1
for j in range(-1, len_b):
f[-1][j] = j + ... | python | def layers_distance(list_a, list_b):
"""The distance between the layers of two neural networks."""
len_a = len(list_a)
len_b = len(list_b)
f = np.zeros((len_a + 1, len_b + 1))
f[-1][-1] = 0
for i in range(-1, len_a):
f[i][-1] = i + 1
for j in range(-1, len_b):
f[-1][j] = j + ... | [
"def",
"layers_distance",
"(",
"list_a",
",",
"list_b",
")",
":",
"len_a",
"=",
"len",
"(",
"list_a",
")",
"len_b",
"=",
"len",
"(",
"list_b",
")",
"f",
"=",
"np",
".",
"zeros",
"(",
"(",
"len_a",
"+",
"1",
",",
"len_b",
"+",
"1",
")",
")",
"f"... | The distance between the layers of two neural networks. | [
"The",
"distance",
"between",
"the",
"layers",
"of",
"two",
"neural",
"networks",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L72-L89 |
27,088 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | skip_connection_distance | def skip_connection_distance(a, b):
"""The distance between two skip-connections."""
if a[2] != b[2]:
return 1.0
len_a = abs(a[1] - a[0])
len_b = abs(b[1] - b[0])
return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b)) | python | def skip_connection_distance(a, b):
"""The distance between two skip-connections."""
if a[2] != b[2]:
return 1.0
len_a = abs(a[1] - a[0])
len_b = abs(b[1] - b[0])
return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b)) | [
"def",
"skip_connection_distance",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"[",
"2",
"]",
"!=",
"b",
"[",
"2",
"]",
":",
"return",
"1.0",
"len_a",
"=",
"abs",
"(",
"a",
"[",
"1",
"]",
"-",
"a",
"[",
"0",
"]",
")",
"len_b",
"=",
"abs",
"(",... | The distance between two skip-connections. | [
"The",
"distance",
"between",
"two",
"skip",
"-",
"connections",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L92-L98 |
27,089 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | skip_connections_distance | def skip_connections_distance(list_a, list_b):
"""The distance between the skip-connections of two neural networks."""
distance_matrix = np.zeros((len(list_a), len(list_b)))
for i, a in enumerate(list_a):
for j, b in enumerate(list_b):
distance_matrix[i][j] = skip_connection_distance(a, ... | python | def skip_connections_distance(list_a, list_b):
"""The distance between the skip-connections of two neural networks."""
distance_matrix = np.zeros((len(list_a), len(list_b)))
for i, a in enumerate(list_a):
for j, b in enumerate(list_b):
distance_matrix[i][j] = skip_connection_distance(a, ... | [
"def",
"skip_connections_distance",
"(",
"list_a",
",",
"list_b",
")",
":",
"distance_matrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"list_a",
")",
",",
"len",
"(",
"list_b",
")",
")",
")",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"list... | The distance between the skip-connections of two neural networks. | [
"The",
"distance",
"between",
"the",
"skip",
"-",
"connections",
"of",
"two",
"neural",
"networks",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L101-L109 |
27,090 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | vector_distance | def vector_distance(a, b):
"""The Euclidean distance between two vectors."""
a = np.array(a)
b = np.array(b)
return np.linalg.norm(a - b) | python | def vector_distance(a, b):
"""The Euclidean distance between two vectors."""
a = np.array(a)
b = np.array(b)
return np.linalg.norm(a - b) | [
"def",
"vector_distance",
"(",
"a",
",",
"b",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"a",
")",
"b",
"=",
"np",
".",
"array",
"(",
"b",
")",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"a",
"-",
"b",
")"
] | The Euclidean distance between two vectors. | [
"The",
"Euclidean",
"distance",
"between",
"two",
"vectors",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L269-L273 |
27,091 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | contain | def contain(descriptors, target_descriptor):
"""Check if the target descriptor is in the descriptors."""
for descriptor in descriptors:
if edit_distance(descriptor, target_descriptor) < 1e-5:
return True
return False | python | def contain(descriptors, target_descriptor):
"""Check if the target descriptor is in the descriptors."""
for descriptor in descriptors:
if edit_distance(descriptor, target_descriptor) < 1e-5:
return True
return False | [
"def",
"contain",
"(",
"descriptors",
",",
"target_descriptor",
")",
":",
"for",
"descriptor",
"in",
"descriptors",
":",
"if",
"edit_distance",
"(",
"descriptor",
",",
"target_descriptor",
")",
"<",
"1e-5",
":",
"return",
"True",
"return",
"False"
] | Check if the target descriptor is in the descriptors. | [
"Check",
"if",
"the",
"target",
"descriptor",
"is",
"in",
"the",
"descriptors",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L449-L454 |
27,092 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | IncrementalGaussianProcess.incremental_fit | def incremental_fit(self, train_x, train_y):
""" Incrementally fit the regressor. """
if not self._first_fitted:
raise ValueError("The first_fit function needs to be called first.")
train_x, train_y = np.array(train_x), np.array(train_y)
# Incrementally compute K
up... | python | def incremental_fit(self, train_x, train_y):
""" Incrementally fit the regressor. """
if not self._first_fitted:
raise ValueError("The first_fit function needs to be called first.")
train_x, train_y = np.array(train_x), np.array(train_y)
# Incrementally compute K
up... | [
"def",
"incremental_fit",
"(",
"self",
",",
"train_x",
",",
"train_y",
")",
":",
"if",
"not",
"self",
".",
"_first_fitted",
":",
"raise",
"ValueError",
"(",
"\"The first_fit function needs to be called first.\"",
")",
"train_x",
",",
"train_y",
"=",
"np",
".",
"... | Incrementally fit the regressor. | [
"Incrementally",
"fit",
"the",
"regressor",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L160-L190 |
27,093 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | IncrementalGaussianProcess.first_fit | def first_fit(self, train_x, train_y):
""" Fit the regressor for the first time. """
train_x, train_y = np.array(train_x), np.array(train_y)
self._x = np.copy(train_x)
self._y = np.copy(train_y)
self._distance_matrix = edit_distance_matrix(self._x)
k_matrix = bourgain_e... | python | def first_fit(self, train_x, train_y):
""" Fit the regressor for the first time. """
train_x, train_y = np.array(train_x), np.array(train_y)
self._x = np.copy(train_x)
self._y = np.copy(train_y)
self._distance_matrix = edit_distance_matrix(self._x)
k_matrix = bourgain_e... | [
"def",
"first_fit",
"(",
"self",
",",
"train_x",
",",
"train_y",
")",
":",
"train_x",
",",
"train_y",
"=",
"np",
".",
"array",
"(",
"train_x",
")",
",",
"np",
".",
"array",
"(",
"train_y",
")",
"self",
".",
"_x",
"=",
"np",
".",
"copy",
"(",
"tra... | Fit the regressor for the first time. | [
"Fit",
"the",
"regressor",
"for",
"the",
"first",
"time",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L198-L214 |
27,094 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | BayesianOptimizer.acq | def acq(self, graph):
''' estimate the value of generated graph
'''
mean, std = self.gpr.predict(np.array([graph.extract_descriptor()]))
if self.optimizemode is OptimizeMode.Maximize:
return mean + self.beta * std
return mean - self.beta * std | python | def acq(self, graph):
''' estimate the value of generated graph
'''
mean, std = self.gpr.predict(np.array([graph.extract_descriptor()]))
if self.optimizemode is OptimizeMode.Maximize:
return mean + self.beta * std
return mean - self.beta * std | [
"def",
"acq",
"(",
"self",
",",
"graph",
")",
":",
"mean",
",",
"std",
"=",
"self",
".",
"gpr",
".",
"predict",
"(",
"np",
".",
"array",
"(",
"[",
"graph",
".",
"extract_descriptor",
"(",
")",
"]",
")",
")",
"if",
"self",
".",
"optimizemode",
"is... | estimate the value of generated graph | [
"estimate",
"the",
"value",
"of",
"generated",
"graph"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L396-L402 |
27,095 | Microsoft/nni | src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py | SearchTree.get_dict | def get_dict(self, u=None):
""" A recursive function to return the content of the tree in a dict."""
if u is None:
return self.get_dict(self.root)
children = []
for v in self.adj_list[u]:
children.append(self.get_dict(v))
ret = {"name": u, "children": chil... | python | def get_dict(self, u=None):
""" A recursive function to return the content of the tree in a dict."""
if u is None:
return self.get_dict(self.root)
children = []
for v in self.adj_list[u]:
children.append(self.get_dict(v))
ret = {"name": u, "children": chil... | [
"def",
"get_dict",
"(",
"self",
",",
"u",
"=",
"None",
")",
":",
"if",
"u",
"is",
"None",
":",
"return",
"self",
".",
"get_dict",
"(",
"self",
".",
"root",
")",
"children",
"=",
"[",
"]",
"for",
"v",
"in",
"self",
".",
"adj_list",
"[",
"u",
"]"... | A recursive function to return the content of the tree in a dict. | [
"A",
"recursive",
"function",
"to",
"return",
"the",
"content",
"of",
"the",
"tree",
"in",
"a",
"dict",
"."
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L480-L488 |
27,096 | Microsoft/nni | examples/trials/weight_sharing/ga_squad/graph.py | Layer.update_hash | def update_hash(self, layers: Iterable):
"""
Calculation of `hash_id` of Layer. Which is determined by the properties of itself, and the `hash_id`s of input layers
"""
if self.graph_type == LayerType.input.value:
return
hasher = hashlib.md5()
hasher.update(Lay... | python | def update_hash(self, layers: Iterable):
"""
Calculation of `hash_id` of Layer. Which is determined by the properties of itself, and the `hash_id`s of input layers
"""
if self.graph_type == LayerType.input.value:
return
hasher = hashlib.md5()
hasher.update(Lay... | [
"def",
"update_hash",
"(",
"self",
",",
"layers",
":",
"Iterable",
")",
":",
"if",
"self",
".",
"graph_type",
"==",
"LayerType",
".",
"input",
".",
"value",
":",
"return",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"hasher",
".",
"update",
"(",
... | Calculation of `hash_id` of Layer. Which is determined by the properties of itself, and the `hash_id`s of input layers | [
"Calculation",
"of",
"hash_id",
"of",
"Layer",
".",
"Which",
"is",
"determined",
"by",
"the",
"properties",
"of",
"itself",
"and",
"the",
"hash_id",
"s",
"of",
"input",
"layers"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph.py#L83-L96 |
27,097 | Microsoft/nni | examples/trials/mnist-batch-tune-keras/mnist-keras.py | create_mnist_model | def create_mnist_model(hyper_params, input_shape=(H, W, 1), num_classes=NUM_CLASSES):
'''
Create simple convolutional model
'''
layers = [
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2,... | python | def create_mnist_model(hyper_params, input_shape=(H, W, 1), num_classes=NUM_CLASSES):
'''
Create simple convolutional model
'''
layers = [
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2,... | [
"def",
"create_mnist_model",
"(",
"hyper_params",
",",
"input_shape",
"=",
"(",
"H",
",",
"W",
",",
"1",
")",
",",
"num_classes",
"=",
"NUM_CLASSES",
")",
":",
"layers",
"=",
"[",
"Conv2D",
"(",
"32",
",",
"kernel_size",
"=",
"(",
"3",
",",
"3",
")",... | Create simple convolutional model | [
"Create",
"simple",
"convolutional",
"model"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-batch-tune-keras/mnist-keras.py#L39-L60 |
27,098 | Microsoft/nni | examples/trials/mnist-batch-tune-keras/mnist-keras.py | load_mnist_data | def load_mnist_data(args):
'''
Load MNIST dataset
'''
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train]
x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test]
y_train = keras.utils... | python | def load_mnist_data(args):
'''
Load MNIST dataset
'''
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = (np.expand_dims(x_train, -1).astype(np.float) / 255.)[:args.num_train]
x_test = (np.expand_dims(x_test, -1).astype(np.float) / 255.)[:args.num_test]
y_train = keras.utils... | [
"def",
"load_mnist_data",
"(",
"args",
")",
":",
"(",
"x_train",
",",
"y_train",
")",
",",
"(",
"x_test",
",",
"y_test",
")",
"=",
"mnist",
".",
"load_data",
"(",
")",
"x_train",
"=",
"(",
"np",
".",
"expand_dims",
"(",
"x_train",
",",
"-",
"1",
")... | Load MNIST dataset | [
"Load",
"MNIST",
"dataset"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-batch-tune-keras/mnist-keras.py#L62-L76 |
27,099 | Microsoft/nni | tools/nni_cmd/config_utils.py | Config.get_all_config | def get_all_config(self):
'''get all of config values'''
return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':')) | python | def get_all_config(self):
'''get all of config values'''
return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':')) | [
"def",
"get_all_config",
"(",
"self",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"config",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")"
] | get all of config values | [
"get",
"all",
"of",
"config",
"values"
] | c7cc8db32da8d2ec77a382a55089f4e17247ce41 | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L35-L37 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.