Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def parse_rev_args(receive_msg):
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)
y_te... | [
" parse reveive msgs to global variable\n "
] |
Please provide a description of the function:def train_eval():
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,
v... | [
" train and eval the model\n "
] |
Please provide a description of the function:def on_epoch_end(self, epoch, logs=None):
if logs is None:
logs = dict()
logger.debug(logs)
nni.report_intermediate_result(logs["val_acc"]) | [
"\n Run on end of each epoch\n "
] |
Please provide a description of the function:def create_bracket_parameter_id(brackets_id, brackets_curr_decay, increased_id=-1):
if increased_id == -1:
increased_id = str(create_parameter_id())
params_id = '_'.join([str(brackets_id),
str(brackets_curr_decay),
... | [
"Create a full id for a specific bracket's hyperparameter configuration\n \n Parameters\n ----------\n brackets_id: int\n brackets id\n brackets_curr_decay:\n brackets curr decay\n increased_id: int\n increased id\n\n Returns\n -------\n int\n params id\n "
... |
Please provide a description of the function:def json2paramater(ss_spec, random_state):
if isinstance(ss_spec, dict):
if '_type' in ss_spec.keys():
_type = ss_spec['_type']
_value = ss_spec['_value']
if _type == 'choice':
_index = random_state.randint... | [
"Randomly generate values for hyperparameters from hyperparameter space i.e., x.\n \n Parameters\n ----------\n ss_spec:\n hyperparameter space\n random_state:\n random operator to generate random values\n\n Returns\n -------\n Parameter:\n Parameters in this experiment\... |
Please provide a description of the function:def get_n_r(self):
return math.floor(self.n / self.eta**self.i + _epsilon), math.floor(self.r * self.eta**self.i + _epsilon) | [
"return the values of n and r for the next round"
] |
Please provide a description of the function:def increase_i(self):
self.i += 1
if self.i > self.bracket_id:
self.no_more_trial = True | [
"i means the ith round. Increase i by 1"
] |
Please provide a description of the function:def set_config_perf(self, i, parameter_id, seq, value):
if parameter_id in self.configs_perf[i]:
if self.configs_perf[i][parameter_id][0] < seq:
self.configs_perf[i][parameter_id] = [seq, value]
else:
self.conf... | [
"update trial's latest result with its sequence number, e.g., epoch number or batch number\n \n Parameters\n ----------\n i: int\n the ith round\n parameter_id: int\n the id of the trial/parameter\n seq: int\n sequence number, e.g., epoch nu... |
Please provide a description of the function:def inform_trial_end(self, i):
global _KEY # pylint: disable=global-statement
self.num_finished_configs[i] += 1
_logger.debug('bracket id: %d, round: %d %d, finished: %d, all: %d', self.bracket_id, self.i, i, self.num_finished_configs[i], sel... | [
"If the trial is finished and the corresponding round (i.e., i) has all its trials finished,\n it will choose the top k trials for the next round (i.e., i+1)\n\n Parameters\n ----------\n i: int\n the ith round\n "
] |
Please provide a description of the function:def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name
global _KEY # pylint: disable=global-statement
assert self.i == 0
hyperparameter_configs = dict()
for _ in range(num):... | [
"Randomly generate num hyperparameter configurations from search space\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. Format: [[key1, ... |
Please provide a description of the function:def _record_hyper_configs(self, hyper_configs):
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() | [
"after generating one round of hyperconfigs, this function records the generated hyperconfigs,\n creates a dict to record the performance when those hyperconifgs are running, set the number of finished configs\n in this round to be 0, and increase the round number.\n\n Parameters\n -----... |
Please provide a description of the function:def _request_one_trial_job(self):
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.brackets[self.curr... | [
"get one trial job, i.e., one hyperparameter configuration."
] |
Please provide a description of the function:def handle_update_search_space(self, data):
self.searchspace_json = data
self.random_state = np.random.RandomState() | [
"data: JSON object, which is search space\n \n Parameters\n ----------\n data: int\n number of trial jobs\n "
] |
Please provide a description of the function:def handle_trial_end(self, data):
hyper_params = json_tricks.loads(data['hyper_params'])
bracket_id, i, _ = hyper_params['parameter_id'].split('_')
hyper_configs = self.brackets[int(bracket_id)].inform_trial_end(int(i))
if hyper_confi... | [
"\n Parameters\n ----------\n data: dict()\n it has three keys: trial_job_id, event, hyper_params\n trial_job_id: the id generated by training service\n event: the job's state\n hyper_params: the hyperparameters (a string) generated and returned by tu... |
Please provide a description of the function:def handle_report_metric_data(self, data):
value = extract_scalar_reward(data['value'])
bracket_id, i, _ = data['parameter_id'].split('_')
bracket_id = int(bracket_id)
if data['type'] == 'FINAL':
# sys.maxsize indicates th... | [
"\n Parameters\n ----------\n data: \n it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.\n \n Raises\n ------\n ValueError\n Data type not supported\n "
] |
Please provide a description of the function:def generate_parameters(self, parameter_id):
if len(self.population) <= 0:
logger.debug("the len of poplution lower than zero.")
raise Exception('The population is empty')
pos = -1
for i in range(len(self.population)):... | [
"Returns a set of trial graph config, as a serializable object.\n parameter_id : int\n "
] |
Please provide a description of the function: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
'''
... | [] |
Please provide a description of the function:def generate(self, model_len=None, model_width=None):
if model_len is None:
model_len = Constant.MODEL_LEN
if model_width is None:
model_width = Constant.MODEL_WIDTH
pooling_len = int(model_len / 4)
graph = Gr... | [
"Generates a CNN.\n Args:\n model_len: An integer. Number of convolutional layers.\n model_width: An integer. Number of filters for the convolutional layers.\n Returns:\n An instance of the class Graph. Represents the neural architecture graph of the generated model.\n... |
Please provide a description of the function:def generate(self, model_len=None, model_width=None):
if model_len is None:
model_len = Constant.MODEL_LEN
if model_width is None:
model_width = Constant.MODEL_WIDTH
if isinstance(model_width, list) and not len(model_w... | [
"Generates a Multi-Layer Perceptron.\n Args:\n model_len: An integer. Number of hidden layers.\n model_width: An integer or a list of integers of length `model_len`. If it is a list, it represents the\n number of nodes in each hidden layer. If it is an integer, all hidden... |
Please provide a description of the function:def generate_search_space(code_dir):
search_space = {}
if code_dir.endswith(slash):
code_dir = code_dir[:-1]
for subdir, _, files in os.walk(code_dir):
# generate module name from path
if subdir == code_dir:
package ... | [
"Generate search space from Python source code.\n Return a serializable search space object.\n code_dir: directory path of source files (str)\n "
] |
Please provide a description of the function:def expand_annotations(src_dir, dst_dir):
if src_dir[-1] == slash:
src_dir = src_dir[:-1]
if dst_dir[-1] == slash:
dst_dir = dst_dir[:-1]
annotated = False
for src_subdir, dirs, files in os.walk(src_dir):
assert src_subdir.... | [
"Expand annotations in user code.\n Return dst_dir if annotation detected; return src_dir if not.\n src_dir: directory path of user code (str)\n dst_dir: directory to place generated files (str)\n "
] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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)) | [] |
Please provide a description of the function: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'):
... | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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 r... | [] |
Please provide a description of the function: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_d... | [] |
Please provide a description of the function: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)
... | [] |
Please provide a description of the function:def setType(key, type):
'''check key type'''
return And(type, error=SCHEMA_TYPE_ERROR % (key, type.__name__)) | [] |
Please provide a description of the function:def setChoice(key, *args):
'''check choice'''
return And(lambda n: n in args, error=SCHEMA_RANGE_ERROR % (key, str(args))) | [] |
Please provide a description of the function: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))),
) | [] |
Please provide a description of the function: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)... | [] |
Please provide a description of the function: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(
... | [] |
Please provide a description of the function: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 l... | [] |
Please provide a description of the function: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:... | [] |
Please provide a description of the function: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):
laye... | [] |
Please provide a description of the function: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.") | [] |
Please provide a description of the function: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),
... | [] |
Please provide a description of the function: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] + h... | [] |
Please provide a description of the function: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]... | [] |
Please provide a description of the function:def conv2d(x_input, w_matrix):
return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME') | [
"conv2d returns a 2d convolution layer with full stride."
] |
Please provide a description of the function:def max_pool(x_input, pool_size):
return tf.nn.max_pool(x_input, ksize=[1, pool_size, pool_size, 1],
strides=[1, pool_size, pool_size, 1], padding='SAME') | [
"max_pool downsamples a feature map by 2X."
] |
Please provide a description of the function: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... | [] |
Please provide a description of the function:def build_net(self, is_training):
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.get_variabl... | [
"Build the whole neural network for the QA model.",
"Modify target for label smoothing."
] |
Please provide a description of the function: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:
... | [] |
Please provide a description of the function: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) | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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('pyth... | [] |
Please provide a description of the function: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, defa... | [] |
Please provide a description of the function: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 ... | [] |
Please provide a description of the function: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))
... | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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():
i... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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 ... | [] |
Please provide a description of the function: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_dic... | [] |
Please provide a description of the function: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_s... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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 n... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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('... | [] |
Please provide a description of the function: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... | [] |
Please provide a description of the function: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)... | [] |
Please provide a description of the function: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')))) | [] |
Please provide a description of the function: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)
... | [] |
Please provide a description of the function: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'))
seco... | [] |
Please provide a description of the function: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)
... | [] |
Please provide a description of the function: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_e... | [] |
Please provide a description of the function:def parse_trial_data(content):
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_... | [
"output: List[Dict]"
] |
Please provide a description of the function:def export_trials_data(args):
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not run... | [
"export experiment metadata to csv\n "
] |
Please provide a description of the function: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.... | [] |
Please provide a description of the function: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 = ... | [] |
Please provide a description of the function:def json2space(x, oldy=None, name=NodeType.Root.value):
y = list()
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
name = name + '-' + _type
if _type == 'choice':
... | [
"Change search space from json format to hyperopt format\n "
] |
Please provide a description of the function:def json2paramater(x, is_rand, random_state, oldy=None, Rand=False, name=NodeType.Root.value):
if isinstance(x, dict):
if NodeType.Type.value in x.keys():
_type = x[NodeType.Type.value]
_value = x[NodeType.Value.value]
nam... | [
"Json to pramaters.\n "
] |
Please provide a description of the function:def _split_index(params):
result = {}
for key in params:
if isinstance(params[key], dict):
value = params[key]['_value']
else:
value = params[key]
result[key] = value
return result | [
"Delete index information from params\n\n Parameters\n ----------\n params : dict\n\n Returns\n -------\n result : dict\n "
] |
Please provide a description of the function:def mutation(self, config=None, info=None, save_dir=None):
self.result = None
self.config = config
self.restore_dir = self.save_dir
self.save_dir = save_dir
self.info = info | [
"\n Parameters\n ----------\n config : str\n info : str\n save_dir : str\n "
] |
Please provide a description of the function:def update_search_space(self, search_space):
self.searchspace_json = search_space
self.space = json2space(self.searchspace_json)
self.random_state = np.random.RandomState()
self.population = []
is_rand = dict()
for it... | [
"Update search space. \n Search_space contains the information that user pre-defined.\n\n Parameters\n ----------\n search_space : dict\n "
] |
Please provide a description of the function:def generate_parameters(self, parameter_id):
if not self.population:
raise RuntimeError('The population is empty')
pos = -1
for i in range(len(self.population)):
if self.population[i].result is None:
po... | [
"Returns a dict of trial (hyper-)parameters, as a serializable object.\n\n Parameters\n ----------\n parameter_id : int\n \n Returns\n -------\n config : dict\n "
] |
Please provide a description of the function: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... | [] |
Please provide a description of the function:def get_json_content(file_path):
try:
with open(file_path, 'r') as file:
return json.load(file)
except TypeError as err:
print('Error: ', err)
return None | [
"Load json file content\n \n Parameters\n ----------\n file_path:\n path to the file\n \n Raises\n ------\n TypeError\n Error with the file path\n "
] |
Please provide a description of the function:def generate_pcs(nni_search_space_content):
categorical_dict = {}
search_space = nni_search_space_content
with open('param_config_space.pcs', 'w') as pcs_fd:
if isinstance(search_space, dict):
for key in search_space.keys():
... | [
"Generate the Parameter Configuration Space (PCS) which defines the \n legal ranges of the parameters to be optimized and their default values.\n \n Generally, the format is:\n # parameter_name categorical {value_1, ..., value_N} [default value]\n # parameter_name ordinal {value_1, ..., value_N} [def... |
Please provide a description of the function:def generate_scenario(ss_content):
with open('scenario.txt', 'w') as sce_fd:
sce_fd.write('deterministic = 0\n')
#sce_fd.write('output_dir = \n')
sce_fd.write('paramfile = param_config_space.pcs\n')
sce_fd.write('run_obj = quality\n')... | [
"Generate the scenario. The scenario-object (smac.scenario.scenario.Scenario) is used to configure SMAC and \n can be constructed either by providing an actual scenario-object, or by specifing the options in a scenario file.\n \n Reference: https://automl.github.io/SMAC3/stable/options.html\n\n The form... |
Please provide a description of the function: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='... | [] |
Please provide a description of the function:def layer_distance(a, b):
# 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.... | [
"The distance between two layers."
] |
Please provide a description of the function: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)
... | [] |
Please provide a description of the function:def layers_distance(list_a, list_b):
len_a = len(list_a)
len_b = len(list_b)
f = np.zeros((len_a + 1, len_b + 1))
f[-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 r... | [
"The distance between the layers of two neural networks."
] |
Please provide a description of the function:def skip_connection_distance(a, b):
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)) | [
"The distance between two skip-connections."
] |
Please provide a description of the function:def skip_connections_distance(list_a, list_b):
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_mat... | [
"The distance between the skip-connections of two neural networks."
] |
Please provide a description of the function:def edit_distance(x, y):
ret = layers_distance(x.layers, y.layers)
ret += Constant.KERNEL_LAMBDA * skip_connections_distance(
x.skip_connections, y.skip_connections
)
return ret | [
"The distance between two neural networks.\n Args:\n x: An instance of NetworkDescriptor.\n y: An instance of NetworkDescriptor\n Returns:\n The edit-distance between x and y.\n "
] |
Please provide a description of the function:def edit_distance_matrix(train_x, train_y=None):
if train_y is None:
ret = np.zeros((train_x.shape[0], train_x.shape[0]))
for x_index, x in enumerate(train_x):
for y_index, y in enumerate(train_x):
if x_index == y_index:
... | [
"Calculate the edit distance.\n Args:\n train_x: A list of neural architectures.\n train_y: A list of neural architectures.\n Returns:\n An edit-distance matrix.\n "
] |
Please provide a description of the function:def vector_distance(a, b):
a = np.array(a)
b = np.array(b)
return np.linalg.norm(a - b) | [
"The Euclidean distance between two vectors."
] |
Please provide a description of the function:def bourgain_embedding_matrix(distance_matrix):
distance_matrix = np.array(distance_matrix)
n = len(distance_matrix)
if n == 1:
return distance_matrix
np.random.seed(123)
distort_elements = []
r = range(n)
k = int(math.ceil(math.log(n... | [
"Use Bourgain algorithm to embed the neural architectures based on their edit-distance.\n Args:\n distance_matrix: A matrix of edit-distances.\n Returns:\n A matrix of distances after embedding.\n "
] |
Please provide a description of the function:def contain(descriptors, target_descriptor):
for descriptor in descriptors:
if edit_distance(descriptor, target_descriptor) < 1e-5:
return True
return False | [
"Check if the target descriptor is in the descriptors."
] |
Please provide a description of the function:def fit(self, train_x, train_y):
if self.first_fitted:
self.incremental_fit(train_x, train_y)
else:
self.first_fit(train_x, train_y) | [
" Fit the regressor with more data.\n Args:\n train_x: A list of NetworkDescriptor.\n train_y: A list of metric values.\n "
] |
Please provide a description of the function:def incremental_fit(self, train_x, train_y):
if not self._first_fitted:
raise ValueError("The first_fit function needs to be called first.")
train_x, train_y = np.array(train_x), np.array(train_y)
# Incrementally compute K
... | [
" Incrementally fit the regressor. "
] |
Please provide a description of the function:def first_fit(self, train_x, train_y):
train_x, train_y = np.array(train_x), np.array(train_y)
self._x = np.copy(train_x)
self._y = np.copy(train_y)
self._distance_matrix = edit_distance_matrix(self._x)
k_matrix = bourgain_e... | [
" Fit the regressor for the first time. "
] |
Please provide a description of the function:def predict(self, train_x):
k_trans = np.exp(-np.power(edit_distance_matrix(train_x, self._x), 2))
y_mean = k_trans.dot(self._alpha_vector) # Line 4 (y_mean = f_star)
# compute inverse K_inv of K based on its Cholesky
# decompositio... | [
"Predict the result.\n Args:\n train_x: A list of NetworkDescriptor.\n Returns:\n y_mean: The predicted mean.\n y_std: The predicted standard deviation.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.