repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
Microsoft/nni
tools/nni_cmd/nnictl_utils.py
trial_ls
def trial_ls(args): '''List trial''' 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...') return running, r...
python
def trial_ls(args): '''List trial''' 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...') return running, r...
[ "def", "trial_ls", "(", "args", ")", ":", "nni_config", "=", "Config", "(", "get_config_filename", "(", "args", ")", ")", "rest_port", "=", "nni_config", ".", "get_config", "(", "'restServerPort'", ")", "rest_pid", "=", "nni_config", ".", "get_config", "(", ...
List trial
[ "List", "trial" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L236-L255
train
Microsoft/nni
tools/nni_cmd/nnictl_utils.py
trial_kill
def trial_kill(args): '''List trial''' 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...') return running,...
python
def trial_kill(args): '''List trial''' 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...') return running,...
[ "def", "trial_kill", "(", "args", ")", ":", "nni_config", "=", "Config", "(", "get_config_filename", "(", "args", ")", ")", "rest_port", "=", "nni_config", ".", "get_config", "(", "'restServerPort'", ")", "rest_pid", "=", "nni_config", ".", "get_config", "(", ...
List trial
[ "List", "trial" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L257-L273
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
Microsoft/nni
tools/nni_cmd/nnictl_utils.py
parse_trial_data
def parse_trial_data(content): """output: List[Dict]""" trial_records = [] for trial_data in content: for phase_i in range(len(trial_data['hyperParameters'])): hparam = json.loads(trial_data['hyperParameters'][phase_i])['parameters'] hparam['id'] = trial_data['id'] ...
python
def parse_trial_data(content): """output: List[Dict]""" trial_records = [] for trial_data in content: for phase_i in range(len(trial_data['hyperParameters'])): hparam = json.loads(trial_data['hyperParameters'][phase_i])['parameters'] hparam['id'] = trial_data['id'] ...
[ "def", "parse_trial_data", "(", "content", ")", ":", "trial_records", "=", "[", "]", "for", "trial_data", "in", "content", ":", "for", "phase_i", "in", "range", "(", "len", "(", "trial_data", "[", "'hyperParameters'", "]", ")", ")", ":", "hparam", "=", "...
output: List[Dict]
[ "output", ":", "List", "[", "Dict", "]" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L454-L472
train
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
train
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
train
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
train
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
train
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
train
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
train
Microsoft/nni
src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py
Individual.mutation
def mutation(self, config=None, info=None, save_dir=None): """ Parameters ---------- config : str info : str save_dir : str """ self.result = None self.config = config self.restore_dir = self.save_dir self.save_dir = save_dir ...
python
def mutation(self, config=None, info=None, save_dir=None): """ Parameters ---------- config : str info : str save_dir : str """ self.result = None self.config = config self.restore_dir = self.save_dir self.save_dir = save_dir ...
[ "def", "mutation", "(", "self", ",", "config", "=", "None", ",", "info", "=", "None", ",", "save_dir", "=", "None", ")", ":", "self", ".", "result", "=", "None", "self", ".", "config", "=", "config", "self", ".", "restore_dir", "=", "self", ".", "s...
Parameters ---------- config : str info : str save_dir : str
[ "Parameters", "----------", "config", ":", "str", "info", ":", "str", "save_dir", ":", "str" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L176-L188
train
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
train
Microsoft/nni
src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py
EvolutionTuner.generate_parameters
def generate_parameters(self, parameter_id): """Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- config : dict """ if not self.population: raise Runtime...
python
def generate_parameters(self, parameter_id): """Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- config : dict """ if not self.population: raise Runtime...
[ "def", "generate_parameters", "(", "self", ",", "parameter_id", ")", ":", "if", "not", "self", ".", "population", ":", "raise", "RuntimeError", "(", "'The population is empty'", ")", "pos", "=", "-", "1", "for", "i", "in", "range", "(", "len", "(", "self",...
Returns a dict of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- config : dict
[ "Returns", "a", "dict", "of", "trial", "(", "hyper", "-", ")", "parameters", "as", "a", "serializable", "object", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/evolution_tuner/evolution_tuner.py#L236-L278
train
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
train
Microsoft/nni
src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py
get_json_content
def get_json_content(file_path): """Load json file content Parameters ---------- file_path: path to the file Raises ------ TypeError Error with the file path """ try: with open(file_path, 'r') as file: return json.load(file) except Ty...
python
def get_json_content(file_path): """Load json file content Parameters ---------- file_path: path to the file Raises ------ TypeError Error with the file path """ try: with open(file_path, 'r') as file: return json.load(file) except Ty...
[ "def", "get_json_content", "(", "file_path", ")", ":", "try", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "file", ":", "return", "json", ".", "load", "(", "file", ")", "except", "TypeError", "as", "err", ":", "print", "(", "'Error: '"...
Load json file content Parameters ---------- file_path: path to the file Raises ------ TypeError Error with the file path
[ "Load", "json", "file", "content", "Parameters", "----------", "file_path", ":", "path", "to", "the", "file", "Raises", "------", "TypeError", "Error", "with", "the", "file", "path" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py#L25-L43
train
Microsoft/nni
src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py
generate_pcs
def generate_pcs(nni_search_space_content): """Generate the Parameter Configuration Space (PCS) which defines the legal ranges of the parameters to be optimized and their default values. Generally, the format is: # parameter_name categorical {value_1, ..., value_N} [default value] # parameter_...
python
def generate_pcs(nni_search_space_content): """Generate the Parameter Configuration Space (PCS) which defines the legal ranges of the parameters to be optimized and their default values. Generally, the format is: # parameter_name categorical {value_1, ..., value_N} [default value] # parameter_...
[ "def", "generate_pcs", "(", "nni_search_space_content", ")", ":", "categorical_dict", "=", "{", "}", "search_space", "=", "nni_search_space_content", "with", "open", "(", "'param_config_space.pcs'", ",", "'w'", ")", "as", "pcs_fd", ":", "if", "isinstance", "(", "s...
Generate the Parameter Configuration Space (PCS) which defines the legal ranges of the parameters to be optimized and their default values. Generally, the format is: # parameter_name categorical {value_1, ..., value_N} [default value] # parameter_name ordinal {value_1, ..., value_N} [default value...
[ "Generate", "the", "Parameter", "Configuration", "Space", "(", "PCS", ")", "which", "defines", "the", "legal", "ranges", "of", "the", "parameters", "to", "be", "optimized", "and", "their", "default", "values", ".", "Generally", "the", "format", "is", ":", "#...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py#L45-L122
train
Microsoft/nni
src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py
generate_scenario
def generate_scenario(ss_content): """Generate the scenario. The scenario-object (smac.scenario.scenario.Scenario) is used to configure SMAC and can be constructed either by providing an actual scenario-object, or by specifing the options in a scenario file. Reference: https://automl.github.io/SMAC3/s...
python
def generate_scenario(ss_content): """Generate the scenario. The scenario-object (smac.scenario.scenario.Scenario) is used to configure SMAC and can be constructed either by providing an actual scenario-object, or by specifing the options in a scenario file. Reference: https://automl.github.io/SMAC3/s...
[ "def", "generate_scenario", "(", "ss_content", ")", ":", "with", "open", "(", "'scenario.txt'", ",", "'w'", ")", "as", "sce_fd", ":", "sce_fd", ".", "write", "(", "'deterministic = 0\\n'", ")", "#sce_fd.write('output_dir = \\n')", "sce_fd", ".", "write", "(", "'...
Generate the scenario. The scenario-object (smac.scenario.scenario.Scenario) is used to configure SMAC and can be constructed either by providing an actual scenario-object, or by specifing the options in a scenario file. Reference: https://automl.github.io/SMAC3/stable/options.html The format of the ...
[ "Generate", "the", "scenario", ".", "The", "scenario", "-", "object", "(", "smac", ".", "scenario", ".", "scenario", ".", "Scenario", ")", "is", "used", "to", "configure", "SMAC", "and", "can", "be", "constructed", "either", "by", "providing", "an", "actua...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/smac_tuner/convert_ss_to_scenario.py#L124-L210
train
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
train
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
train
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
train
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
train
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
train
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
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
edit_distance
def edit_distance(x, y): """The distance between two neural networks. Args: x: An instance of NetworkDescriptor. y: An instance of NetworkDescriptor Returns: The edit-distance between x and y. """ ret = layers_distance(x.layers, y.layers) ret += Constant.KERNEL_LAMBDA * ...
python
def edit_distance(x, y): """The distance between two neural networks. Args: x: An instance of NetworkDescriptor. y: An instance of NetworkDescriptor Returns: The edit-distance between x and y. """ ret = layers_distance(x.layers, y.layers) ret += Constant.KERNEL_LAMBDA * ...
[ "def", "edit_distance", "(", "x", ",", "y", ")", ":", "ret", "=", "layers_distance", "(", "x", ".", "layers", ",", "y", ".", "layers", ")", "ret", "+=", "Constant", ".", "KERNEL_LAMBDA", "*", "skip_connections_distance", "(", "x", ".", "skip_connections", ...
The distance between two neural networks. Args: x: An instance of NetworkDescriptor. y: An instance of NetworkDescriptor Returns: The edit-distance between x and y.
[ "The", "distance", "between", "two", "neural", "networks", ".", "Args", ":", "x", ":", "An", "instance", "of", "NetworkDescriptor", ".", "y", ":", "An", "instance", "of", "NetworkDescriptor", "Returns", ":", "The", "edit", "-", "distance", "between", "x", ...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L112-L125
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
edit_distance_matrix
def edit_distance_matrix(train_x, train_y=None): """Calculate the edit distance. Args: train_x: A list of neural architectures. train_y: A list of neural architectures. Returns: An edit-distance matrix. """ if train_y is None: ret = np.zeros((train_x.shape[0], train_x...
python
def edit_distance_matrix(train_x, train_y=None): """Calculate the edit distance. Args: train_x: A list of neural architectures. train_y: A list of neural architectures. Returns: An edit-distance matrix. """ if train_y is None: ret = np.zeros((train_x.shape[0], train_x...
[ "def", "edit_distance_matrix", "(", "train_x", ",", "train_y", "=", "None", ")", ":", "if", "train_y", "is", "None", ":", "ret", "=", "np", ".", "zeros", "(", "(", "train_x", ".", "shape", "[", "0", "]", ",", "train_x", ".", "shape", "[", "0", "]",...
Calculate the edit distance. Args: train_x: A list of neural architectures. train_y: A list of neural architectures. Returns: An edit-distance matrix.
[ "Calculate", "the", "edit", "distance", ".", "Args", ":", "train_x", ":", "A", "list", "of", "neural", "architectures", ".", "train_y", ":", "A", "list", "of", "neural", "architectures", ".", "Returns", ":", "An", "edit", "-", "distance", "matrix", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L243-L266
train
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
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
bourgain_embedding_matrix
def bourgain_embedding_matrix(distance_matrix): """Use Bourgain algorithm to embed the neural architectures based on their edit-distance. Args: distance_matrix: A matrix of edit-distances. Returns: A matrix of distances after embedding. """ distance_matrix = np.array(distance_matrix)...
python
def bourgain_embedding_matrix(distance_matrix): """Use Bourgain algorithm to embed the neural architectures based on their edit-distance. Args: distance_matrix: A matrix of edit-distances. Returns: A matrix of distances after embedding. """ distance_matrix = np.array(distance_matrix)...
[ "def", "bourgain_embedding_matrix", "(", "distance_matrix", ")", ":", "distance_matrix", "=", "np", ".", "array", "(", "distance_matrix", ")", "n", "=", "len", "(", "distance_matrix", ")", "if", "n", "==", "1", ":", "return", "distance_matrix", "np", ".", "r...
Use Bourgain algorithm to embed the neural architectures based on their edit-distance. Args: distance_matrix: A matrix of edit-distances. Returns: A matrix of distances after embedding.
[ "Use", "Bourgain", "algorithm", "to", "embed", "the", "neural", "architectures", "based", "on", "their", "edit", "-", "distance", ".", "Args", ":", "distance_matrix", ":", "A", "matrix", "of", "edit", "-", "distances", ".", "Returns", ":", "A", "matrix", "...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L276-L303
train
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
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
IncrementalGaussianProcess.fit
def fit(self, train_x, train_y): """ Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values. """ if self.first_fitted: self.incremental_fit(train_x, train_y) else: self.first_f...
python
def fit(self, train_x, train_y): """ Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values. """ if self.first_fitted: self.incremental_fit(train_x, train_y) else: self.first_f...
[ "def", "fit", "(", "self", ",", "train_x", ",", "train_y", ")", ":", "if", "self", ".", "first_fitted", ":", "self", ".", "incremental_fit", "(", "train_x", ",", "train_y", ")", "else", ":", "self", ".", "first_fit", "(", "train_x", ",", "train_y", ")"...
Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values.
[ "Fit", "the", "regressor", "with", "more", "data", ".", "Args", ":", "train_x", ":", "A", "list", "of", "NetworkDescriptor", ".", "train_y", ":", "A", "list", "of", "metric", "values", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L149-L158
train
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
train
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
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
IncrementalGaussianProcess.predict
def predict(self, train_x): """Predict the result. Args: train_x: A list of NetworkDescriptor. Returns: y_mean: The predicted mean. y_std: The predicted standard deviation. """ k_trans = np.exp(-np.power(edit_distance_matrix(train_x, self._x), ...
python
def predict(self, train_x): """Predict the result. Args: train_x: A list of NetworkDescriptor. Returns: y_mean: The predicted mean. y_std: The predicted standard deviation. """ k_trans = np.exp(-np.power(edit_distance_matrix(train_x, self._x), ...
[ "def", "predict", "(", "self", ",", "train_x", ")", ":", "k_trans", "=", "np", ".", "exp", "(", "-", "np", ".", "power", "(", "edit_distance_matrix", "(", "train_x", ",", "self", ".", "_x", ")", ",", "2", ")", ")", "y_mean", "=", "k_trans", ".", ...
Predict the result. Args: train_x: A list of NetworkDescriptor. Returns: y_mean: The predicted mean. y_std: The predicted standard deviation.
[ "Predict", "the", "result", ".", "Args", ":", "train_x", ":", "A", "list", "of", "NetworkDescriptor", ".", "Returns", ":", "y_mean", ":", "The", "predicted", "mean", ".", "y_std", ":", "The", "predicted", "standard", "deviation", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L216-L240
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
BayesianOptimizer.generate
def generate(self, descriptors): """Generate new architecture. Args: descriptors: All the searched neural architectures. Returns: graph: An instance of Graph. A morphed neural network with weights. father_id: The father node ID in the search tree. """ ...
python
def generate(self, descriptors): """Generate new architecture. Args: descriptors: All the searched neural architectures. Returns: graph: An instance of Graph. A morphed neural network with weights. father_id: The father node ID in the search tree. """ ...
[ "def", "generate", "(", "self", ",", "descriptors", ")", ":", "model_ids", "=", "self", ".", "search_tree", ".", "adj_list", ".", "keys", "(", ")", "target_graph", "=", "None", "father_id", "=", "None", "descriptors", "=", "deepcopy", "(", "descriptors", "...
Generate new architecture. Args: descriptors: All the searched neural architectures. Returns: graph: An instance of Graph. A morphed neural network with weights. father_id: The father node ID in the search tree.
[ "Generate", "new", "architecture", ".", "Args", ":", "descriptors", ":", "All", "the", "searched", "neural", "architectures", ".", "Returns", ":", "graph", ":", "An", "instance", "of", "Graph", ".", "A", "morphed", "neural", "network", "with", "weights", "."...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L333-L394
train
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
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py
SearchTree.add_child
def add_child(self, u, v): ''' add child to search tree itself. Arguments: u {int} -- father id v {int} -- child id ''' if u == -1: self.root = v self.adj_list[v] = [] return if v not in self.adj_list[u]: s...
python
def add_child(self, u, v): ''' add child to search tree itself. Arguments: u {int} -- father id v {int} -- child id ''' if u == -1: self.root = v self.adj_list[v] = [] return if v not in self.adj_list[u]: s...
[ "def", "add_child", "(", "self", ",", "u", ",", "v", ")", ":", "if", "u", "==", "-", "1", ":", "self", ".", "root", "=", "v", "self", ".", "adj_list", "[", "v", "]", "=", "[", "]", "return", "if", "v", "not", "in", "self", ".", "adj_list", ...
add child to search tree itself. Arguments: u {int} -- father id v {int} -- child id
[ "add", "child", "to", "search", "tree", "itself", ".", "Arguments", ":", "u", "{", "int", "}", "--", "father", "id", "v", "{", "int", "}", "--", "child", "id" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/bayesian.py#L464-L478
train
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
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/trial.py
train_with_graph
def train_with_graph(p_graph, qp_pairs, dev_qp_pairs): ''' Train a network from a specific graph. ''' global sess with tf.Graph().as_default(): train_model = GAG(cfg, embed, p_graph) train_model.build_net(is_training=True) tf.get_variable_scope().reuse_variables() dev...
python
def train_with_graph(p_graph, qp_pairs, dev_qp_pairs): ''' Train a network from a specific graph. ''' global sess with tf.Graph().as_default(): train_model = GAG(cfg, embed, p_graph) train_model.build_net(is_training=True) tf.get_variable_scope().reuse_variables() dev...
[ "def", "train_with_graph", "(", "p_graph", ",", "qp_pairs", ",", "dev_qp_pairs", ")", ":", "global", "sess", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "train_model", "=", "GAG", "(", "cfg", ",", "embed", ",", "p_graph", ")...
Train a network from a specific graph.
[ "Train", "a", "network", "from", "a", "specific", "graph", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/trial.py#L301-L377
train
Microsoft/nni
src/sdk/pynni/nni/tuner.py
Tuner.generate_multiple_parameters
def generate_multiple_parameters(self, parameter_id_list): """Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects. Call 'generate_parameters()' by 'count' times by default. User code must override either this function or 'generate_parameters()'. If ther...
python
def generate_multiple_parameters(self, parameter_id_list): """Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects. Call 'generate_parameters()' by 'count' times by default. User code must override either this function or 'generate_parameters()'. If ther...
[ "def", "generate_multiple_parameters", "(", "self", ",", "parameter_id_list", ")", ":", "result", "=", "[", "]", "for", "parameter_id", "in", "parameter_id_list", ":", "try", ":", "_logger", ".", "debug", "(", "\"generating param for {}\"", ".", "format", "(", "...
Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects. Call 'generate_parameters()' by 'count' times by default. User code must override either this function or 'generate_parameters()'. If there's no more trial, user should raise nni.NoMoreTrialError exception in...
[ "Returns", "multiple", "sets", "of", "trial", "(", "hyper", "-", ")", "parameters", "as", "iterable", "of", "serializable", "objects", ".", "Call", "generate_parameters", "()", "by", "count", "times", "by", "default", ".", "User", "code", "must", "override", ...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/tuner.py#L40-L56
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/graph.py
graph_loads
def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['graph_type'], layer['input'], layer['output'], layer['size'], layer['hash_id']) layer_info.is_delete = layer['is_delete'] _logger.debug('append layer {}'.f...
python
def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['graph_type'], layer['input'], layer['output'], layer['size'], layer['hash_id']) layer_info.is_delete = layer['is_delete'] _logger.debug('append layer {}'.f...
[ "def", "graph_loads", "(", "graph_json", ")", ":", "layers", "=", "[", "]", "for", "layer", "in", "graph_json", "[", "'layers'", "]", ":", "layer_info", "=", "Layer", "(", "layer", "[", "'graph_type'", "]", ",", "layer", "[", "'input'", "]", ",", "laye...
Load graph
[ "Load", "graph" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph.py#L131-L144
train
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
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/graph.py
Graph.update_hash
def update_hash(self): """ update hash id of each layer, in topological order/recursively hash id will be used in weight sharing """ _logger.debug('update hash') layer_in_cnt = [len(layer.input) for layer in self.layers] topo_queue = deque([i for i, layer in enume...
python
def update_hash(self): """ update hash id of each layer, in topological order/recursively hash id will be used in weight sharing """ _logger.debug('update hash') layer_in_cnt = [len(layer.input) for layer in self.layers] topo_queue = deque([i for i, layer in enume...
[ "def", "update_hash", "(", "self", ")", ":", "_logger", ".", "debug", "(", "'update hash'", ")", "layer_in_cnt", "=", "[", "len", "(", "layer", ".", "input", ")", "for", "layer", "in", "self", ".", "layers", "]", "topo_queue", "=", "deque", "(", "[", ...
update hash id of each layer, in topological order/recursively hash id will be used in weight sharing
[ "update", "hash", "id", "of", "each", "layer", "in", "topological", "order", "/", "recursively", "hash", "id", "will", "be", "used", "in", "weight", "sharing" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/graph.py#L239-L253
train
Microsoft/nni
src/sdk/pynni/nni/common.py
init_logger
def init_logger(logger_file_path, log_level_name='info'): """Initialize root logger. This will redirect anything from logging.getLogger() as well as stdout to specified file. logger_file_path: path of logger file (path-like object). """ log_level = log_level_map.get(log_level_name, logging.INFO) ...
python
def init_logger(logger_file_path, log_level_name='info'): """Initialize root logger. This will redirect anything from logging.getLogger() as well as stdout to specified file. logger_file_path: path of logger file (path-like object). """ log_level = log_level_map.get(log_level_name, logging.INFO) ...
[ "def", "init_logger", "(", "logger_file_path", ",", "log_level_name", "=", "'info'", ")", ":", "log_level", "=", "log_level_map", ".", "get", "(", "log_level_name", ",", "logging", ".", "INFO", ")", "logger_file", "=", "open", "(", "logger_file_path", ",", "'w...
Initialize root logger. This will redirect anything from logging.getLogger() as well as stdout to specified file. logger_file_path: path of logger file (path-like object).
[ "Initialize", "root", "logger", ".", "This", "will", "redirect", "anything", "from", "logging", ".", "getLogger", "()", "as", "well", "as", "stdout", "to", "specified", "file", ".", "logger_file_path", ":", "path", "of", "logger", "file", "(", "path", "-", ...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/common.py#L49-L69
train
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
train
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
train
Microsoft/nni
examples/trials/mnist-batch-tune-keras/mnist-keras.py
train
def train(args, params): ''' Train model ''' x_train, y_train, x_test, y_test = load_mnist_data(args) model = create_mnist_model(params) # nni model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, verbose=1, validation_data=(x_test, y_test), callbacks=[SendMet...
python
def train(args, params): ''' Train model ''' x_train, y_train, x_test, y_test = load_mnist_data(args) model = create_mnist_model(params) # nni model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, verbose=1, validation_data=(x_test, y_test), callbacks=[SendMet...
[ "def", "train", "(", "args", ",", "params", ")", ":", "x_train", ",", "y_train", ",", "x_test", ",", "y_test", "=", "load_mnist_data", "(", "args", ")", "model", "=", "create_mnist_model", "(", "params", ")", "# nni ", "model", ".", "fit", "(", "x_train"...
Train model
[ "Train", "model" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-batch-tune-keras/mnist-keras.py#L89-L102
train
Microsoft/nni
examples/trials/mnist-batch-tune-keras/mnist-keras.py
SendMetrics.on_epoch_end
def on_epoch_end(self, epoch, logs={}): ''' Run on end of each epoch ''' LOG.debug(logs) nni.report_intermediate_result(logs["val_acc"])
python
def on_epoch_end(self, epoch, logs={}): ''' Run on end of each epoch ''' LOG.debug(logs) nni.report_intermediate_result(logs["val_acc"])
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "logs", "=", "{", "}", ")", ":", "LOG", ".", "debug", "(", "logs", ")", "nni", ".", "report_intermediate_result", "(", "logs", "[", "\"val_acc\"", "]", ")" ]
Run on end of each epoch
[ "Run", "on", "end", "of", "each", "epoch" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/mnist-batch-tune-keras/mnist-keras.py#L82-L87
train
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
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Config.set_config
def set_config(self, key, value): '''set {key:value} paris to self.config''' self.config = self.read_file() self.config[key] = value self.write_file()
python
def set_config(self, key, value): '''set {key:value} paris to self.config''' self.config = self.read_file() self.config[key] = value self.write_file()
[ "def", "set_config", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "config", "=", "self", ".", "read_file", "(", ")", "self", ".", "config", "[", "key", "]", "=", "value", "self", ".", "write_file", "(", ")" ]
set {key:value} paris to self.config
[ "set", "{", "key", ":", "value", "}", "paris", "to", "self", ".", "config" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L39-L43
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Config.write_file
def write_file(self): '''save config to local file''' if self.config: try: with open(self.config_file, 'w') as file: json.dump(self.config, file) except IOError as error: print('Error:', error) return
python
def write_file(self): '''save config to local file''' if self.config: try: with open(self.config_file, 'w') as file: json.dump(self.config, file) except IOError as error: print('Error:', error) return
[ "def", "write_file", "(", "self", ")", ":", "if", "self", ".", "config", ":", "try", ":", "with", "open", "(", "self", ".", "config_file", ",", "'w'", ")", "as", "file", ":", "json", ".", "dump", "(", "self", ".", "config", ",", "file", ")", "exc...
save config to local file
[ "save", "config", "to", "local", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L49-L57
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Experiments.add_experiment
def add_experiment(self, id, port, time, file_name, platform): '''set {key:value} paris to self.experiment''' self.experiments[id] = {} self.experiments[id]['port'] = port self.experiments[id]['startTime'] = time self.experiments[id]['endTime'] = 'N/A' self.experiments[id...
python
def add_experiment(self, id, port, time, file_name, platform): '''set {key:value} paris to self.experiment''' self.experiments[id] = {} self.experiments[id]['port'] = port self.experiments[id]['startTime'] = time self.experiments[id]['endTime'] = 'N/A' self.experiments[id...
[ "def", "add_experiment", "(", "self", ",", "id", ",", "port", ",", "time", ",", "file_name", ",", "platform", ")", ":", "self", ".", "experiments", "[", "id", "]", "=", "{", "}", "self", ".", "experiments", "[", "id", "]", "[", "'port'", "]", "=", ...
set {key:value} paris to self.experiment
[ "set", "{", "key", ":", "value", "}", "paris", "to", "self", ".", "experiment" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L76-L85
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Experiments.update_experiment
def update_experiment(self, id, key, value): '''Update experiment''' if id not in self.experiments: return False self.experiments[id][key] = value self.write_file() return True
python
def update_experiment(self, id, key, value): '''Update experiment''' if id not in self.experiments: return False self.experiments[id][key] = value self.write_file() return True
[ "def", "update_experiment", "(", "self", ",", "id", ",", "key", ",", "value", ")", ":", "if", "id", "not", "in", "self", ".", "experiments", ":", "return", "False", "self", ".", "experiments", "[", "id", "]", "[", "key", "]", "=", "value", "self", ...
Update experiment
[ "Update", "experiment" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L87-L93
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Experiments.remove_experiment
def remove_experiment(self, id): '''remove an experiment by id''' if id in self.experiments: self.experiments.pop(id) self.write_file()
python
def remove_experiment(self, id): '''remove an experiment by id''' if id in self.experiments: self.experiments.pop(id) self.write_file()
[ "def", "remove_experiment", "(", "self", ",", "id", ")", ":", "if", "id", "in", "self", ".", "experiments", ":", "self", ".", "experiments", ".", "pop", "(", "id", ")", "self", ".", "write_file", "(", ")" ]
remove an experiment by id
[ "remove", "an", "experiment", "by", "id" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L95-L99
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Experiments.write_file
def write_file(self): '''save config to local file''' try: with open(self.experiment_file, 'w') as file: json.dump(self.experiments, file) except IOError as error: print('Error:', error) return
python
def write_file(self): '''save config to local file''' try: with open(self.experiment_file, 'w') as file: json.dump(self.experiments, file) except IOError as error: print('Error:', error) return
[ "def", "write_file", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "experiment_file", ",", "'w'", ")", "as", "file", ":", "json", ".", "dump", "(", "self", ".", "experiments", ",", "file", ")", "except", "IOError", "as", "error...
save config to local file
[ "save", "config", "to", "local", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L105-L112
train
Microsoft/nni
tools/nni_cmd/config_utils.py
Experiments.read_file
def read_file(self): '''load config from local file''' if os.path.exists(self.experiment_file): try: with open(self.experiment_file, 'r') as file: return json.load(file) except ValueError: return {} return {}
python
def read_file(self): '''load config from local file''' if os.path.exists(self.experiment_file): try: with open(self.experiment_file, 'r') as file: return json.load(file) except ValueError: return {} return {}
[ "def", "read_file", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "experiment_file", ")", ":", "try", ":", "with", "open", "(", "self", ".", "experiment_file", ",", "'r'", ")", "as", "file", ":", "return", "json", ...
load config from local file
[ "load", "config", "from", "local", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L114-L122
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
load_from_file
def load_from_file(path, fmt=None, is_training=True): ''' load data from file ''' if fmt is None: fmt = 'squad' assert fmt in ['squad', 'csv'], 'input format must be squad or csv' qp_pairs = [] if fmt == 'squad': with open(path) as data_file: data = json.load(data...
python
def load_from_file(path, fmt=None, is_training=True): ''' load data from file ''' if fmt is None: fmt = 'squad' assert fmt in ['squad', 'csv'], 'input format must be squad or csv' qp_pairs = [] if fmt == 'squad': with open(path) as data_file: data = json.load(data...
[ "def", "load_from_file", "(", "path", ",", "fmt", "=", "None", ",", "is_training", "=", "True", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "'squad'", "assert", "fmt", "in", "[", "'squad'", ",", "'csv'", "]", ",", "'input format must be squad o...
load data from file
[ "load", "data", "from", "file" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L67-L104
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
tokenize
def tokenize(qp_pair, tokenizer=None, is_training=False): ''' tokenize function. ''' question_tokens = tokenizer.tokenize(qp_pair['question']) passage_tokens = tokenizer.tokenize(qp_pair['passage']) if is_training: question_tokens = question_tokens[:300] passage_tokens = passage_...
python
def tokenize(qp_pair, tokenizer=None, is_training=False): ''' tokenize function. ''' question_tokens = tokenizer.tokenize(qp_pair['question']) passage_tokens = tokenizer.tokenize(qp_pair['passage']) if is_training: question_tokens = question_tokens[:300] passage_tokens = passage_...
[ "def", "tokenize", "(", "qp_pair", ",", "tokenizer", "=", "None", ",", "is_training", "=", "False", ")", ":", "question_tokens", "=", "tokenizer", ".", "tokenize", "(", "qp_pair", "[", "'question'", "]", ")", "passage_tokens", "=", "tokenizer", ".", "tokeniz...
tokenize function.
[ "tokenize", "function", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L107-L121
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
collect_vocab
def collect_vocab(qp_pairs): ''' Build the vocab from corpus. ''' vocab = set() for qp_pair in qp_pairs: for word in qp_pair['question_tokens']: vocab.add(word['word']) for word in qp_pair['passage_tokens']: vocab.add(word['word']) return vocab
python
def collect_vocab(qp_pairs): ''' Build the vocab from corpus. ''' vocab = set() for qp_pair in qp_pairs: for word in qp_pair['question_tokens']: vocab.add(word['word']) for word in qp_pair['passage_tokens']: vocab.add(word['word']) return vocab
[ "def", "collect_vocab", "(", "qp_pairs", ")", ":", "vocab", "=", "set", "(", ")", "for", "qp_pair", "in", "qp_pairs", ":", "for", "word", "in", "qp_pair", "[", "'question_tokens'", "]", ":", "vocab", ".", "add", "(", "word", "[", "'word'", "]", ")", ...
Build the vocab from corpus.
[ "Build", "the", "vocab", "from", "corpus", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L124-L134
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
shuffle_step
def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answer
python
def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answer
[ "def", "shuffle_step", "(", "entries", ",", "step", ")", ":", "answer", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "entries", ")", ",", "step", ")", ":", "sub", "=", "entries", "[", "i", ":", "i", "+", "step", "]", "...
Shuffle the step
[ "Shuffle", "the", "step" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L137-L146
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_batches
def get_batches(qp_pairs, batch_size, need_sort=True): ''' Get batches data and shuffle. ''' if need_sort: qp_pairs = sorted(qp_pairs, key=lambda qp: ( len(qp['passage_tokens']), qp['id']), reverse=True) batches = [{'qp_pairs': qp_pairs[i:(i + batch_size)]} for i i...
python
def get_batches(qp_pairs, batch_size, need_sort=True): ''' Get batches data and shuffle. ''' if need_sort: qp_pairs = sorted(qp_pairs, key=lambda qp: ( len(qp['passage_tokens']), qp['id']), reverse=True) batches = [{'qp_pairs': qp_pairs[i:(i + batch_size)]} for i i...
[ "def", "get_batches", "(", "qp_pairs", ",", "batch_size", ",", "need_sort", "=", "True", ")", ":", "if", "need_sort", ":", "qp_pairs", "=", "sorted", "(", "qp_pairs", ",", "key", "=", "lambda", "qp", ":", "(", "len", "(", "qp", "[", "'passage_tokens'", ...
Get batches data and shuffle.
[ "Get", "batches", "data", "and", "shuffle", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L149-L159
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_char_input
def get_char_input(data, char_dict, max_char_length): ''' Get char input. ''' batch_size = len(data) sequence_length = max(len(d) for d in data) char_id = np.zeros((max_char_length, sequence_length, batch_size), dtype=np.int32) char_lengths = np.zeros((sequence_length...
python
def get_char_input(data, char_dict, max_char_length): ''' Get char input. ''' batch_size = len(data) sequence_length = max(len(d) for d in data) char_id = np.zeros((max_char_length, sequence_length, batch_size), dtype=np.int32) char_lengths = np.zeros((sequence_length...
[ "def", "get_char_input", "(", "data", ",", "char_dict", ",", "max_char_length", ")", ":", "batch_size", "=", "len", "(", "data", ")", "sequence_length", "=", "max", "(", "len", "(", "d", ")", "for", "d", "in", "data", ")", "char_id", "=", "np", ".", ...
Get char input.
[ "Get", "char", "input", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L162-L179
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_word_input
def get_word_input(data, word_dict, embed, embed_dim): ''' Get word input. ''' batch_size = len(data) max_sequence_length = max(len(d) for d in data) sequence_length = max_sequence_length word_input = np.zeros((max_sequence_length, batch_size, embed_dim), dtype=np....
python
def get_word_input(data, word_dict, embed, embed_dim): ''' Get word input. ''' batch_size = len(data) max_sequence_length = max(len(d) for d in data) sequence_length = max_sequence_length word_input = np.zeros((max_sequence_length, batch_size, embed_dim), dtype=np....
[ "def", "get_word_input", "(", "data", ",", "word_dict", ",", "embed", ",", "embed_dim", ")", ":", "batch_size", "=", "len", "(", "data", ")", "max_sequence_length", "=", "max", "(", "len", "(", "d", ")", "for", "d", "in", "data", ")", "sequence_length", ...
Get word input.
[ "Get", "word", "input", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L182-L208
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_word_index
def get_word_index(tokens, char_index): ''' Given word return word index. ''' for (i, token) in enumerate(tokens): if token['char_end'] == 0: continue if token['char_begin'] <= char_index and char_index <= token['char_end']: return i return 0
python
def get_word_index(tokens, char_index): ''' Given word return word index. ''' for (i, token) in enumerate(tokens): if token['char_end'] == 0: continue if token['char_begin'] <= char_index and char_index <= token['char_end']: return i return 0
[ "def", "get_word_index", "(", "tokens", ",", "char_index", ")", ":", "for", "(", "i", ",", "token", ")", "in", "enumerate", "(", "tokens", ")", ":", "if", "token", "[", "'char_end'", "]", "==", "0", ":", "continue", "if", "token", "[", "'char_begin'", ...
Given word return word index.
[ "Given", "word", "return", "word", "index", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L211-L220
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_answer_begin_end
def get_answer_begin_end(data): ''' Get answer's index of begin and end. ''' begin = [] end = [] for qa_pair in data: tokens = qa_pair['passage_tokens'] char_begin = qa_pair['answer_begin'] char_end = qa_pair['answer_end'] word_begin = get_word_index(tokens, char_...
python
def get_answer_begin_end(data): ''' Get answer's index of begin and end. ''' begin = [] end = [] for qa_pair in data: tokens = qa_pair['passage_tokens'] char_begin = qa_pair['answer_begin'] char_end = qa_pair['answer_end'] word_begin = get_word_index(tokens, char_...
[ "def", "get_answer_begin_end", "(", "data", ")", ":", "begin", "=", "[", "]", "end", "=", "[", "]", "for", "qa_pair", "in", "data", ":", "tokens", "=", "qa_pair", "[", "'passage_tokens'", "]", "char_begin", "=", "qa_pair", "[", "'answer_begin'", "]", "ch...
Get answer's index of begin and end.
[ "Get", "answer", "s", "index", "of", "begin", "and", "end", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L223-L237
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
get_buckets
def get_buckets(min_length, max_length, bucket_count): ''' Get bucket by length. ''' if bucket_count <= 0: return [max_length] unit_length = int((max_length - min_length) // (bucket_count)) buckets = [min_length + unit_length * (i + 1) for i in range(0, bucket_count)] ...
python
def get_buckets(min_length, max_length, bucket_count): ''' Get bucket by length. ''' if bucket_count <= 0: return [max_length] unit_length = int((max_length - min_length) // (bucket_count)) buckets = [min_length + unit_length * (i + 1) for i in range(0, bucket_count)] ...
[ "def", "get_buckets", "(", "min_length", ",", "max_length", ",", "bucket_count", ")", ":", "if", "bucket_count", "<=", "0", ":", "return", "[", "max_length", "]", "unit_length", "=", "int", "(", "(", "max_length", "-", "min_length", ")", "//", "(", "bucket...
Get bucket by length.
[ "Get", "bucket", "by", "length", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L249-L259
train
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
WhitespaceTokenizer.tokenize
def tokenize(self, text): ''' tokenize function in Tokenizer. ''' start = -1 tokens = [] for i, character in enumerate(text): if character == ' ' or character == '\t': if start >= 0: word = text[start:i] ...
python
def tokenize(self, text): ''' tokenize function in Tokenizer. ''' start = -1 tokens = [] for i, character in enumerate(text): if character == ' ' or character == '\t': if start >= 0: word = text[start:i] ...
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "start", "=", "-", "1", "tokens", "=", "[", "]", "for", "i", ",", "character", "in", "enumerate", "(", "text", ")", ":", "if", "character", "==", "' '", "or", "character", "==", "'\\t'", ":", ...
tokenize function in Tokenizer.
[ "tokenize", "function", "in", "Tokenizer", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L38-L64
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
CustomerTuner.generate_new_id
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
python
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
[ "def", "generate_new_id", "(", "self", ")", ":", "self", ".", "events", ".", "append", "(", "Event", "(", ")", ")", "indiv_id", "=", "self", ".", "indiv_counter", "self", ".", "indiv_counter", "+=", "1", "return", "indiv_id" ]
generate new id and event hook for new Individual
[ "generate", "new", "id", "and", "event", "hook", "for", "new", "Individual" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L84-L91
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
CustomerTuner.init_population
def init_population(self, population_size, graph_max_layer, graph_min_layer): """ initialize populations for evolution tuner """ population = [] graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer, inputs=[Layer(LayerType.input.value, ...
python
def init_population(self, population_size, graph_max_layer, graph_min_layer): """ initialize populations for evolution tuner """ population = [] graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer, inputs=[Layer(LayerType.input.value, ...
[ "def", "init_population", "(", "self", ",", "population_size", ",", "graph_max_layer", ",", "graph_min_layer", ")", ":", "population", "=", "[", "]", "graph", "=", "Graph", "(", "max_layer_num", "=", "graph_max_layer", ",", "min_layer_num", "=", "graph_min_layer",...
initialize populations for evolution tuner
[ "initialize", "populations", "for", "evolution", "tuner" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L99-L113
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
CustomerTuner.generate_parameters
def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. An example configuration: ```json { "shared_id": [ "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", ...
python
def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. An example configuration: ```json { "shared_id": [ "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", ...
[ "def", "generate_parameters", "(", "self", ",", "parameter_id", ")", ":", "logger", ".", "debug", "(", "'acquiring lock for param {}'", ".", "format", "(", "parameter_id", ")", ")", "self", ".", "thread_lock", ".", "acquire", "(", ")", "logger", ".", "debug", ...
Returns a set of trial graph config, as a serializable object. An example configuration: ```json { "shared_id": [ "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", "11f646e9f650f5f3fedc12b6349ec60f", ...
[ "Returns", "a", "set", "of", "trial", "graph", "config", "as", "a", "serializable", "object", ".", "An", "example", "configuration", ":", "json", "{", "shared_id", ":", "[", "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", "11f646e9f650f5f3fedc12b...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L115-L197
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
CustomerTuner.receive_trial_result
def receive_trial_result(self, parameter_id, parameters, value): ''' Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward ''' logger.debug('acquiring lock for param {...
python
def receive_trial_result(self, parameter_id, parameters, value): ''' Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward ''' logger.debug('acquiring lock for param {...
[ "def", "receive_trial_result", "(", "self", ",", "parameter_id", ",", "parameters", ",", "value", ")", ":", "logger", ".", "debug", "(", "'acquiring lock for param {}'", ".", "format", "(", "parameter_id", ")", ")", "self", ".", "thread_lock", ".", "acquire", ...
Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward
[ "Record", "an", "observation", "of", "the", "objective", "function", "parameter_id", ":", "int", "parameters", ":", "dict", "of", "parameters", "value", ":", "final", "metrics", "of", "the", "trial", "including", "reward" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L199-L222
train
Microsoft/nni
src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py
MedianstopAssessor._update_data
def _update_data(self, trial_job_id, trial_history): """update data Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial """ if trial_job_id not in self.running_history: ...
python
def _update_data(self, trial_job_id, trial_history): """update data Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial """ if trial_job_id not in self.running_history: ...
[ "def", "_update_data", "(", "self", ",", "trial_job_id", ",", "trial_history", ")", ":", "if", "trial_job_id", "not", "in", "self", ".", "running_history", ":", "self", ".", "running_history", "[", "trial_job_id", "]", "=", "[", "]", "self", ".", "running_hi...
update data Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial
[ "update", "data" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py#L47-L59
train
Microsoft/nni
src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py
MedianstopAssessor.trial_end
def trial_end(self, trial_job_id, success): """trial_end Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise """ if trial_job_id in self.running_history: ...
python
def trial_end(self, trial_job_id, success): """trial_end Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise """ if trial_job_id in self.running_history: ...
[ "def", "trial_end", "(", "self", ",", "trial_job_id", ",", "success", ")", ":", "if", "trial_job_id", "in", "self", ".", "running_history", ":", "if", "success", ":", "cnt", "=", "0", "history_sum", "=", "0", "self", ".", "completed_avg_history", "[", "tri...
trial_end Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise
[ "trial_end", "Parameters", "----------", "trial_job_id", ":", "int", "trial", "job", "id", "success", ":", "bool", "True", "if", "succssfully", "finish", "the", "experiment", "False", "otherwise" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py#L61-L82
train
Microsoft/nni
src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py
MedianstopAssessor.assess_trial
def assess_trial(self, trial_job_id, trial_history): """assess_trial Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool As...
python
def assess_trial(self, trial_job_id, trial_history): """assess_trial Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool As...
[ "def", "assess_trial", "(", "self", ",", "trial_job_id", ",", "trial_history", ")", ":", "curr_step", "=", "len", "(", "trial_history", ")", "if", "curr_step", "<", "self", ".", "start_step", ":", "return", "AssessResult", ".", "Good", "try", ":", "num_trial...
assess_trial Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool AssessResult.Good or AssessResult.Bad Raises ----...
[ "assess_trial", "Parameters", "----------", "trial_job_id", ":", "int", "trial", "job", "id", "trial_history", ":", "list", "The", "history", "performance", "matrix", "of", "each", "trial" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py#L84-L136
train
Microsoft/nni
tools/nni_trial_tool/hdfsClientUtility.py
copyHdfsDirectoryToLocal
def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient): '''Copy directory from HDFS to local''' if not os.path.exists(localDirectory): os.makedirs(localDirectory) try: listing = hdfsClient.list_status(hdfsDirectory) except Exception as exception: nni_log(LogType....
python
def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient): '''Copy directory from HDFS to local''' if not os.path.exists(localDirectory): os.makedirs(localDirectory) try: listing = hdfsClient.list_status(hdfsDirectory) except Exception as exception: nni_log(LogType....
[ "def", "copyHdfsDirectoryToLocal", "(", "hdfsDirectory", ",", "localDirectory", ",", "hdfsClient", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "localDirectory", ")", ":", "os", ".", "makedirs", "(", "localDirectory", ")", "try", ":", "listi...
Copy directory from HDFS to local
[ "Copy", "directory", "from", "HDFS", "to", "local" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L26-L46
train
Microsoft/nni
tools/nni_trial_tool/hdfsClientUtility.py
copyHdfsFileToLocal
def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True): '''Copy file from HDFS to local''' if not hdfsClient.exists(hdfsFilePath): raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath)) try: file_status = hdfsClient.get_file_status(hdfsFilePath) ...
python
def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True): '''Copy file from HDFS to local''' if not hdfsClient.exists(hdfsFilePath): raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath)) try: file_status = hdfsClient.get_file_status(hdfsFilePath) ...
[ "def", "copyHdfsFileToLocal", "(", "hdfsFilePath", ",", "localFilePath", ",", "hdfsClient", ",", "override", "=", "True", ")", ":", "if", "not", "hdfsClient", ".", "exists", "(", "hdfsFilePath", ")", ":", "raise", "Exception", "(", "'HDFS file {} does not exist!'"...
Copy file from HDFS to local
[ "Copy", "file", "from", "HDFS", "to", "local" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L48-L67
train
Microsoft/nni
tools/nni_trial_tool/hdfsClientUtility.py
copyDirectoryToHdfs
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient): '''Copy directory from local to HDFS''' if not os.path.exists(localDirectory): raise Exception('Local Directory does not exist!') hdfsClient.mkdirs(hdfsDirectory) result = True for file in os.listdir(localDirectory): ...
python
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient): '''Copy directory from local to HDFS''' if not os.path.exists(localDirectory): raise Exception('Local Directory does not exist!') hdfsClient.mkdirs(hdfsDirectory) result = True for file in os.listdir(localDirectory): ...
[ "def", "copyDirectoryToHdfs", "(", "localDirectory", ",", "hdfsDirectory", ",", "hdfsClient", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "localDirectory", ")", ":", "raise", "Exception", "(", "'Local Directory does not exist!'", ")", "hdfsClient...
Copy directory from local to HDFS
[ "Copy", "directory", "from", "local", "to", "HDFS" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L69-L91
train
Microsoft/nni
tools/nni_trial_tool/hdfsClientUtility.py
copyFileToHdfs
def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True): '''Copy a local file to HDFS directory''' if not os.path.exists(localFilePath): raise Exception('Local file Path does not exist!') if os.path.isdir(localFilePath): raise Exception('localFile should not a directory!')...
python
def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True): '''Copy a local file to HDFS directory''' if not os.path.exists(localFilePath): raise Exception('Local file Path does not exist!') if os.path.isdir(localFilePath): raise Exception('localFile should not a directory!')...
[ "def", "copyFileToHdfs", "(", "localFilePath", ",", "hdfsFilePath", ",", "hdfsClient", ",", "override", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "localFilePath", ")", ":", "raise", "Exception", "(", "'Local file Path does not ...
Copy a local file to HDFS directory
[ "Copy", "a", "local", "file", "to", "HDFS", "directory" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_trial_tool/hdfsClientUtility.py#L93-L109
train
Microsoft/nni
examples/trials/sklearn/regression/main.py
load_data
def load_data(): '''Load dataset, use boston dataset''' boston = load_boston() X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25) #normalize data ss_X = StandardScaler() ss_y = StandardScaler() X_train = ss_X.fit_transform(X_trai...
python
def load_data(): '''Load dataset, use boston dataset''' boston = load_boston() X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25) #normalize data ss_X = StandardScaler() ss_y = StandardScaler() X_train = ss_X.fit_transform(X_trai...
[ "def", "load_data", "(", ")", ":", "boston", "=", "load_boston", "(", ")", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "boston", ".", "data", ",", "boston", ".", "target", ",", "random_state", "=", "99", ",", ...
Load dataset, use boston dataset
[ "Load", "dataset", "use", "boston", "dataset" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/regression/main.py#L33-L46
train
Microsoft/nni
examples/trials/sklearn/regression/main.py
get_model
def get_model(PARAMS): '''Get model according to parameters''' model_dict = { 'LinearRegression': LinearRegression(), 'SVR': SVR(), 'KNeighborsRegressor': KNeighborsRegressor(), 'DecisionTreeRegressor': DecisionTreeRegressor() } if not model_dict.get(PARAMS['model_name'])...
python
def get_model(PARAMS): '''Get model according to parameters''' model_dict = { 'LinearRegression': LinearRegression(), 'SVR': SVR(), 'KNeighborsRegressor': KNeighborsRegressor(), 'DecisionTreeRegressor': DecisionTreeRegressor() } if not model_dict.get(PARAMS['model_name'])...
[ "def", "get_model", "(", "PARAMS", ")", ":", "model_dict", "=", "{", "'LinearRegression'", ":", "LinearRegression", "(", ")", ",", "'SVR'", ":", "SVR", "(", ")", ",", "'KNeighborsRegressor'", ":", "KNeighborsRegressor", "(", ")", ",", "'DecisionTreeRegressor'", ...
Get model according to parameters
[ "Get", "model", "according", "to", "parameters" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/regression/main.py#L55-L77
train
Microsoft/nni
examples/trials/sklearn/regression/main.py
run
def run(X_train, X_test, y_train, y_test, PARAMS): '''Train model and predict result''' model.fit(X_train, y_train) predict_y = model.predict(X_test) score = r2_score(y_test, predict_y) LOG.debug('r2 score: %s' % score) nni.report_final_result(score)
python
def run(X_train, X_test, y_train, y_test, PARAMS): '''Train model and predict result''' model.fit(X_train, y_train) predict_y = model.predict(X_test) score = r2_score(y_test, predict_y) LOG.debug('r2 score: %s' % score) nni.report_final_result(score)
[ "def", "run", "(", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", ",", "PARAMS", ")", ":", "model", ".", "fit", "(", "X_train", ",", "y_train", ")", "predict_y", "=", "model", ".", "predict", "(", "X_test", ")", "score", "=", "r2_score", "(...
Train model and predict result
[ "Train", "model", "and", "predict", "result" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/sklearn/regression/main.py#L80-L86
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
NetworkDescriptor.add_skip_connection
def add_skip_connection(self, u, v, connection_type): """ Add a skip-connection to the descriptor. Args: u: Number of convolutional layers before the starting point. v: Number of convolutional layers before the ending point. connection_type: Must be either CONCAT_CONN...
python
def add_skip_connection(self, u, v, connection_type): """ Add a skip-connection to the descriptor. Args: u: Number of convolutional layers before the starting point. v: Number of convolutional layers before the ending point. connection_type: Must be either CONCAT_CONN...
[ "def", "add_skip_connection", "(", "self", ",", "u", ",", "v", ",", "connection_type", ")", ":", "if", "connection_type", "not", "in", "[", "self", ".", "CONCAT_CONNECT", ",", "self", ".", "ADD_CONNECT", "]", ":", "raise", "ValueError", "(", "\"connection_ty...
Add a skip-connection to the descriptor. Args: u: Number of convolutional layers before the starting point. v: Number of convolutional layers before the ending point. connection_type: Must be either CONCAT_CONNECT or ADD_CONNECT.
[ "Add", "a", "skip", "-", "connection", "to", "the", "descriptor", ".", "Args", ":", "u", ":", "Number", "of", "convolutional", "layers", "before", "the", "starting", "point", ".", "v", ":", "Number", "of", "convolutional", "layers", "before", "the", "endin...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L75-L87
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
NetworkDescriptor.to_json
def to_json(self): ''' NetworkDescriptor to json representation ''' skip_list = [] for u, v, connection_type in self.skip_connections: skip_list.append({"from": u, "to": v, "type": connection_type}) return {"node_list": self.layers, "skip_list": skip_list}
python
def to_json(self): ''' NetworkDescriptor to json representation ''' skip_list = [] for u, v, connection_type in self.skip_connections: skip_list.append({"from": u, "to": v, "type": connection_type}) return {"node_list": self.layers, "skip_list": skip_list}
[ "def", "to_json", "(", "self", ")", ":", "skip_list", "=", "[", "]", "for", "u", ",", "v", ",", "connection_type", "in", "self", ".", "skip_connections", ":", "skip_list", ".", "append", "(", "{", "\"from\"", ":", "u", ",", "\"to\"", ":", "v", ",", ...
NetworkDescriptor to json representation
[ "NetworkDescriptor", "to", "json", "representation" ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L89-L96
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph.add_layer
def add_layer(self, layer, input_node_id): """Add a layer to the Graph. Args: layer: An instance of the subclasses of StubLayer in layers.py. input_node_id: An integer. The ID of the input node of the layer. Returns: output_node_id: An integer. The ID of the o...
python
def add_layer(self, layer, input_node_id): """Add a layer to the Graph. Args: layer: An instance of the subclasses of StubLayer in layers.py. input_node_id: An integer. The ID of the input node of the layer. Returns: output_node_id: An integer. The ID of the o...
[ "def", "add_layer", "(", "self", ",", "layer", ",", "input_node_id", ")", ":", "if", "isinstance", "(", "input_node_id", ",", "Iterable", ")", ":", "layer", ".", "input", "=", "list", "(", "map", "(", "lambda", "x", ":", "self", ".", "node_list", "[", ...
Add a layer to the Graph. Args: layer: An instance of the subclasses of StubLayer in layers.py. input_node_id: An integer. The ID of the input node of the layer. Returns: output_node_id: An integer. The ID of the output node of the layer.
[ "Add", "a", "layer", "to", "the", "Graph", ".", "Args", ":", "layer", ":", "An", "instance", "of", "the", "subclasses", "of", "StubLayer", "in", "layers", ".", "py", ".", "input_node_id", ":", "An", "integer", ".", "The", "ID", "of", "the", "input", ...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L165-L185
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._add_node
def _add_node(self, node): """Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer. """ node_id = len(self.node_list) self.node_to_id[node] = node_id self.node_list.append(node) ...
python
def _add_node(self, node): """Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer. """ node_id = len(self.node_list) self.node_to_id[node] = node_id self.node_list.append(node) ...
[ "def", "_add_node", "(", "self", ",", "node", ")", ":", "node_id", "=", "len", "(", "self", ".", "node_list", ")", "self", ".", "node_to_id", "[", "node", "]", "=", "node_id", "self", ".", "node_list", ".", "append", "(", "node", ")", "self", ".", ...
Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer.
[ "Add", "a", "new", "node", "to", "node_list", "and", "give", "the", "node", "an", "ID", ".", "Args", ":", "node", ":", "An", "instance", "of", "Node", ".", "Returns", ":", "node_id", ":", "An", "integer", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L200-L212
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._add_edge
def _add_edge(self, layer, input_id, output_id): """Add a new layer to the graph. The nodes should be created in advance.""" if layer in self.layer_to_id: layer_id = self.layer_to_id[layer] if input_id not in self.layer_id_to_input_node_ids[layer_id]: self.layer_...
python
def _add_edge(self, layer, input_id, output_id): """Add a new layer to the graph. The nodes should be created in advance.""" if layer in self.layer_to_id: layer_id = self.layer_to_id[layer] if input_id not in self.layer_id_to_input_node_ids[layer_id]: self.layer_...
[ "def", "_add_edge", "(", "self", ",", "layer", ",", "input_id", ",", "output_id", ")", ":", "if", "layer", "in", "self", ".", "layer_to_id", ":", "layer_id", "=", "self", ".", "layer_to_id", "[", "layer", "]", "if", "input_id", "not", "in", "self", "."...
Add a new layer to the graph. The nodes should be created in advance.
[ "Add", "a", "new", "layer", "to", "the", "graph", ".", "The", "nodes", "should", "be", "created", "in", "advance", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L214-L231
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._redirect_edge
def _redirect_edge(self, u_id, v_id, new_v_id): """Redirect the layer to a new node. Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id` while keeping all other property of the edge the same. """ layer_id = None for index, edge_tuple in...
python
def _redirect_edge(self, u_id, v_id, new_v_id): """Redirect the layer to a new node. Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id` while keeping all other property of the edge the same. """ layer_id = None for index, edge_tuple in...
[ "def", "_redirect_edge", "(", "self", ",", "u_id", ",", "v_id", ",", "new_v_id", ")", ":", "layer_id", "=", "None", "for", "index", ",", "edge_tuple", "in", "enumerate", "(", "self", ".", "adj_list", "[", "u_id", "]", ")", ":", "if", "edge_tuple", "[",...
Redirect the layer to a new node. Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id` while keeping all other property of the edge the same.
[ "Redirect", "the", "layer", "to", "a", "new", "node", ".", "Change", "the", "edge", "originally", "from", "u_id", "to", "v_id", "into", "an", "edge", "from", "u_id", "to", "new_v_id", "while", "keeping", "all", "other", "property", "of", "the", "edge", "...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L233-L255
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._replace_layer
def _replace_layer(self, layer_id, new_layer): """Replace the layer with a new layer.""" old_layer = self.layer_list[layer_id] new_layer.input = old_layer.input new_layer.output = old_layer.output new_layer.output.shape = new_layer.output_shape self.layer_list[layer_id] =...
python
def _replace_layer(self, layer_id, new_layer): """Replace the layer with a new layer.""" old_layer = self.layer_list[layer_id] new_layer.input = old_layer.input new_layer.output = old_layer.output new_layer.output.shape = new_layer.output_shape self.layer_list[layer_id] =...
[ "def", "_replace_layer", "(", "self", ",", "layer_id", ",", "new_layer", ")", ":", "old_layer", "=", "self", ".", "layer_list", "[", "layer_id", "]", "new_layer", ".", "input", "=", "old_layer", ".", "input", "new_layer", ".", "output", "=", "old_layer", "...
Replace the layer with a new layer.
[ "Replace", "the", "layer", "with", "a", "new", "layer", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L257-L265
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph.topological_order
def topological_order(self): """Return the topological order of the node IDs from the input node to the output node.""" q = Queue() in_degree = {} for i in range(self.n_nodes): in_degree[i] = 0 for u in range(self.n_nodes): for v, _ in self.adj_list[u]: ...
python
def topological_order(self): """Return the topological order of the node IDs from the input node to the output node.""" q = Queue() in_degree = {} for i in range(self.n_nodes): in_degree[i] = 0 for u in range(self.n_nodes): for v, _ in self.adj_list[u]: ...
[ "def", "topological_order", "(", "self", ")", ":", "q", "=", "Queue", "(", ")", "in_degree", "=", "{", "}", "for", "i", "in", "range", "(", "self", ".", "n_nodes", ")", ":", "in_degree", "[", "i", "]", "=", "0", "for", "u", "in", "range", "(", ...
Return the topological order of the node IDs from the input node to the output node.
[ "Return", "the", "topological", "order", "of", "the", "node", "IDs", "from", "the", "input", "node", "to", "the", "output", "node", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L268-L289
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._get_pooling_layers
def _get_pooling_layers(self, start_node_id, end_node_id): """Given two node IDs, return all the pooling layers between them.""" layer_list = [] node_list = [start_node_id] assert self._depth_first_search(end_node_id, layer_list, node_list) ret = [] for layer_id in layer_...
python
def _get_pooling_layers(self, start_node_id, end_node_id): """Given two node IDs, return all the pooling layers between them.""" layer_list = [] node_list = [start_node_id] assert self._depth_first_search(end_node_id, layer_list, node_list) ret = [] for layer_id in layer_...
[ "def", "_get_pooling_layers", "(", "self", ",", "start_node_id", ",", "end_node_id", ")", ":", "layer_list", "=", "[", "]", "node_list", "=", "[", "start_node_id", "]", "assert", "self", ".", "_depth_first_search", "(", "end_node_id", ",", "layer_list", ",", "...
Given two node IDs, return all the pooling layers between them.
[ "Given", "two", "node", "IDs", "return", "all", "the", "pooling", "layers", "between", "them", "." ]
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L291-L303
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._depth_first_search
def _depth_first_search(self, target_id, layer_id_list, node_list): """Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.""" assert len(node_list) <= self.n_nodes ...
python
def _depth_first_search(self, target_id, layer_id_list, node_list): """Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.""" assert len(node_list) <= self.n_nodes ...
[ "def", "_depth_first_search", "(", "self", ",", "target_id", ",", "layer_id_list", ",", "node_list", ")", ":", "assert", "len", "(", "node_list", ")", "<=", "self", ".", "n_nodes", "u", "=", "node_list", "[", "-", "1", "]", "if", "u", "==", "target_id", ...
Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.
[ "Search", "for", "all", "the", "layers", "and", "nodes", "down", "the", "path", ".", "A", "recursive", "function", "to", "search", "all", "the", "layers", "and", "nodes", "between", "the", "node", "in", "the", "node_list", "and", "the", "node", "with", "...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L305-L322
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph._search
def _search(self, u, start_dim, total_dim, n_add): """Search the graph for all the layers to be widened caused by an operation. It is an recursive function with duplication check to avoid deadlock. It searches from a starting node u until the corresponding layers has been widened. Args: ...
python
def _search(self, u, start_dim, total_dim, n_add): """Search the graph for all the layers to be widened caused by an operation. It is an recursive function with duplication check to avoid deadlock. It searches from a starting node u until the corresponding layers has been widened. Args: ...
[ "def", "_search", "(", "self", ",", "u", ",", "start_dim", ",", "total_dim", ",", "n_add", ")", ":", "if", "(", "u", ",", "start_dim", ",", "total_dim", ",", "n_add", ")", "in", "self", ".", "vis", ":", "return", "self", ".", "vis", "[", "(", "u"...
Search the graph for all the layers to be widened caused by an operation. It is an recursive function with duplication check to avoid deadlock. It searches from a starting node u until the corresponding layers has been widened. Args: u: The starting node ID. start_dim: Th...
[ "Search", "the", "graph", "for", "all", "the", "layers", "to", "be", "widened", "caused", "by", "an", "operation", ".", "It", "is", "an", "recursive", "function", "with", "duplication", "check", "to", "avoid", "deadlock", ".", "It", "searches", "from", "a"...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L324-L387
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph.to_deeper_model
def to_deeper_model(self, target_id, new_layer): """Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses. """ self.operation_...
python
def to_deeper_model(self, target_id, new_layer): """Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses. """ self.operation_...
[ "def", "to_deeper_model", "(", "self", ",", "target_id", ",", "new_layer", ")", ":", "self", ".", "operation_history", ".", "append", "(", "(", "\"to_deeper_model\"", ",", "target_id", ",", "new_layer", ")", ")", "input_id", "=", "self", ".", "layer_id_to_inpu...
Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses.
[ "Insert", "a", "relu", "-", "conv", "-", "bn", "block", "after", "the", "target", "block", ".", "Args", ":", "target_id", ":", "A", "convolutional", "layer", "ID", ".", "The", "new", "block", "should", "be", "inserted", "after", "the", "block", ".", "n...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L402-L419
train
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/graph.py
Graph.to_wider_model
def to_wider_model(self, pre_layer_id, n_add): """Widen the last dimension of the output of the pre_layer. Args: pre_layer_id: The ID of a convolutional layer or dense layer. n_add: The number of dimensions to add. """ self.operation_history.append(("to_wider_mode...
python
def to_wider_model(self, pre_layer_id, n_add): """Widen the last dimension of the output of the pre_layer. Args: pre_layer_id: The ID of a convolutional layer or dense layer. n_add: The number of dimensions to add. """ self.operation_history.append(("to_wider_mode...
[ "def", "to_wider_model", "(", "self", ",", "pre_layer_id", ",", "n_add", ")", ":", "self", ".", "operation_history", ".", "append", "(", "(", "\"to_wider_model\"", ",", "pre_layer_id", ",", "n_add", ")", ")", "pre_layer", "=", "self", ".", "layer_list", "[",...
Widen the last dimension of the output of the pre_layer. Args: pre_layer_id: The ID of a convolutional layer or dense layer. n_add: The number of dimensions to add.
[ "Widen", "the", "last", "dimension", "of", "the", "output", "of", "the", "pre_layer", ".", "Args", ":", "pre_layer_id", ":", "The", "ID", "of", "a", "convolutional", "layer", "or", "dense", "layer", ".", "n_add", ":", "The", "number", "of", "dimensions", ...
c7cc8db32da8d2ec77a382a55089f4e17247ce41
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/graph.py#L421-L436
train