INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Delete index infromation from params
def _split_index(params): """ Delete index infromation from params """ if isinstance(params, list): return [params[0], _split_index(params[1])] elif isinstance(params, dict): if INDEX in params.keys(): return _split_index(params[VALUE]) result = dict() for...
Parameters ---------- algorithm_name: str algorithm_name includes tpe random_search and anneal
def _choose_tuner(self, algorithm_name): """ Parameters ---------- algorithm_name : str algorithm_name includes "tpe", "random_search" and anneal" """ if algorithm_name == 'tpe': return hp.tpe.suggest if algorithm_name == 'random_search': ...
Update search space definition in tuner by search_space in parameters.
def update_search_space(self, search_space): """ Update search space definition in tuner by search_space in parameters. Will called when first setup experiemnt or update search space in WebUI. Parameters ---------- search_space : dict """ self.json = sea...
Returns a set of trial ( hyper - ) parameters as a serializable object.
def generate_parameters(self, parameter_id): """ Returns a set of trial (hyper-)parameters, as a serializable object. Parameters ---------- parameter_id : int Returns ------- params : dict """ total_params = self.get_suggestion(random_sea...
Record an observation of the objective function
def receive_trial_result(self, parameter_id, parameters, value): """ Record an observation of the objective function Parameters ---------- parameter_id : int parameters : dict value : dict/float if value is dict, it should have "default" key. ...
Unpack the idxs - vals format into the list of dictionaries that is misc.
def miscs_update_idxs_vals(self, miscs, idxs, vals, assert_all_vals_used=True, idxs_map=None): """ Unpack the idxs-vals format into the list of dictionaries that is `misc`. Parameters ---------- idxs_map : dic...
get suggestion from hyperopt
def get_suggestion(self, random_search=False): """get suggestion from hyperopt Parameters ---------- random_search : bool flag to indicate random search or not (default: {False}) Returns ---------- total_params : dict parameter suggestion...
Import additional data for tuning
def import_data(self, data): """Import additional data for tuning Parameters ---------- data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' """ _completed_num = 0 for trial_info in data: logger.info("I...
Lowest Mu acquisition function
def next_hyperparameter_lowest_mu(fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_starting_points, minimize_constraints_fun=None): ''' "Lowest Mu" acquisition ...
Calculate the lowest mu
def _lowest_mu(x, fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_constraints_fun): ''' Calculate the lowest mu ''' # This is only for step-wise optimization x = lib_data.match_val_type(x, x_bounds, x_types) mu = sys.maxsize if (minimize_constraints_fun is No...
Build char embedding network for the QA model.
def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): """Build char embedding network for the QA model.""" max_char_length = self.cfg.max_char_length inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids), self.cfg.dropout, is_train...
data: a dict received from nni_manager which contains: - parameter_id: id of the trial - value: metric value reported by nni. report_final_result () - type: report type support { FINAL PERIODICAL }
def handle_report_metric_data(self, data): """ data: a dict received from nni_manager, which contains: - 'parameter_id': id of the trial - 'value': metric value reported by nni.report_final_result() - 'type': report type, support {'FINAL', 'PERIODICAL'} ...
data: it has three keys: trial_job_id event hyper_params - trial_job_id: the id generated by training service - event: the job s state - hyper_params: the hyperparameters generated and returned by tuner
def handle_trial_end(self, data): """ data: it has three keys: trial_job_id, event, hyper_params - trial_job_id: the id generated by training service - event: the job's state - hyper_params: the hyperparameters generated and returned by tuner """ tr...
Call tuner to process final results
def _handle_final_metric_data(self, data): """Call tuner to process final results """ id_ = data['parameter_id'] value = data['value'] if id_ in _customized_parameter_ids: self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value) else: ...
Call assessor to process intermediate results
def _handle_intermediate_metric_data(self, data): """Call assessor to process intermediate results """ if data['type'] != 'PERIODICAL': return if self.assessor is None: return trial_job_id = data['trial_job_id'] if trial_job_id in _ended_trials: ...
Send last intermediate result as final result to tuner in case the trial is early stopped.
def _earlystop_notify_tuner(self, data): """Send last intermediate result as final result to tuner in case the trial is early stopped. """ _logger.debug('Early stop notify tuner data: [%s]', data) data['type'] = 'FINAL' if multi_thread_enabled(): self._handle_...
parse reveive msgs to global variable
def parse_rev_args(receive_msg): """ parse reveive msgs to global variable """ global trainloader global testloader global net # Loading Data logger.debug("Preparing data..") (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() y_train = to_categorical(y_train, 10) ...
train and eval the model
def train_eval(): """ train and eval the model """ global trainloader global testloader global net (x_train, y_train) = trainloader (x_test, y_test) = testloader # train procedure net.fit( x=x_train, y=y_train, batch_size=args.batch_size, validation...
Run on end of each epoch
def on_epoch_end(self, epoch, logs=None): """ Run on end of each epoch """ if logs is None: logs = dict() logger.debug(logs) nni.report_intermediate_result(logs["val_acc"])
Create a full id for a specific bracket s hyperparameter configuration Parameters ---------- brackets_id: int brackets id brackets_curr_decay: brackets curr decay increased_id: int increased id
def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1): """Create a full id for a specific bracket's hyperparameter configuration Parameters ---------- brackets_id: int brackets id brackets_curr_decay: brackets curr decay increased_id: int ...
Randomly generate values for hyperparameters from hyperparameter space i. e. x. Parameters ---------- ss_spec: hyperparameter space random_state: random operator to generate random values
def json2paramater(ss_spec, random_state): """Randomly generate values for hyperparameters from hyperparameter space i.e., x. Parameters ---------- ss_spec: hyperparameter space random_state: random operator to generate random values Returns ------- Parameter: ...
return the values of n and r for the next round
def get_n_r(self): """return the values of n and r for the next round""" return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon)
i means the ith round. Increase i by 1
def increase_i(self): """i means the ith round. Increase i by 1""" self.i += 1 if self.i > self.bracket_id: self.no_more_trial = True
update trial s latest result with its sequence number e. g. epoch number or batch number Parameters ---------- i: int the ith round parameter_id: int the id of the trial/ parameter seq: int sequence number e. g. epoch number or batch number value: int latest result with sequence number seq
def set_config_perf(self, i, parameter_id, seq, value): """update trial's latest result with its sequence number, e.g., epoch number or batch number Parameters ---------- i: int the ith round parameter_id: int the id of the trial/parameter ...
If the trial is finished and the corresponding round ( i. e. i ) has all its trials finished it will choose the top k trials for the next round ( i. e. i + 1 )
def inform_trial_end(self, i): """If the trial is finished and the corresponding round (i.e., i) has all its trials finished, it will choose the top k trials for the next round (i.e., i+1) Parameters ---------- i: int the ith round """ global _KEY # p...
Randomly generate num hyperparameter configurations from search space
def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name """Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations ...
after generating one round of hyperconfigs this function records the generated hyperconfigs creates a dict to record the performance when those hyperconifgs are running set the number of finished configs in this round to be 0 and increase the round number.
def _record_hyper_configs(self, hyper_configs): """after generating one round of hyperconfigs, this function records the generated hyperconfigs, creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs in this round to be 0, and increase th...
get one trial job i. e. one hyperparameter configuration.
def _request_one_trial_job(self): """get one trial job, i.e., one hyperparameter configuration.""" if not self.generated_hyper_configs: if self.curr_s < 0: self.curr_s = self.s_max _logger.debug('create a new bracket, self.curr_s=%d', self.curr_s) self...
data: JSON object which is search space Parameters ---------- data: int number of trial jobs
def handle_update_search_space(self, data): """data: JSON object, which is search space Parameters ---------- data: int number of trial jobs """ self.searchspace_json = data self.random_state = np.random.RandomState()
Parameters ---------- data: dict () it has three keys: trial_job_id event hyper_params trial_job_id: the id generated by training service event: the job s state hyper_params: the hyperparameters ( a string ) generated and returned by tuner
def handle_trial_end(self, data): """ Parameters ---------- data: dict() it has three keys: trial_job_id, event, hyper_params trial_job_id: the id generated by training service event: the job's state hyper_params: the hyperparameters (a str...
Parameters ---------- data: it is an object which has keys parameter_id value trial_job_id type sequence. Raises ------ ValueError Data type not supported
def handle_report_metric_data(self, data): """ Parameters ---------- data: it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'. Raises ------ ValueError Data type not supported """ ...
Returns a set of trial graph config as a serializable object. parameter_id: int
def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. parameter_id : int """ if len(self.population) <= 0: logger.debug("the len of poplution lower than zero.") raise Exception('The population is empty') ...
Record an observation of the objective function parameter_id: int parameters: dict of parameters value: final metrics of the trial including reward
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 ''' reward = extract_scalar_reward(value) ...
Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents the neural architecture graph of the generated model.
def generate(self, model_len=None, model_width=None): """Generates a CNN. Args: model_len: An integer. Number of convolutional layers. model_width: An integer. Number of filters for the convolutional layers. Returns: An instance of the class Graph. Represents ...
Generates a Multi - Layer Perceptron. Args: model_len: An integer. Number of hidden layers. model_width: An integer or a list of integers of length model_len. If it is a list it represents the number of nodes in each hidden layer. If it is an integer all hidden layers have nodes equal to this value. Returns: An instanc...
def generate(self, model_len=None, model_width=None): """Generates a Multi-Layer Perceptron. Args: model_len: An integer. Number of hidden layers. model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the number of nod...
Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files ( str )
def generate_search_space(code_dir): """Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files (str) """ search_space = {} if code_dir.endswith(slash): code_dir = code_dir[:-1] for subdir, _, files in o...
Expand annotations in user code. Return dst_dir if annotation detected ; return src_dir if not. src_dir: directory path of user code ( str ) dst_dir: directory to place generated files ( str )
def expand_annotations(src_dir, dst_dir): """Expand annotations in user code. Return dst_dir if annotation detected; return src_dir if not. src_dir: directory path of user code (str) dst_dir: directory to place generated files (str) """ if src_dir[-1] == slash: src_dir = src_dir[:-1] ...
Generate send stdout url
def gen_send_stdout_url(ip, port): '''Generate send stdout url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
Generate send error url
def gen_send_version_url(ip, port): '''Generate send error url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
validate if a digit is valid
def validate_digit(value, start, end): '''validate if a digit is valid''' if not str(value).isdigit() or int(value) < start or int(value) > end: raise ValueError('%s must be a digit from %s to %s' % (value, start, end))
validate if the dispatcher of the experiment supports importing data
def validate_dispatcher(args): '''validate if the dispatcher of the experiment supports importing data''' nni_config = Config(get_config_filename(args)).get_config('experimentConfig') if nni_config.get('tuner') and nni_config['tuner'].get('builtinTunerName'): dispatcher_name = nni_config['tuner']['b...
load search space content
def load_search_space(path): '''load search space content''' content = json.dumps(get_json_content(path)) if not content: raise ValueError('searchSpace file should not be empty') return content
call restful server to update experiment profile
def update_experiment_profile(args, key, value): '''call restful server to update experiment profile''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if running: response = rest_get(experimen...
import additional data to the experiment
def import_data(args): '''import additional data to the experiment''' validate_file(args.filename) validate_dispatcher(args) content = load_search_space(args.filename) args.port = get_experiment_port(args) if args.port is not None: if import_data_to_restful_server(args, content): ...
call restful server to import data to the experiment
def import_data_to_restful_server(args, content): '''call restful server to import data to the experiment''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if running: response = rest_post(imp...
check key type
def setType(key, type): '''check key type''' return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__))
check choice
def setChoice(key, *args): '''check choice''' return And(lambda n: n in args, error=SCHEMA_RANGE_ERROR % (key, str(args)))
check number range
def setNumberRange(key, keyType, start, end): '''check number range''' return And( And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)), And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))), )
keras dropout layer.
def keras_dropout(layer, rate): '''keras dropout layer. ''' from keras import layers input_dim = len(layer.input.shape) if input_dim == 2: return layers.SpatialDropout1D(rate) elif input_dim == 3: return layers.SpatialDropout2D(rate) elif input_dim == 4: return laye...
real keras layer.
def to_real_keras_layer(layer): ''' real keras layer. ''' from keras import layers if is_layer(layer, "Dense"): return layers.Dense(layer.units, input_shape=(layer.input_units,)) if is_layer(layer, "Conv"): return layers.Conv2D( layer.filters, layer.kernel_si...
judge the layer type. Returns: boolean -- True or False
def is_layer(layer, layer_type): '''judge the layer type. Returns: boolean -- True or False ''' if layer_type == "Input": return isinstance(layer, StubInput) elif layer_type == "Conv": return isinstance(layer, StubConv) elif layer_type == "Dense": return isinstan...
get layer description.
def layer_description_extractor(layer, node_to_id): '''get layer description. ''' layer_input = layer.input layer_output = layer.output if layer_input is not None: if isinstance(layer_input, Iterable): layer_input = list(map(lambda x: node_to_id[x], layer_input)) else: ...
build layer from description.
def layer_description_builder(layer_information, id_to_node): '''build layer from description. ''' # pylint: disable=W0123 layer_type = layer_information[0] layer_input_ids = layer_information[1] if isinstance(layer_input_ids, Iterable): layer_input = list(map(lambda x: id_to_node[x], l...
get layer width.
def layer_width(layer): '''get layer width. ''' if is_layer(layer, "Dense"): return layer.units if is_layer(layer, "Conv"): return layer.filters raise TypeError("The layer should be either Dense or Conv layer.")
Define parameters.
def define_params(self): ''' Define parameters. ''' input_dim = self.input_dim hidden_dim = self.hidden_dim prefix = self.name self.w_matrix = tf.Variable(tf.random_normal([input_dim, 3 * hidden_dim], stddev=0.1), name='/'.join(...
Build the GRU cell.
def build(self, x, h, mask=None): ''' Build the GRU cell. ''' xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1) hu = tf.split(tf.matmul(h, self.U), 3, 1) r = tf.sigmoid(xw[0] + hu[0]) z = tf.sigmoid(xw[1] + hu[1]) h1 = tf.tanh(xw[2] + r * hu[2])...
Build GRU sequence.
def build_sequence(self, xs, masks, init, is_left_to_right): ''' Build GRU sequence. ''' states = [] last = init if is_left_to_right: for i, xs_i in enumerate(xs): h = self.build(xs_i, last, masks[i]) states.append(h) ...
conv2d returns a 2d convolution layer with full stride.
def conv2d(x_input, w_matrix): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
max_pool downsamples a feature map by 2X.
def max_pool(x_input, pool_size): """max_pool downsamples a feature map by 2X.""" return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1], strides=[1, pool_size, pool_size, 1], padding='SAME')
Main function build mnist network run and send result to NNI.
def main(params): ''' Main function, build mnist network, run and send result to NNI. ''' # Import data mnist = download_mnist_retry(params['data_dir']) print('Mnist download data done.') logger.debug('Mnist download data done.') # Create the model # Build the graph for the deep net...
Build the whole neural network for the QA model.
def build_net(self, is_training): """Build the whole neural network for the QA model.""" cfg = self.cfg with tf.device('/cpu:0'): word_embed = tf.get_variable( name='word_embed', initializer=self.embed, dtype=tf.float32, trainable=False) char_embed = tf.ge...
call check_output command to read content from a file
def check_output_command(file_path, head=None, tail=None): '''call check_output command to read content from a file''' if os.path.exists(file_path): if sys.platform == 'win32': cmds = ['powershell.exe', 'type', file_path] if head: cmds += ['|', 'select', '-first',...
kill command
def kill_command(pid): '''kill command''' if sys.platform == 'win32': process = psutil.Process(pid=pid) process.send_signal(signal.CTRL_BREAK_EVENT) else: cmds = ['kill', str(pid)] call(cmds)
install python package from pip
def install_package_command(package_name): '''install python package from pip''' #TODO refactor python logic if sys.platform == "win32": cmds = 'python -m pip install --user {0}'.format(package_name) else: cmds = 'python3 -m pip install --user {0}'.format(package_name) call(cmds, she...
install requirements. txt
def install_requirements_command(requirements_path): '''install requirements.txt''' cmds = 'cd ' + requirements_path + ' && {0} -m pip install --user -r requirements.txt' #TODO refactor python logic if sys.platform == "win32": cmds = cmds.format('python') else: cmds = cmds.format('py...
Get parameters from command line
def get_params(): ''' Get parameters from command line ''' parser = argparse.ArgumentParser() parser.add_argument("--data_dir", type=str, default='/tmp/tensorflow/mnist/input_data', help="data directory") parser.add_argument("--dropout_rate", type=float, default=0.5, help="dropout rate") parser.add_...
Building network for mnist
def build_network(self): ''' Building network for mnist ''' # Reshape to use within a convolutional neural net. # Last dimension is for "features" - there is only one here, since images are # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. with tf.n...
get the startTime and endTime of an experiment
def get_experiment_time(port): '''get the startTime and endTime of an experiment''' response = rest_get(experiment_url(port), REST_TIME_OUT) if response and check_response(response): content = convert_time_stamp_to_date(json.loads(response.text)) return content.get('startTime'), content.get(...
get the status of an experiment
def get_experiment_status(port): '''get the status of an experiment''' result, response = check_rest_server_quick(port) if result: return json.loads(response.text).get('status') return None
Update the experiment status in config file
def update_experiment(): '''Update the experiment status in config file''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: return None for key in experiment_dict.keys(): if isinstance(experiment_dict[key], dict): ...
check if the id is valid
def check_experiment_id(args): '''check if the id is valid ''' update_experiment() experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() if not experiment_dict: print_normal('There is no experiment running...') return None if not args.id:...
Parse the arguments for nnictl stop 1. If there is an id specified return the corresponding id 2. If there is no id specified and there is an experiment running return the id or return Error 3. If the id matches an experiment nnictl will return the id. 4. If the id ends with * nnictl will match all ids matchs the regul...
def parse_ids(args): '''Parse the arguments for nnictl stop 1.If there is an id specified, return the corresponding id 2.If there is no id specified, and there is an experiment running, return the id, or return Error 3.If the id matches an experiment, nnictl will return the id. 4.If the id ends with...
get the file name of config file
def get_config_filename(args): '''get the file name of config file''' experiment_id = check_experiment_id(args) if experiment_id is None: print_error('Please set the experiment id!') exit(1) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() ...
Convert time stamp to date time format
def convert_time_stamp_to_date(content): '''Convert time stamp to date time format''' start_time_stamp = content.get('startTime') end_time_stamp = content.get('endTime') if start_time_stamp: start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S") ...
check if restful server is running
def check_rest(args): '''check if restful server is running''' nni_config = Config(get_config_filename(args)) rest_port = nni_config.get_config('restServerPort') running, _ = check_rest_server_quick(rest_port) if not running: print_normal('Restful server is running...') else: pri...
Stop the experiment which is running
def stop_experiment(args): '''Stop the experiment which is running''' experiment_id_list = parse_ids(args) if experiment_id_list: experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() for experiment_id in experiment_id_list: print_nor...
List trial
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...
List trial
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,...
Get experiment information
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...') ...
Show the status of experiment
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: ...
internal function to call get_log_content
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') ...
get trial log path
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...
show the url of web ui
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'))))
get the information of all experiments
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 = ...
get the interval of two times
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)...
show experiment information in monitor
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 =...
monitor the 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(...
output: List [ Dict ]
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'] ...
export experiment metadata to csv
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...
copy remote directory to local machine
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...
create ssh 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) ...
Change search space from json format to hyperopt format
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 == '...
Json to pramaters.
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 + '-' +...
Delete index information from params
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...
Parameters ---------- config: str info: str save_dir: str
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 ...
Update search space. Search_space contains the information that user pre - defined.
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_...
Returns a dict of trial ( hyper - ) parameters as a serializable object.
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...
Record the result from a trial
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. ''' ...
Load json file content Parameters ---------- file_path: path to the file Raises ------ TypeError Error with the file path
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...
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 ] # parameter_name ...
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_...