INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Generate the scenario. The scenario - object ( smac. scenario. scenario. Scenario ) is used to configure SMAC and can be constructed either by providing an actual scenario - object or by specifing the options in a scenario file. Reference: https:// automl. github. io/ SMAC3/ stable/ options. html
def generate_scenario(ss_content): """Generate the scenario. The scenario-object (smac.scenario.scenario.Scenario) is used to configure SMAC and can be constructed either by providing an actual scenario-object, or by specifing the options in a scenario file. Reference: https://automl.github.io/SMAC3/s...
Load or create dataset
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 = ...
The distance between two layers.
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)...
The attribute distance.
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)
The distance between the layers of two neural networks.
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 + ...
The distance between two skip - connections.
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))
The distance between the skip - connections of two neural networks.
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, ...
The distance between two neural networks. Args: x: An instance of NetworkDescriptor. y: An instance of NetworkDescriptor Returns: The edit - distance between x and y.
def edit_distance(x, y): """The distance between two neural networks. Args: x: An instance of NetworkDescriptor. y: An instance of NetworkDescriptor Returns: The edit-distance between x and y. """ ret = layers_distance(x.layers, y.layers) ret += Constant.KERNEL_LAMBDA * ...
Calculate the edit distance. Args: train_x: A list of neural architectures. train_y: A list of neural architectures. Returns: An edit - distance matrix.
def edit_distance_matrix(train_x, train_y=None): """Calculate the edit distance. Args: train_x: A list of neural architectures. train_y: A list of neural architectures. Returns: An edit-distance matrix. """ if train_y is None: ret = np.zeros((train_x.shape[0], train_x...
The Euclidean distance between two vectors.
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)
Use Bourgain algorithm to embed the neural architectures based on their edit - distance. Args: distance_matrix: A matrix of edit - distances. Returns: A matrix of distances after embedding.
def bourgain_embedding_matrix(distance_matrix): """Use Bourgain algorithm to embed the neural architectures based on their edit-distance. Args: distance_matrix: A matrix of edit-distances. Returns: A matrix of distances after embedding. """ distance_matrix = np.array(distance_matrix)...
Check if the target descriptor is in the descriptors.
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
Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values.
def fit(self, train_x, train_y): """ Fit the regressor with more data. Args: train_x: A list of NetworkDescriptor. train_y: A list of metric values. """ if self.first_fitted: self.incremental_fit(train_x, train_y) else: self.first_f...
Incrementally fit the regressor.
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...
Fit the regressor for the first time.
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_e...
Predict the result. Args: train_x: A list of NetworkDescriptor. Returns: y_mean: The predicted mean. y_std: The predicted standard deviation.
def predict(self, train_x): """Predict the result. Args: train_x: A list of NetworkDescriptor. Returns: y_mean: The predicted mean. y_std: The predicted standard deviation. """ k_trans = np.exp(-np.power(edit_distance_matrix(train_x, self._x), ...
Generate new architecture. Args: descriptors: All the searched neural architectures. Returns: graph: An instance of Graph. A morphed neural network with weights. father_id: The father node ID in the search tree.
def generate(self, descriptors): """Generate new architecture. Args: descriptors: All the searched neural architectures. Returns: graph: An instance of Graph. A morphed neural network with weights. father_id: The father node ID in the search tree. """ ...
estimate the value of generated graph
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
add child to search tree itself. Arguments: u { int } -- father id v { int } -- child id
def add_child(self, u, v): ''' add child to search tree itself. Arguments: u {int} -- father id v {int} -- child id ''' if u == -1: self.root = v self.adj_list[v] = [] return if v not in self.adj_list[u]: s...
A recursive function to return the content of the tree in a dict.
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": chil...
Train a network from a specific graph.
def train_with_graph(p_graph, qp_pairs, dev_qp_pairs): ''' Train a network from a specific graph. ''' global sess with tf.Graph().as_default(): train_model = GAG(cfg, embed, p_graph) train_model.build_net(is_training=True) tf.get_variable_scope().reuse_variables() dev...
Returns multiple sets of trial ( hyper - ) parameters as iterable of serializable objects. Call generate_parameters () by count times by default. User code must override either this function or generate_parameters (). If there s no more trial user should raise nni. NoMoreTrialError exception in generate_parameters (). ...
def generate_multiple_parameters(self, parameter_id_list): """Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects. Call 'generate_parameters()' by 'count' times by default. User code must override either this function or 'generate_parameters()'. If ther...
Load graph
def graph_loads(graph_json): ''' Load graph ''' layers = [] for layer in graph_json['layers']: layer_info = Layer(layer['graph_type'], layer['input'], layer['output'], layer['size'], layer['hash_id']) layer_info.is_delete = layer['is_delete'] _logger.debug('append layer {}'.f...
Calculation of hash_id of Layer. Which is determined by the properties of itself and the hash_id s of input layers
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 layers """ if self.graph_type == LayerType.input.value: return hasher = hashlib.md5() hasher.update(Lay...
update hash id of each layer in topological order/ recursively hash id will be used in weight sharing
def update_hash(self): """ update hash id of each layer, in topological order/recursively hash id will be used in weight sharing """ _logger.debug('update hash') layer_in_cnt = [len(layer.input) for layer in self.layers] topo_queue = deque([i for i, layer in enume...
Initialize root logger. This will redirect anything from logging. getLogger () as well as stdout to specified file. logger_file_path: path of logger file ( path - like object ).
def init_logger(logger_file_path, log_level_name='info'): """Initialize root logger. This will redirect anything from logging.getLogger() as well as stdout to specified file. logger_file_path: path of logger file (path-like object). """ log_level = log_level_map.get(log_level_name, logging.INFO) ...
Create simple convolutional model
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,...
Load MNIST dataset
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...
Train model
def train(args, params): ''' Train model ''' x_train, y_train, x_test, y_test = load_mnist_data(args) model = create_mnist_model(params) # nni model.fit(x_train, y_train, batch_size=args.batch_size, epochs=args.epochs, verbose=1, validation_data=(x_test, y_test), callbacks=[SendMet...
Run on end of each epoch
def on_epoch_end(self, epoch, logs={}): ''' Run on end of each epoch ''' LOG.debug(logs) nni.report_intermediate_result(logs["val_acc"])
get all of config values
def get_all_config(self): '''get all of config values''' return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':'))
set { key: value } paris to self. config
def set_config(self, key, value): '''set {key:value} paris to self.config''' self.config = self.read_file() self.config[key] = value self.write_file()
save config to local file
def write_file(self): '''save config to local file''' if self.config: try: with open(self.config_file, 'w') as file: json.dump(self.config, file) except IOError as error: print('Error:', error) return
set { key: value } paris to self. experiment
def add_experiment(self, id, port, time, file_name, platform): '''set {key:value} paris to self.experiment''' self.experiments[id] = {} self.experiments[id]['port'] = port self.experiments[id]['startTime'] = time self.experiments[id]['endTime'] = 'N/A' self.experiments[id...
Update experiment
def update_experiment(self, id, key, value): '''Update experiment''' if id not in self.experiments: return False self.experiments[id][key] = value self.write_file() return True
remove an experiment by id
def remove_experiment(self, id): '''remove an experiment by id''' if id in self.experiments: self.experiments.pop(id) self.write_file()
save config to local file
def write_file(self): '''save config to local file''' try: with open(self.experiment_file, 'w') as file: json.dump(self.experiments, file) except IOError as error: print('Error:', error) return
load config from local file
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 {}
load data from file
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...
tokenize function.
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_...
Build the vocab from corpus.
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
Shuffle the step
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
Get batches data and shuffle.
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...
Get char input.
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...
Get word input.
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....
Given word return word index.
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
Get answer s index of begin and end.
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_...
Get bucket by length.
def get_buckets(min_length, max_length, bucket_count): ''' Get bucket by length. ''' if bucket_count <= 0: return [max_length] unit_length = int((max_length - min_length) // (bucket_count)) buckets = [min_length + unit_length * (i + 1) for i in range(0, bucket_count)] ...
tokenize function in Tokenizer.
def tokenize(self, text): ''' tokenize function in Tokenizer. ''' start = -1 tokens = [] for i, character in enumerate(text): if character == ' ' or character == '\t': if start >= 0: word = text[start:i] ...
generate new id and event hook for new Individual
def generate_new_id(self): """ generate new id and event hook for new Individual """ self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
initialize populations for evolution tuner
def init_population(self, population_size, graph_max_layer, graph_min_layer): """ initialize populations for evolution tuner """ population = [] graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer, inputs=[Layer(LayerType.input.value, ...
Returns a set of trial graph config as a serializable object. An example configuration: json { shared_id: [ 4a11b2ef9cb7211590dfe81039b27670 370af04de24985e5ea5b3d72b12644c9 11f646e9f650f5f3fedc12b6349ec60f 0604e5350b9c734dd2d770ee877cfb26 6dbeb8b022083396acb721267335f228 ba55380d6c84f5caeb87155d1c5fa654 ] graph: { lay...
def generate_parameters(self, parameter_id): """Returns a set of trial graph config, as a serializable object. An example configuration: ```json { "shared_id": [ "4a11b2ef9cb7211590dfe81039b27670", "370af04de24985e5ea5b3d72b12644c9", ...
Record an observation of the objective function parameter_id: int parameters: dict of parameters value: final metrics of the trial including reward
def receive_trial_result(self, parameter_id, parameters, value): ''' Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward ''' logger.debug('acquiring lock for param {...
update data
def _update_data(self, trial_job_id, trial_history): """update data Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial """ if trial_job_id not in self.running_history: ...
trial_end 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): """trial_end Parameters ---------- trial_job_id: int trial job id success: bool True if succssfully finish the experiment, False otherwise """ if trial_job_id in self.running_history: ...
assess_trial Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial
def assess_trial(self, trial_job_id, trial_history): """assess_trial Parameters ---------- trial_job_id: int trial job id trial_history: list The history performance matrix of each trial Returns ------- bool As...
Copy directory from HDFS to local
def copyHdfsDirectoryToLocal(hdfsDirectory, localDirectory, hdfsClient): '''Copy directory from HDFS to local''' if not os.path.exists(localDirectory): os.makedirs(localDirectory) try: listing = hdfsClient.list_status(hdfsDirectory) except Exception as exception: nni_log(LogType....
Copy file from HDFS to local
def copyHdfsFileToLocal(hdfsFilePath, localFilePath, hdfsClient, override=True): '''Copy file from HDFS to local''' if not hdfsClient.exists(hdfsFilePath): raise Exception('HDFS file {} does not exist!'.format(hdfsFilePath)) try: file_status = hdfsClient.get_file_status(hdfsFilePath) ...
Copy directory from local to HDFS
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient): '''Copy directory from local to HDFS''' if not os.path.exists(localDirectory): raise Exception('Local Directory does not exist!') hdfsClient.mkdirs(hdfsDirectory) result = True for file in os.listdir(localDirectory): ...
Copy a local file to HDFS directory
def copyFileToHdfs(localFilePath, hdfsFilePath, hdfsClient, override=True): '''Copy a local file to HDFS directory''' if not os.path.exists(localFilePath): raise Exception('Local file Path does not exist!') if os.path.isdir(localFilePath): raise Exception('localFile should not a directory!')...
Load dataset use boston dataset
def load_data(): '''Load dataset, use boston dataset''' boston = load_boston() X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, random_state=99, test_size=0.25) #normalize data ss_X = StandardScaler() ss_y = StandardScaler() X_train = ss_X.fit_transform(X_trai...
Get model according to parameters
def get_model(PARAMS): '''Get model according to parameters''' model_dict = { 'LinearRegression': LinearRegression(), 'SVR': SVR(), 'KNeighborsRegressor': KNeighborsRegressor(), 'DecisionTreeRegressor': DecisionTreeRegressor() } if not model_dict.get(PARAMS['model_name'])...
Train model and predict result
def run(X_train, X_test, y_train, y_test, PARAMS): '''Train model and predict result''' model.fit(X_train, y_train) predict_y = model.predict(X_test) score = r2_score(y_test, predict_y) LOG.debug('r2 score: %s' % score) nni.report_final_result(score)
Add a skip - connection to the descriptor. Args: u: Number of convolutional layers before the starting point. v: Number of convolutional layers before the ending point. connection_type: Must be either CONCAT_CONNECT or ADD_CONNECT.
def add_skip_connection(self, u, v, connection_type): """ Add a skip-connection to the descriptor. Args: u: Number of convolutional layers before the starting point. v: Number of convolutional layers before the ending point. connection_type: Must be either CONCAT_CONN...
NetworkDescriptor to json representation
def to_json(self): ''' NetworkDescriptor to json representation ''' skip_list = [] for u, v, connection_type in self.skip_connections: skip_list.append({"from": u, "to": v, "type": connection_type}) return {"node_list": self.layers, "skip_list": skip_list}
Add a layer to the Graph. Args: layer: An instance of the subclasses of StubLayer in layers. py. input_node_id: An integer. The ID of the input node of the layer. Returns: output_node_id: An integer. The ID of the output node of the layer.
def add_layer(self, layer, input_node_id): """Add a layer to the Graph. Args: layer: An instance of the subclasses of StubLayer in layers.py. input_node_id: An integer. The ID of the input node of the layer. Returns: output_node_id: An integer. The ID of the o...
Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer.
def _add_node(self, node): """Add a new node to node_list and give the node an ID. Args: node: An instance of Node. Returns: node_id: An integer. """ node_id = len(self.node_list) self.node_to_id[node] = node_id self.node_list.append(node) ...
Add a new layer to the graph. The nodes should be created in advance.
def _add_edge(self, layer, input_id, output_id): """Add a new layer to the graph. The nodes should be created in advance.""" if layer in self.layer_to_id: layer_id = self.layer_to_id[layer] if input_id not in self.layer_id_to_input_node_ids[layer_id]: self.layer_...
Redirect the layer to a new node. Change the edge originally from u_id to v_id into an edge from u_id to new_v_id while keeping all other property of the edge the same.
def _redirect_edge(self, u_id, v_id, new_v_id): """Redirect the layer to a new node. Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id` while keeping all other property of the edge the same. """ layer_id = None for index, edge_tuple in...
Replace the layer with a new layer.
def _replace_layer(self, layer_id, new_layer): """Replace the layer with a new layer.""" old_layer = self.layer_list[layer_id] new_layer.input = old_layer.input new_layer.output = old_layer.output new_layer.output.shape = new_layer.output_shape self.layer_list[layer_id] =...
Return the topological order of the node IDs from the input node to the output node.
def topological_order(self): """Return the topological order of the node IDs from the input node to the output node.""" q = Queue() in_degree = {} for i in range(self.n_nodes): in_degree[i] = 0 for u in range(self.n_nodes): for v, _ in self.adj_list[u]: ...
Given two node IDs return all the pooling layers between them.
def _get_pooling_layers(self, start_node_id, end_node_id): """Given two node IDs, return all the pooling layers between them.""" layer_list = [] node_list = [start_node_id] assert self._depth_first_search(end_node_id, layer_list, node_list) ret = [] for layer_id in layer_...
Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.
def _depth_first_search(self, target_id, layer_id_list, node_list): """Search for all the layers and nodes down the path. A recursive function to search all the layers and nodes between the node in the node_list and the node with target_id.""" assert len(node_list) <= self.n_nodes ...
Search the graph for all the layers to be widened caused by an operation. It is an recursive function with duplication check to avoid deadlock. It searches from a starting node u until the corresponding layers has been widened. Args: u: The starting node ID. start_dim: The position to insert the additional dimensions. ...
def _search(self, u, start_dim, total_dim, n_add): """Search the graph for all the layers to be widened caused by an operation. It is an recursive function with duplication check to avoid deadlock. It searches from a starting node u until the corresponding layers has been widened. Args: ...
Insert a relu - conv - bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses.
def to_deeper_model(self, target_id, new_layer): """Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses. """ self.operation_...
Widen the last dimension of the output of the pre_layer. Args: pre_layer_id: The ID of a convolutional layer or dense layer. n_add: The number of dimensions to add.
def to_wider_model(self, pre_layer_id, n_add): """Widen the last dimension of the output of the pre_layer. Args: pre_layer_id: The ID of a convolutional layer or dense layer. n_add: The number of dimensions to add. """ self.operation_history.append(("to_wider_mode...
Insert the new_layers after the node with start_node_id.
def _insert_new_layers(self, new_layers, start_node_id, end_node_id): """Insert the new_layers after the node with start_node_id.""" new_node_id = self._add_node(deepcopy(self.node_list[end_node_id])) temp_output_id = new_node_id for layer in new_layers[:-1]: temp_output_id =...
Add a weighted add skip - connection from after start node to end node. Args: start_id: The convolutional layer ID after which to start the skip - connection. end_id: The convolutional layer ID after which to end the skip - connection.
def to_add_skip_model(self, start_id, end_id): """Add a weighted add skip-connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-connection...
Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID after which to start the skip - connection. end_id: The convolutional layer ID after which to end the skip - connection.
def to_concat_skip_model(self, start_id, end_id): """Add a weighted add concatenate connection from after start node to end node. Args: start_id: The convolutional layer ID, after which to start the skip-connection. end_id: The convolutional layer ID, after which to end the skip-...
Extract the the description of the Graph as an instance of NetworkDescriptor.
def extract_descriptor(self): """Extract the the description of the Graph as an instance of NetworkDescriptor.""" main_chain = self.get_main_chain() index_in_main_chain = {} for index, u in enumerate(main_chain): index_in_main_chain[u] = index ret = NetworkDescriptor...
clear weights of the graph
def clear_weights(self): ''' clear weights of the graph ''' self.weighted = False for layer in self.layer_list: layer.weights = None
Return a list of layer IDs in the main chain.
def get_main_chain_layers(self): """Return a list of layer IDs in the main chain.""" main_chain = self.get_main_chain() ret = [] for u in main_chain: for v, layer_id in self.adj_list[u]: if v in main_chain and u in main_chain: ret.append(la...
Returns the main chain node ID list.
def get_main_chain(self): """Returns the main chain node ID list.""" pre_node = {} distance = {} for i in range(self.n_nodes): distance[i] = 0 pre_node[i] = i for i in range(self.n_nodes - 1): for u in range(self.n_nodes): for v...
Run the tuner. This function will never return unless raise.
def run(self): """Run the tuner. This function will never return unless raise. """ _logger.info('Start dispatcher') if dispatcher_env_vars.NNI_MODE == 'resume': self.load_checkpoint() while True: command, data = receive() if data: ...
Process commands in command queues.
def command_queue_worker(self, command_queue): """Process commands in command queues. """ while True: try: # set timeout to ensure self.stopping is checked periodically command, data = command_queue.get(timeout=3) try: ...
Enqueue command into command queues
def enqueue_command(self, command, data): """Enqueue command into command queues """ if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'): self.assessor_command_queue.put((command, data)) else: self.defau...
Worker thread to process a command.
def process_command_thread(self, request): """Worker thread to process a command. """ command, data = request if multi_thread_enabled(): try: self.process_command(command, data) except Exception as e: _logger.exception(str(e)) ...
Update values in the array to match their corresponding type
def match_val_type(vals, vals_bounds, vals_types): ''' Update values in the array, to match their corresponding type ''' vals_new = [] for i, _ in enumerate(vals_types): if vals_types[i] == "discrete_int": # Find the closest integer in the array, vals_bounds vals_new...
Random generate variable value within their bounds
def rand(x_bounds, x_types): ''' Random generate variable value within their bounds ''' outputs = [] for i, _ in enumerate(x_bounds): if x_types[i] == "discrete_int": temp = x_bounds[i][random.randint(0, len(x_bounds[i]) - 1)] outputs.append(temp) elif x_type...
wider graph
def to_wider_graph(graph): ''' wider graph ''' weighted_layer_ids = graph.wide_layer_ids() weighted_layer_ids = list( filter(lambda x: graph.layer_list[x].output.shape[-1], weighted_layer_ids) ) wider_layers = sample(weighted_layer_ids, 1) for layer_id in wider_layers: layer...
skip connection graph
def to_skip_connection_graph(graph): ''' skip connection graph ''' # The last conv layer cannot be widen since wider operator cannot be done over the two sides of flatten. weighted_layer_ids = graph.skip_connection_layer_ids() valid_connection = [] for skip_type in sorted([NetworkDescriptor.ADD_...
create new layer for the graph
def create_new_layer(layer, n_dim): ''' create new layer for the graph ''' input_shape = layer.output.shape dense_deeper_classes = [StubDense, get_dropout_class(n_dim), StubReLU] conv_deeper_classes = [get_conv_class(n_dim), get_batch_norm_class(n_dim), StubReLU] if is_layer(layer, "ReLU"): ...
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