Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_best_model_id(self): if self.optimize_mode is OptimizeMode.Maximize: return max(self.history, key=lambda x: x["metric_value"])["model_id"] return min(self.history, key=lambda x: x["metric_value"])["model_id"]
[ " Get the best model_id from history using the metric value\n " ]
Please provide a description of the function:def load_model_by_id(self, model_id): with open(os.path.join(self.path, str(model_id) + ".json")) as fin: json_str = fin.read().replace("\n", "") load_model = json_to_graph(json_str) return load_model
[ "Get the model by model_id\n\n Parameters\n ----------\n model_id : int\n model index\n \n Returns\n -------\n load_model : Graph\n the model graph representation\n " ]
Please provide a description of the function:def _rand_init(x_bounds, x_types, selection_num_starting_points): ''' Random sample some init seed within bounds. ''' return [lib_data.rand(x_bounds, x_types) for i \ in range(0, selection_num_starting_points)]
[]
Please provide a description of the function:def get_median(temp_list): num = len(temp_list) temp_list.sort() print(temp_list) if num % 2 == 0: median = (temp_list[int(num/2)] + temp_list[int(num/2) - 1]) / 2 else: median = temp_list[int(num/2)] return median
[ "Return median\n " ]
Please provide a description of the function:def update_search_space(self, search_space): self.x_bounds = [[] for i in range(len(search_space))] self.x_types = [NONE_TYPE for i in range(len(search_space))] for key in search_space: self.key_order.append(key) key_typ...
[ "Update the self.x_bounds and self.x_types by the search_space.json\n\n Parameters\n ----------\n search_space : dict\n " ]
Please provide a description of the function:def _pack_output(self, init_parameter): output = {} for i, param in enumerate(init_parameter): output[self.key_order[i]] = param return output
[ "Pack the output\n\n Parameters\n ----------\n init_parameter : dict\n\n Returns\n -------\n output : dict\n " ]
Please provide a description of the function:def generate_parameters(self, parameter_id): if len(self.samples_x) < self.cold_start_num: init_parameter = _rand_init(self.x_bounds, self.x_types, 1)[0] results = self._pack_output(init_parameter) else: self.minim...
[ "Generate next parameter for trial\n If the number of trial result is lower than cold start number,\n metis will first random generate some parameters.\n Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model.\n\n Parameters\n ------...
Please provide a description of the function:def receive_trial_result(self, parameter_id, parameters, value): value = extract_scalar_reward(value) if self.optimize_mode == OptimizeMode.Maximize: value = -value logger.info("Received trial result.") logger.info("value...
[ "Tuner receive result from trial.\n\n Parameters\n ----------\n parameter_id : int\n parameters : dict\n value : dict/float\n if value is dict, it should have \"default\" key.\n " ]
Please provide a description of the function:def import_data(self, data): _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data))) _completed_num += 1 assert "parameter" in tria...
[ "Import additional data for tuning\n Parameters\n ----------\n data:\n a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'\n " ]
Please provide a description of the function:def create_model(samples_x, samples_y_aggregation, n_restarts_optimizer=250, is_white_kernel=False): ''' Trains GP regression model ''' kernel = gp.kernels.ConstantKernel(constant_value=1, constant_value...
[]
Please provide a description of the function:def json2paramater(self, ss_spec): ''' generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space ''' if isinstance(ss_spec, dict): if '_type' in ss_spec.keys(): ...
[]
Please provide a description of the function:def _parse_quniform(self, param_value): '''parse type of quniform parameter and return a list''' if param_value[2] < 2: raise RuntimeError("The number of values sampled (q) should be at least 2") low, high, count = param_value[0], param_va...
[]
Please provide a description of the function:def parse_qtype(self, param_type, param_value): '''parse type of quniform or qloguniform''' if param_type == 'quniform': return self._parse_quniform(param_value) if param_type == 'qloguniform': param_value[:2] = np.log(param_va...
[]
Please provide a description of the function:def expand_parameters(self, para): ''' Enumerate all possible combinations of all parameters para: {key1: [v11, v12, ...], key2: [v21, v22, ...], ...} return: {{key1: v11, key2: v21, ...}, {key1: v11, key2: v22, ...}, ...} ''' ...
[]
Please provide a description of the function:def import_data(self, data): _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data))) _completed_num += 1 assert "parameter" in tria...
[ "Import additional data for tuning\n\n Parameters\n ----------\n data:\n a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'\n " ]
Please provide a description of the function:def nni_log(log_type, log_message): '''Log message into stdout''' dt = datetime.now() print('[{0}] {1} {2}'.format(dt, log_type.value, log_message))
[]
Please provide a description of the function:def write(self, buf): ''' Write buffer data into logger/stdout ''' for line in buf.rstrip().splitlines(): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() try: self.logge...
[]
Please provide a description of the function:def run(self): for line in iter(self.pipeReader.readline, ''): self.orig_stdout.write(line.rstrip() + '\n') self.orig_stdout.flush() if self.log_collection == 'none': # If not match metrics, do not put the ...
[ "Run the thread, logging everything.\n If the log_collection is 'none', the log content will not be enqueued\n " ]
Please provide a description of the function:def extract_scalar_reward(value, scalar_key='default'): if isinstance(value, float) or isinstance(value, int): reward = value elif isinstance(value, dict) and scalar_key in value and isinstance(value[scalar_key], (float, int)): reward = value[sca...
[ "\n Extract scalar reward from trial result.\n\n Raises\n ------\n RuntimeError\n Incorrect final result: the final result should be float/int,\n or a dict which has a key named \"default\" whose value is float/int.\n " ]
Please provide a description of the function:def convert_dict2tuple(value): if isinstance(value, dict): for _keys in value: value[_keys] = convert_dict2tuple(value[_keys]) return tuple(sorted(value.items())) else: return value
[ "\n convert dict type to tuple to solve unhashable problem.\n " ]
Please provide a description of the function:def init_dispatcher_logger(): logger_file_path = 'dispatcher.log' if dispatcher_env_vars.NNI_LOG_DIRECTORY is not None: logger_file_path = os.path.join(dispatcher_env_vars.NNI_LOG_DIRECTORY, logger_file_path) init_logger(logger_file_path, dispatcher_...
[ " Initialize dispatcher logging configuration" ]
Please provide a description of the function:def sample_from_largest_budget(self, info_dict): best = np.inf best_vector = None budget = max(self.kde_models.keys()) l = self.kde_models[budget]['good'].pdf g = self.kde_models[budget]['bad'].pdf minimize_me = lam...
[ "We opted for a single multidimensional KDE compared to the\n hierarchy of one-dimensional KDEs used in TPE. The dimensional is\n seperated by budget. This function sample a configuration from\n largest budget. Firstly we sample \"num_samples\" configurations,\n then prefer one with the ...
Please provide a description of the function:def get_config(self, budget): logger.debug('start sampling a new configuration.') sample = None info_dict = {} # If no model is available, sample from prior # also mix in a fraction of random configs if len(self.kde_m...
[ "Function to sample a new configuration\n This function is called inside BOHB to query a new configuration\n\n Parameters:\n -----------\n budget: float\n the budget for which this configuration is scheduled\n\n Returns\n -------\n config\n retu...
Please provide a description of the function:def new_result(self, loss, budget, parameters, update_model=True): if loss is None: # One could skip crashed results, but we decided # assign a +inf loss and count them as bad configurations loss = np.inf if budge...
[ "\n Function to register finished runs. Every time a run has finished, this function should be called\n to register it with the loss.\n\n Parameters:\n -----------\n loss: float\n the loss of the parameters\n budget: float\n the budget of the parameter...
Please provide a description of the function:def is_valid(self, search_space): if not len(search_space) == 1: raise RuntimeError('BatchTuner only supprt one combined-paramreters key.') for param in search_space: param_type = search_space[param][TYPE] ...
[ "\n Check the search space is valid: only contains 'choice' type\n \n Parameters\n ----------\n search_space : dict\n " ]
Please provide a description of the function:def generate_parameters(self, parameter_id): self.count +=1 if self.count>len(self.values)-1: raise nni.NoMoreTrialError('no more parameters now.') return self.values[self.count]
[ "Returns a dict of trial (hyper-)parameters, as a serializable object.\n\n Parameters\n ----------\n parameter_id : int\n " ]
Please provide a description of the function:def normalize(inputs, epsilon=1e-8, scope="ln"): '''Applies layer normalization. Args: inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. epsilon: A floating number. A very small nu...
[]
Please provide a description of the function:def multihead_attention(queries, keys, scope="multihead_attention", num_units=None, num_heads=4, dropout_rate=0, is_training=True, ...
[]
Please provide a description of the function:def positional_encoding(inputs, num_units=None, zero_pad=True, scale=True, scope="positional_encoding", reuse=None): ''' Return positinal embedding...
[]
Please provide a description of the function:def feedforward(inputs, num_units, scope="multihead_attention"): '''Point-wise feed forward net. Args: inputs: A 3d tensor with shape of [N, T, C]. num_units: A list of two integers. scope: Optional scope for `variab...
[]
Please provide a description of the function:def generate(module_name, code): try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') visitor = SearchSpaceGenerator(module_name) try: visitor.visit(ast_tree) except AssertionError as exc: ...
[ "Generate search space.\n Return a serializable search space object.\n module_name: name of the module (str)\n code: user code (str)\n " ]
Please provide a description of the function:def rest_put(url, data, timeout, show_error=False): '''Call rest put method''' try: response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) r...
[]
Please provide a description of the function:def rest_post(url, data, timeout, show_error=False): '''Call rest post method''' try: response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\ data=data, timeout=timeout) ...
[]
Please provide a description of the function:def rest_get(url, timeout, show_error=False): '''Call rest get method''' try: response = requests.get(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return Non...
[]
Please provide a description of the function:def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) r...
[]
Please provide a description of the function:def check_rest_server(rest_port): '''Check if restful server is ready''' retry_count = 5 for _ in range(retry_count): response = rest_get(check_status_url(rest_port), REST_TIME_OUT) if response: if response.status_code == 200: ...
[]
Please provide a description of the function:def check_rest_server_quick(rest_port): '''Check if restful server is ready, only check once''' response = rest_get(check_status_url(rest_port), 5) if response and response.status_code == 200: return True, response return False, None
[]
Please provide a description of the function:def vap(x, a, b, c): return np.exp(a+b/x+c*np.log(x))
[ "Vapor pressure model\n \n Parameters\n ----------\n x: int\n a: float\n b: float\n c: float\n\n Returns\n -------\n float\n np.exp(a+b/x+c*np.log(x))\n " ]
Please provide a description of the function:def logx_linear(x, a, b): x = np.log(x) return a*x + b
[ "logx linear\n\n Parameters\n ----------\n x: int\n a: float\n b: float\n\n Returns\n -------\n float\n a * np.log(x) + b\n " ]
Please provide a description of the function:def dr_hill_zero_background(x, theta, eta, kappa): return (theta* x**eta) / (kappa**eta + x**eta)
[ "dr hill zero background\n \n Parameters\n ----------\n x: int\n theta: float\n eta: float\n kappa: float\n\n Returns\n -------\n float\n (theta* x**eta) / (kappa**eta + x**eta)\n " ]
Please provide a description of the function:def log_power(x, a, b, c): return a/(1.+(x/np.exp(b))**c)
[ "\"logistic power\n\n Parameters\n ----------\n x: int\n a: float\n b: float\n c: float\n\n Returns\n -------\n float\n a/(1.+(x/np.exp(b))**c)\n " ]
Please provide a description of the function:def pow4(x, alpha, a, b, c): return c - (a*x+b)**-alpha
[ "pow4\n\n Parameters\n ----------\n x: int\n alpha: float\n a: float\n b: float\n c: float\n\n Returns\n -------\n float\n c - (a*x+b)**-alpha\n " ]
Please provide a description of the function:def mmf(x, alpha, beta, kappa, delta): return alpha - (alpha - beta) / (1. + (kappa * x)**delta)
[ "Morgan-Mercer-Flodin\n http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm\n\n Parameters\n ----------\n x: int\n alpha: float\n beta: float\n kappa: float\n delta: float\n\n Returns\n -------\n float\n alpha - (alpha - beta) / (1. + (kappa * x)...
Please provide a description of the function:def weibull(x, alpha, beta, kappa, delta): return alpha - (alpha - beta) * np.exp(-(kappa * x)**delta)
[ "Weibull model\n http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm\n\n Parameters\n ----------\n x: int\n alpha: float\n beta: float\n kappa: float\n delta: float\n\n Returns\n -------\n float\n alpha - (alpha - beta) * np.exp(-(kappa * x)**del...
Please provide a description of the function:def janoschek(x, a, beta, k, delta): return a - (a - beta) * np.exp(-k*x**delta)
[ "http://www.pisces-conservation.com/growthhelp/janoschek.htm\n \n Parameters\n ----------\n x: int\n a: float\n beta: float\n k: float\n delta: float\n\n Returns\n -------\n float\n a - (a - beta) * np.exp(-k*x**delta)\n " ]
Please provide a description of the function:def parse_args(): '''Definite the arguments users need to follow and input''' parser = argparse.ArgumentParser(prog='nnictl', description='use nnictl command to control nni experiments') parser.add_argument('--version', '-v', action='store_true') parser.set_d...
[]
Please provide a description of the function:def get_log_path(config_file_name): '''generate stdout and stderr log path''' stdout_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stdout') stderr_full_path = os.path.join(NNICTL_HOME_DIR, config_file_name, 'stderr') return stdout_full_path, st...
[]
Please provide a description of the function:def print_log_content(config_file_name): '''print log information''' stdout_full_path, stderr_full_path = get_log_path(config_file_name) print_normal(' Stdout:') print(check_output_command(stdout_full_path)) print('\n\n') print_normal(' Stderr:') ...
[]
Please provide a description of the function:def start_rest_server(port, platform, mode, config_file_name, experiment_id=None, log_dir=None, log_level=None): '''Run nni manager process''' nni_config = Config(config_file_name) if detect_port(port): print_error('Port %s is used by another process, ple...
[]
Please provide a description of the function:def set_trial_config(experiment_config, port, config_file_name): '''set trial configuration''' request_data = dict() request_data['trial_config'] = experiment_config['trial'] response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_...
[]
Please provide a description of the function:def set_local_config(experiment_config, port, config_file_name): '''set local configuration''' #set machine_list request_data = dict() if experiment_config.get('localConfig'): request_data['local_config'] = experiment_config['localConfig'] if ...
[]
Please provide a description of the function:def set_remote_config(experiment_config, port, config_file_name): '''Call setClusterMetadata to pass trial''' #set machine_list request_data = dict() request_data['machine_list'] = experiment_config['machineList'] if request_data['machine_list']: ...
[]
Please provide a description of the function:def setNNIManagerIp(experiment_config, port, config_file_name): '''set nniManagerIp''' if experiment_config.get('nniManagerIp') is None: return True, None ip_config_dict = dict() ip_config_dict['nni_manager_ip'] = { 'nniManagerIp' : experiment_config[...
[]
Please provide a description of the function:def set_frameworkcontroller_config(experiment_config, port, config_file_name): '''set kubeflow configuration''' frameworkcontroller_config_data = dict() frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig'...
[]
Please provide a description of the function:def set_experiment(experiment_config, mode, port, config_file_name): '''Call startExperiment (rest POST /experiment) with yaml file content''' request_data = dict() request_data['authorName'] = experiment_config['authorName'] request_data['experimentName'] = ...
[]
Please provide a description of the function:def launch_experiment(args, experiment_config, mode, config_file_name, experiment_id=None): '''follow steps to start rest server and start experiment''' nni_config = Config(config_file_name) # check packages for tuner if experiment_config.get('tuner') and exp...
[]
Please provide a description of the function:def resume_experiment(args): '''resume an experiment''' experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() experiment_id = None experiment_endTime = None #find the latest stopped experiment if not args.id: ...
[]
Please provide a description of the function:def create_experiment(args): '''start a new experiment''' config_file_name = ''.join(random.sample(string.ascii_letters + string.digits, 8)) nni_config = Config(config_file_name) config_path = os.path.abspath(args.config) if not os.path.exists(config_path...
[]
Please provide a description of the function:def fit_theta(self): x = range(1, self.point_num + 1) y = self.trial_history for i in range(NUM_OF_FUNCTIONS): model = curve_combination_models[i] try: # The maximum number of iterations to fit is 100*(...
[ "use least squares to fit all default curves parameter seperately\n \n Returns\n -------\n None\n " ]
Please provide a description of the function:def filter_curve(self): avg = np.sum(self.trial_history) / self.point_num standard = avg * avg * self.point_num predict_data = [] tmp_model = [] for i in range(NUM_OF_FUNCTIONS): var = 0 model = curve_c...
[ "filter the poor performing curve\n \n Returns\n -------\n None\n " ]
Please provide a description of the function:def predict_y(self, model, pos): if model_para_num[model] == 2: y = all_models[model](pos, model_para[model][0], model_para[model][1]) elif model_para_num[model] == 3: y = all_models[model](pos, model_para[model][0], model_par...
[ "return the predict y of 'model' when epoch = pos\n \n Parameters\n ----------\n model: string\n name of the curve function model\n pos: int\n the epoch number of the position you want to predict\n\n Returns\n -------\n int:\n ...
Please provide a description of the function:def f_comb(self, pos, sample): ret = 0 for i in range(self.effective_model_num): model = self.effective_model[i] y = self.predict_y(model, pos) ret += sample[i] * y return ret
[ "return the value of the f_comb when epoch = pos\n\n Parameters\n ----------\n pos: int\n the epoch number of the position you want to predict\n sample: list\n sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}\n\n Returns\n ------...
Please provide a description of the function:def normalize_weight(self, samples): for i in range(NUM_OF_INSTANCE): total = 0 for j in range(self.effective_model_num): total += samples[i][j] for j in range(self.effective_model_num): sam...
[ "normalize weight\n \n Parameters\n ----------\n samples: list\n a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,\n representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}\n\n Returns\n -------\n ...
Please provide a description of the function:def sigma_sq(self, sample): ret = 0 for i in range(1, self.point_num + 1): temp = self.trial_history[i - 1] - self.f_comb(i, sample) ret += temp * temp return 1.0 * ret / self.point_num
[ "returns the value of sigma square, given the weight's sample\n \n Parameters\n ----------\n sample: list\n sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}\n\n Returns\n -------\n float\n the value of sigma square, given ...
Please provide a description of the function:def normal_distribution(self, pos, sample): curr_sigma_sq = self.sigma_sq(sample) delta = self.trial_history[pos - 1] - self.f_comb(pos, sample) return np.exp(np.square(delta) / (-2.0 * curr_sigma_sq)) / np.sqrt(2 * np.pi * np.sqrt(curr_sigma...
[ "returns the value of normal distribution, given the weight's sample and target position\n \n Parameters\n ----------\n pos: int\n the epoch number of the position you want to predict\n sample: list\n sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1...
Please provide a description of the function:def likelihood(self, samples): ret = np.ones(NUM_OF_INSTANCE) for i in range(NUM_OF_INSTANCE): for j in range(1, self.point_num + 1): ret[i] *= self.normal_distribution(j, samples[i]) return ret
[ "likelihood\n\n Parameters\n ----------\n sample: list\n sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}\n \n Returns\n -------\n float\n likelihood\n " ]
Please provide a description of the function:def prior(self, samples): ret = np.ones(NUM_OF_INSTANCE) for i in range(NUM_OF_INSTANCE): for j in range(self.effective_model_num): if not samples[i][j] > 0: ret[i] = 0 if self.f_comb(1, sam...
[ "priori distribution\n \n Parameters\n ----------\n samples: list\n a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,\n representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}\n \n Returns\n -------\n ...
Please provide a description of the function:def target_distribution(self, samples): curr_likelihood = self.likelihood(samples) curr_prior = self.prior(samples) ret = np.ones(NUM_OF_INSTANCE) for i in range(NUM_OF_INSTANCE): ret[i] = curr_likelihood[i] * curr_prior[i...
[ "posterior probability\n \n Parameters\n ----------\n samples: list\n a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,\n representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}\n \n Returns\n --...
Please provide a description of the function:def mcmc_sampling(self): init_weight = np.ones((self.effective_model_num), dtype=np.float) / self.effective_model_num self.weight_samples = np.broadcast_to(init_weight, (NUM_OF_INSTANCE, self.effective_model_num)) for i in range(NUM_OF_SIMULA...
[ "Adjust the weight of each function using mcmc sampling.\n The initial value of each weight is evenly distribute.\n Brief introduction:\n (1)Definition of sample:\n Sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}\n (2)Definition of samples:\n ...
Please provide a description of the function:def predict(self, trial_history): self.trial_history = trial_history self.point_num = len(trial_history) self.fit_theta() self.filter_curve() if self.effective_model_num < LEAST_FITTED_FUNCTION: # different curve's...
[ "predict the value of target position\n \n Parameters\n ----------\n trial_history: list\n The history performance matrix of each trial.\n\n Returns\n -------\n float\n expected final result performance of this hyperparameter config\n " ]
Please provide a description of the function:def _outlierDetection_threaded(inputs): ''' Detect the outlier ''' [samples_idx, samples_x, samples_y_aggregation] = inputs sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\ % (os.path.basename(__file__), samples_idx ...
[]
Please provide a description of the function:def outlierDetection_threaded(samples_x, samples_y_aggregation): ''' Use Multi-thread to detect the outlier ''' outliers = [] threads_inputs = [[samples_idx, samples_x, samples_y_aggregation]\ for samples_idx in range(0, len(s...
[]
Please provide a description of the function:def deeper_conv_block(conv_layer, kernel_size, weighted=True): '''deeper conv layer. ''' n_dim = get_n_dim(conv_layer) filter_shape = (kernel_size,) * 2 n_filters = conv_layer.filters weight = np.zeros((n_filters, n_filters) + filter_shape) center...
[]
Please provide a description of the function:def dense_to_deeper_block(dense_layer, weighted=True): '''deeper dense layer. ''' units = dense_layer.units weight = np.eye(units) bias = np.zeros(units) new_dense_layer = StubDense(units, units) if weighted: new_dense_layer.set_weights( ...
[]
Please provide a description of the function:def wider_pre_dense(layer, n_add, weighted=True): '''wider previous dense layer. ''' if not weighted: return StubDense(layer.input_units, layer.units + n_add) n_units2 = layer.units teacher_w, teacher_b = layer.get_weights() rand = np.random...
[]
Please provide a description of the function:def wider_pre_conv(layer, n_add_filters, weighted=True): '''wider previous conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)( layer.input_channel, layer.filters + n_add_filters, ...
[]
Please provide a description of the function:def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True): '''wider next conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)(layer.input_channel + n_add, layer.filter...
[]
Please provide a description of the function:def wider_bn(layer, start_dim, total_dim, n_add, weighted=True): '''wider batch norm layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_batch_norm_class(n_dim)(layer.num_features + n_add) weights = layer.get_weights() new_weight...
[]
Please provide a description of the function:def wider_next_dense(layer, start_dim, total_dim, n_add, weighted=True): '''wider next dense layer. ''' if not weighted: return StubDense(layer.input_units + n_add, layer.units) teacher_w, teacher_b = layer.get_weights() student_w = teacher_w.copy...
[]
Please provide a description of the function:def add_noise(weights, other_weights): '''add noise to the layer. ''' w_range = np.ptp(other_weights.flatten()) noise_range = NOISE_RATIO * w_range noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape) return np.add(noise, we...
[]
Please provide a description of the function:def init_dense_weight(layer): '''initilize dense layer weight. ''' units = layer.units weight = np.eye(units) bias = np.zeros(units) layer.set_weights( (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
[]
Please provide a description of the function:def init_conv_weight(layer): '''initilize conv layer weight. ''' n_filters = layer.filters filter_shape = (layer.kernel_size,) * get_n_dim(layer) weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), ...
[]
Please provide a description of the function:def init_bn_weight(layer): '''initilize batch norm layer weight. ''' n_filters = layer.num_features new_weights = [ add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0...
[]
Please provide a description of the function:def parse_log_path(args, trial_content): '''parse log path''' path_list = [] host_list = [] for trial in trial_content: if args.trial_id and args.trial_id != 'all' and trial.get('id') != args.trial_id: continue pattern = r'(?P<head...
[]
Please provide a description of the function:def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path): '''use ssh client to copy data from remote machine to local machien''' machine_list = nni_config.get_config('experimentConfig').get('machineList') machine_dict = {} ...
[]
Please provide a description of the function:def get_path_list(args, nni_config, trial_content, temp_nni_path): '''get path list according to different platform''' path_list, host_list = parse_log_path(args, trial_content) platform = nni_config.get_config('experimentConfig').get('trainingServicePlatform') ...
[]
Please provide a description of the function:def start_tensorboard_process(args, nni_config, path_list, temp_nni_path): '''call cmds to start tensorboard process in local machine''' if detect_port(args.port): print_error('Port %s is used by another process, please reset port!' % str(args.port)) ...
[]
Please provide a description of the function:def stop_tensorboard(args): '''stop tensorboard''' experiment_id = check_experiment_id(args) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() config_file_name = experiment_dict[experiment_id]['fileName'] nni_...
[]
Please provide a description of the function:def start_tensorboard(args): '''start tensorboard''' experiment_id = check_experiment_id(args) experiment_config = Experiments() experiment_dict = experiment_config.get_all_experiments() config_file_name = experiment_dict[experiment_id]['fileName'] nn...
[]
Please provide a description of the function:def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad): ''' The ratio is smaller the better ''' ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value]) sigma = 0 re...
[]
Please provide a description of the function:def selection_r(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, num_starting_points=100, minimize_constraints_fun=None): ''' Call selection ''' minimize_star...
[]
Please provide a description of the function:def selection(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points, minimize_constraints_fun=None): ''' Select the lowest mu value ''' results = li...
[]
Please provide a description of the function:def _minimize_constraints_fun_summation(x): ''' Minimize constraints fun summation ''' summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX]) return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND
[]
Please provide a description of the function:def load_data(): '''Load dataset, use 20newsgroups dataset''' digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, random_state=99, test_size=0.25) ss = StandardScaler() X_train = ss.fit_transform(X_train...
[]
Please provide a description of the function:def get_model(PARAMS): '''Get model according to parameters''' model = SVC() model.C = PARAMS.get('C') model.keral = PARAMS.get('keral') model.degree = PARAMS.get('degree') model.gamma = PARAMS.get('gamma') model.coef0 = PARAMS.get('coef0') ...
[]
Please provide a description of the function:def get_hyperparameter_configurations(self, num, r, config_generator): global _KEY assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.s, self.i) ...
[ "generate num hyperparameter configurations from search space using Bayesian optimization\n\n Parameters\n ----------\n num: int\n the number of hyperparameter configurations\n\n Returns\n -------\n list\n a list of hyperparameter configurations. Forma...
Please provide a description of the function:def handle_initialize(self, data): logger.info('start to handle_initialize') # convert search space jason to ConfigSpace self.handle_update_search_space(data) # generate BOHB config_generator using Bayesian optimization if se...
[ "Initialize Tuner, including creating Bayesian optimization-based parametric models \n and search space formations\n\n Parameters\n ----------\n data: search space\n search space of this experiment\n\n Raises\n ------\n ValueError\n Error: Searc...
Please provide a description of the function:def generate_new_bracket(self): logger.debug( 'start to create a new SuccessiveHalving iteration, self.curr_s=%d', self.curr_s) if self.curr_s < 0: logger.info("s < 0, Finish this round of Hyperband in BOHB. Generate new round...
[ "generate a new bracket" ]
Please provide a description of the function:def handle_request_trial_jobs(self, data): # Receive new request self.credit += data for _ in range(self.credit): self._request_one_trial_job()
[ "recerive the number of request and generate trials\n\n Parameters\n ----------\n data: int\n number of trial jobs that nni manager ask to generate\n " ]
Please provide a description of the function:def _request_one_trial_job(self): if not self.generated_hyper_configs: ret = { 'parameter_id': '-1_0_0', 'parameter_source': 'algorithm', 'parameters': '' } send(CommandType....
[ "get one trial job, i.e., one hyperparameter configuration.\n\n If this function is called, Command will be sent by BOHB:\n a. If there is a parameter need to run, will return \"NewTrialJob\" with a dict:\n { \n 'parameter_id': id of new hyperparameter\n 'parameter_source'...