INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
deeper graph | def to_deeper_graph(graph):
''' deeper graph
'''
weighted_layer_ids = graph.deep_layer_ids()
if len(weighted_layer_ids) >= Constant.MAX_LAYERS:
return None
deeper_layer_ids = sample(weighted_layer_ids, 1)
for layer_id in deeper_layer_ids:
layer = graph.layer_list[layer_id]
... |
judge if a graph is legal or not. | def legal_graph(graph):
'''judge if a graph is legal or not.
'''
descriptor = graph.extract_descriptor()
skips = descriptor.skip_connections
if len(skips) != len(set(skips)):
return False
return True |
core transform function for graph. | def transform(graph):
'''core transform function for graph.
'''
graphs = []
for _ in range(Constant.N_NEIGHBOURS * 2):
random_num = randrange(3)
temp_graph = None
if random_num == 0:
temp_graph = to_deeper_graph(deepcopy(graph))
elif random_num == 1:
... |
low: an float that represent an lower bound
high: an float that represent an upper bound
random_state: an object of numpy.random.RandomState | def uniform(low, high, random_state):
'''
low: an float that represent an lower bound
high: an float that represent an upper bound
random_state: an object of numpy.random.RandomState
'''
assert high > low, 'Upper bound must be larger than lower bound'
return random_state.uniform(low, high) |
low: an float that represent an lower bound
high: an float that represent an upper bound
q: sample step
random_state: an object of numpy.random.RandomState | def quniform(low, high, q, random_state):
'''
low: an float that represent an lower bound
high: an float that represent an upper bound
q: sample step
random_state: an object of numpy.random.RandomState
'''
return np.round(uniform(low, high, random_state) / q) * q |
low: an float that represent an lower bound
high: an float that represent an upper bound
random_state: an object of numpy.random.RandomState | def loguniform(low, high, random_state):
'''
low: an float that represent an lower bound
high: an float that represent an upper bound
random_state: an object of numpy.random.RandomState
'''
assert low > 0, 'Lower bound must be positive'
return np.exp(uniform(np.log(low), np.log(high), random... |
low: an float that represent an lower bound
high: an float that represent an upper bound
q: sample step
random_state: an object of numpy.random.RandomState | def qloguniform(low, high, q, random_state):
'''
low: an float that represent an lower bound
high: an float that represent an upper bound
q: sample step
random_state: an object of numpy.random.RandomState
'''
return np.round(loguniform(low, high, random_state) / q) * q |
mu: float or array_like of floats
sigma: float or array_like of floats
q: sample step
random_state: an object of numpy.random.RandomState | def qnormal(mu, sigma, q, random_state):
'''
mu: float or array_like of floats
sigma: float or array_like of floats
q: sample step
random_state: an object of numpy.random.RandomState
'''
return np.round(normal(mu, sigma, random_state) / q) * q |
mu: float or array_like of floats
sigma: float or array_like of floats
random_state: an object of numpy.random.RandomState | def lognormal(mu, sigma, random_state):
'''
mu: float or array_like of floats
sigma: float or array_like of floats
random_state: an object of numpy.random.RandomState
'''
return np.exp(normal(mu, sigma, random_state)) |
mu: float or array_like of floats
sigma: float or array_like of floats
q: sample step
random_state: an object of numpy.random.RandomState | def qlognormal(mu, sigma, q, random_state):
'''
mu: float or array_like of floats
sigma: float or array_like of floats
q: sample step
random_state: an object of numpy.random.RandomState
'''
return np.round(lognormal(mu, sigma, random_state) / q) * q |
Predict by Gaussian Process Model | def predict(parameters_value, regressor_gp):
'''
Predict by Gaussian Process Model
'''
parameters_value = numpy.array(parameters_value).reshape(-1, len(parameters_value))
mu, sigma = regressor_gp.predict(parameters_value, return_std=True)
return mu[0], sigma[0] |
Call rest get method | def rest_get(url, timeout):
'''Call rest get method'''
try:
response = requests.get(url, timeout=timeout)
return response
except Exception as e:
print('Get exception {0} when sending http get to url {1}'.format(str(e), url))
return None |
Call rest post method | def rest_post(url, data, timeout, rethrow_exception=False):
'''Call rest post method'''
try:
response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
data=data, timeout=timeout)
return response
except Exceptio... |
Call rest put method | def rest_put(url, data, timeout):
'''Call rest put method'''
try:
response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
data=data, timeout=timeout)
return response
except Exception as e:
print('Get ex... |
Call rest delete method | def rest_delete(url, timeout):
'''Call rest delete method'''
try:
response = requests.delete(url, timeout=timeout)
return response
except Exception as e:
print('Get exception {0} when sending http delete to url {1}'.format(str(e), url))
return None |
update the best performance of completed trial job
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise | def trial_end(self, trial_job_id, success):
"""update the best performance of completed trial job
Parameters
----------
trial_job_id: int
trial job id
success: bool
True if succssfully finish the experiment, False otherwise
"""
if ... |
assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
Returns
-------
bool
AssessResult.Goo... | def assess_trial(self, trial_job_id, trial_history):
"""assess whether a trial should be early stop by curve fitting algorithm
Parameters
----------
trial_job_id: int
trial job id
trial_history: list
The history performance matrix of each trial
R... |
data is search space | def handle_initialize(self, data):
'''
data is search space
'''
self.tuner.update_search_space(data)
send(CommandType.Initialized, '')
return True |
Returns a set of trial neural architecture, as a serializable object.
Parameters
----------
parameter_id : int | def generate_parameters(self, parameter_id):
"""
Returns a set of trial neural architecture, as a serializable object.
Parameters
----------
parameter_id : int
"""
if not self.history:
self.init_search()
new_father_id = None
generated... |
Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key. | def receive_trial_result(self, parameter_id, parameters, value):
""" Record an observation of the objective function.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""... |
Call the generators to generate the initial architectures for the search. | def init_search(self):
"""Call the generators to generate the initial architectures for the search."""
if self.verbose:
logger.info("Initializing search.")
for generator in self.generators:
graph = generator(self.n_classes, self.input_shape).generate(
self... |
Generate the next neural architecture.
Returns
-------
other_info: any object
Anything to be saved in the training queue together with the architecture.
generated_graph: Graph
An instance of Graph. | def generate(self):
"""Generate the next neural architecture.
Returns
-------
other_info: any object
Anything to be saved in the training queue together with the architecture.
generated_graph: Graph
An instance of Graph.
"""
generated_grap... |
Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instance of Graph. The trained neural architecture.
metric_value: float... | def update(self, other_info, graph, metric_value, model_id):
""" Update the controller with evaluation result of a neural architecture.
Parameters
----------
other_info: any object
In our case it is the father ID in the search tree.
graph: Graph
An instan... |
Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict | def add_model(self, metric_value, model_id):
""" Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict
"""
if self.verbose:
lo... |
Get the best model_id from history using the metric value | def get_best_model_id(self):
""" Get the best model_id from history using the metric value
"""
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"])["mod... |
Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation | def load_model_by_id(self, model_id):
"""Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation
"""
with open(os.path.join(self... |
Random sample some init seed within bounds. | 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)] |
Return median | def get_median(temp_list):
"""Return median
"""
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 |
Update the self.x_bounds and self.x_types by the search_space.json
Parameters
----------
search_space : dict | def update_search_space(self, search_space):
"""Update the self.x_bounds and self.x_types by the search_space.json
Parameters
----------
search_space : dict
"""
self.x_bounds = [[] for i in range(len(search_space))]
self.x_types = [NONE_TYPE for i in range(len(se... |
Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict | def _pack_output(self, init_parameter):
"""Pack the output
Parameters
----------
init_parameter : dict
Returns
-------
output : dict
"""
output = {}
for i, param in enumerate(init_parameter):
output[self.key_order[i]] = param
... |
Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixture Model.
Parameters
----------
... | def generate_parameters(self, parameter_id):
"""Generate next parameter for trial
If the number of trial result is lower than cold start number,
metis will first random generate some parameters.
Otherwise, metis will choose the parameters by the Gussian Process Model and the Gussian Mixt... |
Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key. | def receive_trial_result(self, parameter_id, parameters, value):
"""Tuner receive result from trial.
Parameters
----------
parameter_id : int
parameters : dict
value : dict/float
if value is dict, it should have "default" key.
"""
value = extr... |
Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' | def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("Im... |
Trains GP regression model | 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_bounds=(1e-12, 1e12)) * \
... |
generate all possible configs for hyperparameters from hyperparameter space.
ss_spec: hyperparameter space | 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():
_type = ss_spec['_type']
_... |
parse type of quniform parameter and return a list | 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_value[1], param_value[2]
interval = (hi... |
parse type of quniform or qloguniform | 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_value[:2])
return list(np.exp(self.... |
Enumerate all possible combinations of all parameters
para: {key1: [v11, v12, ...], key2: [v21, v22, ...], ...}
return: {{key1: v11, key2: v21, ...}, {key1: v11, key2: v22, ...}, ...} | 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, ...}, ...}
'''
if len(para) == 1:
for key, value... |
Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' | def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("I... |
Log message into stdout | 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)) |
Write buffer data into logger/stdout | 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.logger.log(self.log_level, line.rstrip())
... |
Run the thread, logging everything.
If the log_collection is 'none', the log content will not be enqueued | def run(self):
"""Run the thread, logging everything.
If the log_collection is 'none', the log content will not be enqueued
"""
for line in iter(self.pipeReader.readline, ''):
self.orig_stdout.write(line.rstrip() + '\n')
self.orig_stdout.flush()
if ... |
Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int. | def extract_scalar_reward(value, scalar_key='default'):
"""
Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int.
"""
if isinstance... |
convert dict type to tuple to solve unhashable problem. | def convert_dict2tuple(value):
"""
convert dict type to tuple to solve unhashable problem.
"""
if isinstance(value, dict):
for _keys in value:
value[_keys] = convert_dict2tuple(value[_keys])
return tuple(sorted(value.items()))
else:
return value |
Initialize dispatcher logging configuration | def init_dispatcher_logger():
""" Initialize dispatcher logging configuration"""
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, dispat... |
We opted for a single multidimensional KDE compared to the
hierarchy of one-dimensional KDEs used in TPE. The dimensional is
seperated by budget. This function sample a configuration from
largest budget. Firstly we sample "num_samples" configurations,
then prefer one with the largest l(x... | def sample_from_largest_budget(self, info_dict):
"""We opted for a single multidimensional KDE compared to the
hierarchy of one-dimensional KDEs used in TPE. The dimensional is
seperated by budget. This function sample a configuration from
largest budget. Firstly we sample "num_samples" ... |
Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
config
return a valid confi... | def get_config(self, budget):
"""Function to sample a new configuration
This function is called inside BOHB to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
Returns
-------
... |
Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the parameters
budget: float
the budget of the parameters
parameters: d... | def new_result(self, loss, budget, parameters, update_model=True):
"""
Function to register finished runs. Every time a run has finished, this function should be called
to register it with the loss.
Parameters:
-----------
loss: float
the loss of the paramete... |
Check the search space is valid: only contains 'choice' type
Parameters
----------
search_space : dict | def is_valid(self, search_space):
"""
Check the search space is valid: only contains 'choice' type
Parameters
----------
search_space : dict
"""
if not len(search_space) == 1:
raise RuntimeError('BatchTuner only supprt one combined-paramreters... |
Returns a dict of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int | def generate_parameters(self, parameter_id):
"""Returns a dict of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
"""
self.count +=1
if self.count>len(self.values)-1:
raise nni.NoMoreTrialError('no more par... |
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 number for preventing ZeroDivision Error.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse ... | 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 number for preventing ZeroDivision Error.
... |
Applies multihead attention.
Args:
queries: A 3d tensor with shape of [N, T_q, C_q].
keys: A 3d tensor with shape of [N, T_k, C_k].
num_units: A cdscalar. Attention size.
dropout_rate: A floating point number.
is_training: Boolean. Controller of mechanism for dropout.
causality:... | def multihead_attention(queries,
keys,
scope="multihead_attention",
num_units=None,
num_heads=4,
dropout_rate=0,
is_training=True,
causality=False):
... |
Return positinal embedding. | def positional_encoding(inputs,
num_units=None,
zero_pad=True,
scale=True,
scope="positional_encoding",
reuse=None):
'''
Return positinal embedding.
'''
Shape = tf.shape(inputs)
N ... |
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 `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the ... | 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 `variable_scope`.
reuse: Boolean, whether to r... |
Generate search space.
Return a serializable search space object.
module_name: name of the module (str)
code: user code (str) | def generate(module_name, code):
"""Generate search space.
Return a serializable search space object.
module_name: name of the module (str)
code: user code (str)
"""
try:
ast_tree = ast.parse(code)
except Exception:
raise RuntimeError('Bad Python code')
visitor = SearchS... |
Call rest put method | 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)
return response
except Exception as except... |
Call rest post method | 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)
return response
except Exception as ex... |
Call rest get method | 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 None |
Call rest delete method | 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)
return None |
Check if restful server is ready | 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:
return True, response
els... |
Check if restful server is ready, only check once | 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 |
Vapor pressure model
Parameters
----------
x: int
a: float
b: float
c: float
Returns
-------
float
np.exp(a+b/x+c*np.log(x)) | def vap(x, a, b, c):
"""Vapor pressure model
Parameters
----------
x: int
a: float
b: float
c: float
Returns
-------
float
np.exp(a+b/x+c*np.log(x))
"""
return np.exp(a+b/x+c*np.log(x)) |
logx linear
Parameters
----------
x: int
a: float
b: float
Returns
-------
float
a * np.log(x) + b | def logx_linear(x, a, b):
"""logx linear
Parameters
----------
x: int
a: float
b: float
Returns
-------
float
a * np.log(x) + b
"""
x = np.log(x)
return a*x + b |
dr hill zero background
Parameters
----------
x: int
theta: float
eta: float
kappa: float
Returns
-------
float
(theta* x**eta) / (kappa**eta + x**eta) | def dr_hill_zero_background(x, theta, eta, kappa):
"""dr hill zero background
Parameters
----------
x: int
theta: float
eta: float
kappa: float
Returns
-------
float
(theta* x**eta) / (kappa**eta + x**eta)
"""
return (theta* x**eta) / (kappa**eta + x**eta) |
logistic power
Parameters
----------
x: int
a: float
b: float
c: float
Returns
-------
float
a/(1.+(x/np.exp(b))**c) | def log_power(x, a, b, c):
""""logistic power
Parameters
----------
x: int
a: float
b: float
c: float
Returns
-------
float
a/(1.+(x/np.exp(b))**c)
"""
return a/(1.+(x/np.exp(b))**c) |
pow4
Parameters
----------
x: int
alpha: float
a: float
b: float
c: float
Returns
-------
float
c - (a*x+b)**-alpha | def pow4(x, alpha, a, b, c):
"""pow4
Parameters
----------
x: int
alpha: float
a: float
b: float
c: float
Returns
-------
float
c - (a*x+b)**-alpha
"""
return c - (a*x+b)**-alpha |
Morgan-Mercer-Flodin
http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm
Parameters
----------
x: int
alpha: float
beta: float
kappa: float
delta: float
Returns
-------
float
alpha - (alpha - beta) / (1. + (kappa * x)**delta) | def mmf(x, alpha, beta, kappa, delta):
"""Morgan-Mercer-Flodin
http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm
Parameters
----------
x: int
alpha: float
beta: float
kappa: float
delta: float
Returns
-------
float
alpha - (alpha ... |
exp4
Parameters
----------
x: int
c: float
a: float
b: float
alpha: float
Returns
-------
float
c - np.exp(-a*(x**alpha)+b) | def exp4(x, c, a, b, alpha):
"""exp4
Parameters
----------
x: int
c: float
a: float
b: float
alpha: float
Returns
-------
float
c - np.exp(-a*(x**alpha)+b)
"""
return c - np.exp(-a*(x**alpha)+b) |
Weibull model
http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm
Parameters
----------
x: int
alpha: float
beta: float
kappa: float
delta: float
Returns
-------
float
alpha - (alpha - beta) * np.exp(-(kappa * x)**delta) | def weibull(x, alpha, beta, kappa, delta):
"""Weibull model
http://www.pisces-conservation.com/growthhelp/index.html?morgan_mercer_floden.htm
Parameters
----------
x: int
alpha: float
beta: float
kappa: float
delta: float
Returns
-------
float
alpha - (alpha - b... |
http://www.pisces-conservation.com/growthhelp/janoschek.htm
Parameters
----------
x: int
a: float
beta: float
k: float
delta: float
Returns
-------
float
a - (a - beta) * np.exp(-k*x**delta) | def janoschek(x, a, beta, k, delta):
"""http://www.pisces-conservation.com/growthhelp/janoschek.htm
Parameters
----------
x: int
a: float
beta: float
k: float
delta: float
Returns
-------
float
a - (a - beta) * np.exp(-k*x**delta)
"""
return a - (a - bet... |
Definite the arguments users need to follow and input | 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_defaults(func=nni_info)
# create subparse... |
generate stdout and stderr log path | 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, stderr_full_path |
print log information | 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:')
print(check_output_command(stderr_full_path)) |
Find nni lib from the following locations in order
Return nni root directory if it exists | def get_nni_installation_path():
''' Find nni lib from the following locations in order
Return nni root directory if it exists
'''
def try_installation_path_sequentially(*sitepackages):
'''Try different installation path sequentially util nni is found.
Return None if nothing is found
... |
Run nni manager process | 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, please reset the port!\n' \
'You could u... |
set trial configuration | 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_OUT)
if check_response(response):
... |
set local configuration | 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 request_data['local_config'] and request_data... |
set nniManagerIp | 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['nniManagerIp'] }
response = rest_put(clu... |
set kubeflow configuration | 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']
response = rest_put(cluster_metadata_ur... |
Call startExperiment (rest POST /experiment) with yaml file content | 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'] = experiment_config['experimentName']
reque... |
follow steps to start rest server and start experiment | 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 experiment_config['tuner'].get('builtinTunerName... |
resume an experiment | 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:
print_error('Please set experiment id... |
start a new experiment | 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):
print_error('Please set correct co... |
use least squares to fit all default curves parameter seperately
Returns
-------
None | def fit_theta(self):
"""use least squares to fit all default curves parameter seperately
Returns
-------
None
"""
x = range(1, self.point_num + 1)
y = self.trial_history
for i in range(NUM_OF_FUNCTIONS):
model = curve_combination_model... |
filter the poor performing curve
Returns
-------
None | def filter_curve(self):
"""filter the poor performing curve
Returns
-------
None
"""
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_FUN... |
return the predict y of 'model' when epoch = pos
Parameters
----------
model: string
name of the curve function model
pos: int
the epoch number of the position you want to predict
Returns
-------
int:
The expected matr... | def predict_y(self, model, pos):
"""return the predict y of 'model' when epoch = pos
Parameters
----------
model: string
name of the curve function model
pos: int
the epoch number of the position you want to predict
Returns
------... |
return the value of the f_comb when epoch = pos
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
int
... | def f_comb(self, pos, sample):
"""return the value of the f_comb when epoch = pos
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
... |
normalize weight
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Returns
-------
list
... | def normalize_weight(self, samples):
"""normalize weight
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
... |
returns the value of sigma square, given the weight's sample
Parameters
----------
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
float
the value of sigma square, given the weight's sa... | def sigma_sq(self, sample):
"""returns the value of sigma square, given the weight's sample
Parameters
----------
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
float
the value... |
returns the value of normal distribution, given the weight's sample and target position
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk... | def normal_distribution(self, pos, sample):
"""returns the value of normal distribution, given the weight's sample and target position
Parameters
----------
pos: int
the epoch number of the position you want to predict
sample: list
sample is a (1 ... |
likelihood
Parameters
----------
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
float
likelihood | def likelihood(self, samples):
"""likelihood
Parameters
----------
sample: list
sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
Returns
-------
float
likelihood
"""
ret = np.ones(NUM_OF_INST... |
priori distribution
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Returns
-------
float
... | def prior(self, samples):
"""priori distribution
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Retu... |
posterior probability
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Returns
-------
... | def target_distribution(self, samples):
"""posterior probability
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}... |
Adjust the weight of each function using mcmc sampling.
The initial value of each weight is evenly distribute.
Brief introduction:
(1)Definition of sample:
Sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
(2)Definition of samples:
Samples is... | def mcmc_sampling(self):
"""Adjust the weight of each function using mcmc sampling.
The initial value of each weight is evenly distribute.
Brief introduction:
(1)Definition of sample:
Sample is a (1 * NUM_OF_FUNCTIONS) matrix, representing{w1, w2, ... wk}
(2)Definitio... |
predict the value of target position
Parameters
----------
trial_history: list
The history performance matrix of each trial.
Returns
-------
float
expected final result performance of this hyperparameter config | def predict(self, trial_history):
"""predict the value of target position
Parameters
----------
trial_history: list
The history performance matrix of each trial.
Returns
-------
float
expected final result performance of this hype... |
Detect the outlier | 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 + 1, len(samples_x)))
outlier = None
... |
deeper conv layer. | 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 = tuple(map(lambda x: int((x - 1) / 2), filt... |
deeper dense layer. | 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(
(add_noise(weight, np.array([0, 1]... |
wider previous dense layer. | 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.randint(n_units2, size=n_add)
student_w ... |
wider previous conv layer. | 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,
kernel_size=layer.kernel_size,
)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.