text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_embedding(path): ''' return embedding for a specific file by given file path. ''' EMBEDDING_DIM = 300 embedding_dict = {} with open(path, 'r', encoding='utf-8') as file: pairs = [line.strip('\r\n').split() for line in file.readlines()] for pair in pairs: if l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_predict_json(position1_result, position2_result, ids, passage_tokens): ''' Generate json by prediction. ''' predict_len = len(position1_result) logger.debug('total prediction num is %s', str(predict_len)) answers = {} for i in range(predict_len): sample_id = ids[i] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def f1_score(prediction, ground_truth): ''' Calculate the f1 score. ''' prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = Counter(prediction_tokens) & Counter(ground_truth_tokens) num_same = sum(common.values()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _evaluate(dataset, predictions): ''' Evaluate function. ''' f1_result = exact_match = total = 0 count = 0 for article in dataset: for paragraph in article['paragraphs']: for qa_pair in paragraph['qas']: total += 1 if qa_pair['id'] not in pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json2space(in_x, name=ROOT): """ Change json to search space in hyperopt. Parameters in_x : dict/list/str/int/float The part of json. name : str name could b...
out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type _value = json2space(in_x[VALUE], name=name) if _type == 'choice': out_y = eval('hp.hp.'+_type)(name, _value) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json2parameter(in_x, parameter, name=ROOT): """ Change json to parameters. """
out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type if _type == 'choice': _index = parameter[name] out_y = { INDEX: _index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 key in params: result[key] = _split_index(params[key]) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_search_space(self, search_space): """ Update search space definition in tuner by search_space in parameters. Will called when first setup experiemnt o...
self.json = search_space search_space_instance = json2space(self.json) rstate = np.random.RandomState() trials = hp.Trials() domain = hp.Domain(None, search_space_instance, pass_expr_memo_ctrl=None) algorithm = self._choose_tuner(self.algorithm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_trial_result(self, parameter_id, parameters, value): """ Record an observation of the objective function Parameters parameter_id : int parameters : d...
reward = extract_scalar_reward(value) # restore the paramsters contains '_index' if parameter_id not in self.total_data: raise RuntimeError('Received parameter_id not in total_data.') params = self.total_data[parameter_id] if self.optimize_mode is OptimizeMode.Maxim...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if idxs_map is None: idxs_map = {} assert set(idxs.keys()) == set(vals.keys()) misc_by_id = {m['tid']: m for m in miscs} for m in miscs: m['idxs'] = dict([(key, []) for key in idxs]) m['vals'] = dict([(key, []) for key in idxs]) for key in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_suggestion(self, random_search=False): """get suggestion from hyperopt Parameters random_search : bool flag to indicate random search or not (default: {F...
rval = self.rval trials = rval.trials algorithm = rval.algo new_ids = rval.trials.new_trial_ids(1) rval.trials.refresh() random_state = rval.rstate.randint(2**31-1) if random_search: new_trials = hp.rand.suggest(new_ids, rval.domain, trials, random_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def next_hyperparameter_lowest_mu(fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_starting_points, minimize_constraints_fun=None): ''' "Lowest Mu" acquisition ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_training) inputs = tf.reshape( inputs, shape=[max_char_length, -1, self.cfg.char_embed_dim]) char_lengths = tf.reshape(cha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self.tuner.receive_trial_result(id_, _trial_params[id_], value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: return history = _trial_history[trial_job_id] history[data['sequence']] = data['value'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_final_metric_data(data) else: self.enqueue_command(CommandType.ReportMetricData, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_data=(x_test, y_test), epochs=args.epochs, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name """Randomly generate num hyperparameter confi...
global _KEY # pylint: disable=global-statement assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.bracket_id, self.i) params = json2paramater(searchspace_json, random_state) params[_KEY...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _record_hyper_configs(self, hyper_configs): """after generating one round of hyperconfigs, this function records the generated hyperconfigs, creates a dict t...
self.hyper_configs.append(hyper_configs) self.configs_perf.append(dict()) self.num_finished_configs.append(0) self.num_configs_to_run.append(len(hyper_configs)) self.increase_i()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def setType(key, type): '''check key type''' return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))), )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> 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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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])...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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'))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 running...') return running, response = check_rest_server_quick(rest_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 == 'choice': if oldy != None: _index = oldy[NodeType.Index.value] y += jso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 + '-' + _type Rand |= is_rand[name] if Rand is True: if _type == 'choice': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: value = params[key] result[key] = value return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_json) self.random_state = np.random.RandomState() self.population = [] is_rand = dict() for item in self.space: is_rand[item] = True for _ in range(self.population_size): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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), ] return attribute_difference(att_diff) if is_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 + 1 for i in range(len_a): for j in range(len_b): f[i][j] = min( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, b) return distance_matrix[linear_sum_assignment(distance_matrix)].sum() + abs( len(list_a) - len(list_b) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_right_k = edit_distance_matrix(self._x, train_x) down_left_k = np.transpose(up_right...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_embedding_matrix(self._distance_matrix) k_matrix[np.diag_indices_from(k_matrix)] += s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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": children} return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 laye...
if self.graph_type == LayerType.input.value: return hasher = hashlib.md5() hasher.update(LayerType(self.graph_type).name.encode('ascii')) hasher.update(str(self.size).encode('ascii')) for i in self.input: if layers[i].hash_id is None: rais...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_all_config(self): '''get all of config values''' return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def remove_experiment(self, id): '''remove an experiment by id''' if id in self.experiments: self.experiments.pop(id) self.write_file()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_...