Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def generate(self, descriptors): model_ids = self.search_tree.adj_list.keys() target_graph = None father_id = None descriptors = deepcopy(descriptors) elem_class = Elem if self.optimizemode is OptimizeMode.Maximize: ...
[ "Generate new architecture.\n Args:\n descriptors: All the searched neural architectures.\n Returns:\n graph: An instance of Graph. A morphed neural network with weights.\n father_id: The father node ID in the search tree.\n " ]
Please provide a description of the function: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 me...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function:def get_dict(self, u=None): if u is None: return self.get_dict(self.root) children = [] for v in self.adj_list[u]: children.append(self.get_dict(v)) ret = {"name": u, "children": children} return ret
[ " A recursive function to return the content of the tree in a dict." ]
Please provide a description of the function: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_v...
[]
Please provide a description of the function:def generate_multiple_parameters(self, parameter_id_list): result = [] for parameter_id in parameter_id_list: try: _logger.debug("generating param for {}".format(parameter_id)) res = self.generate_parameter...
[ "Returns multiple sets of trial (hyper-)parameters, as iterable of serializable objects.\n Call 'generate_parameters()' by 'count' times by default.\n User code must override either this function or 'generate_parameters()'.\n If there's no more trial, user should raise nni.NoMoreTrialError exce...
Please provide a description of the function: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_delet...
[]
Please provide a description of the function:def update_hash(self, layers: Iterable): if self.graph_type == LayerType.input.value: return hasher = hashlib.md5() hasher.update(LayerType(self.graph_type).name.encode('ascii')) hasher.update(str(self.size).encode('ascii'...
[ "\n Calculation of `hash_id` of Layer. Which is determined by the properties of itself, and the `hash_id`s of input layers\n " ]
Please provide a description of the function:def update_hash(self): _logger.debug('update hash') layer_in_cnt = [len(layer.input) for layer in self.layers] topo_queue = deque([i for i, layer in enumerate(self.layers) if not layer.is_delete and layer.graph_type == LayerType.input.value])...
[ "\n update hash id of each layer, in topological order/recursively\n hash id will be used in weight sharing\n " ]
Please provide a description of the function:def init_logger(logger_file_path, log_level_name='info'): log_level = log_level_map.get(log_level_name, logging.INFO) logger_file = open(logger_file_path, 'w') fmt = '[%(asctime)s] %(levelname)s (%(name)s/%(threadName)s) %(message)s' logging.Formatter.co...
[ "Initialize root logger.\n This will redirect anything from logging.getLogger() as well as stdout to specified file.\n logger_file_path: path of logger file (path-like object).\n " ]
Please provide a description of the function: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), activatio...
[]
Please provide a description of the function: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) / 25...
[]
Please provide a description of the function: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, validat...
[]
Please provide a description of the function:def on_epoch_end(self, epoch, logs={}): ''' Run on end of each epoch ''' LOG.debug(logs) nni.report_intermediate_result(logs["val_acc"])
[]
Please provide a description of the function:def get_all_config(self): '''get all of config values''' return json.dumps(self.config, indent=4, sort_keys=True, separators=(',', ':'))
[]
Please provide a description of the function: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()
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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]['...
[]
Please provide a description of the function: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
[]
Please provide a description of the function:def remove_experiment(self, id): '''remove an experiment by id''' if id in self.experiments: self.experiments.pop(id) self.write_file()
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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: ...
[]
Please provide a description of the function: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...
[]
Please provide a description of the 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_t...
[]
Please provide a description of the function: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.a...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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_pair...
[]
Please provide a description of the function: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)...
[]
Please provide a description of the function: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, ...
[]
Please provide a description of the function: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']: ...
[]
Please provide a description of the function: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'] ...
[]
Please provide a description of the function: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 * ...
[]
Please provide a description of the function: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: ...
[]
Please provide a description of the function:def generate_new_id(self): self.events.append(Event()) indiv_id = self.indiv_counter self.indiv_counter += 1 return indiv_id
[ "\n generate new id and event hook for new Individual\n " ]
Please provide a description of the function:def init_population(self, population_size, graph_max_layer, graph_min_layer): population = [] graph = Graph(max_layer_num=graph_max_layer, min_layer_num=graph_min_layer, inputs=[Layer(LayerType.input.value, output=[4, 5], size='...
[ "\n initialize populations for evolution tuner\n " ]
Please provide a description of the function:def generate_parameters(self, parameter_id): logger.debug('acquiring lock for param {}'.format(parameter_id)) self.thread_lock.acquire() logger.debug('lock for current thread acquired') if not self.population: logger.debug...
[ "Returns a set of trial graph config, as a serializable object.\n An example configuration:\n ```json\n {\n \"shared_id\": [\n \"4a11b2ef9cb7211590dfe81039b27670\",\n \"370af04de24985e5ea5b3d72b12644c9\",\n \"11f646e9f650f5f3fedc12b6349ec6...
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 _update_data(self, trial_job_id, trial_history): if trial_job_id not in self.running_history: self.running_history[trial_job_id] = [] self.running_history[trial_job_id].extend(trial_history[len(self.running_history[trial_job_id]):])
[ "update data\n\n Parameters\n ----------\n trial_job_id: int\n trial job id\n trial_history: list\n The history performance matrix of each trial\n " ]
Please provide a description of the function:def trial_end(self, trial_job_id, success): if trial_job_id in self.running_history: if success: cnt = 0 history_sum = 0 self.completed_avg_history[trial_job_id] = [] for each in sel...
[ "trial_end\n \n Parameters\n ----------\n trial_job_id: int\n trial job id\n success: bool\n True if succssfully finish the experiment, False otherwise\n " ]
Please provide a description of the function:def assess_trial(self, trial_job_id, trial_history): curr_step = len(trial_history) if curr_step < self.start_step: return AssessResult.Good try: num_trial_history = [float(ele) for ele in trial_history] excep...
[ "assess_trial\n \n Parameters\n ----------\n trial_job_id: int\n trial job id\n trial_history: list\n The history performance matrix of each trial\n\n Returns\n -------\n bool\n AssessResult.Good or AssessResult.Bad\n\n ...
Please provide a description of the function: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 Exc...
[]
Please provide a description of the function: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 = hd...
[]
Please provide a description of the function: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 fo...
[]
Please provide a description of the function: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 E...
[]
Please provide a description of the function: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 = StandardScal...
[]
Please provide a description of the function:def get_model(PARAMS): '''Get model according to parameters''' model_dict = { 'LinearRegression': LinearRegression(), 'SVR': SVR(), 'KNeighborsRegressor': KNeighborsRegressor(), 'DecisionTreeRegressor': DecisionTreeRegressor() } ...
[]
Please provide a description of the function: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)
[]
Please provide a description of the function:def add_skip_connection(self, u, v, connection_type): if connection_type not in [self.CONCAT_CONNECT, self.ADD_CONNECT]: raise ValueError( "connection_type should be NetworkDescriptor.CONCAT_CONNECT " "or NetworkDe...
[ " Add a skip-connection to the descriptor.\n Args:\n u: Number of convolutional layers before the starting point.\n v: Number of convolutional layers before the ending point.\n connection_type: Must be either CONCAT_CONNECT or ADD_CONNECT.\n " ]
Please provide a description of the function: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": se...
[]
Please provide a description of the function:def add_layer(self, layer, input_node_id): if isinstance(input_node_id, Iterable): layer.input = list(map(lambda x: self.node_list[x], input_node_id)) output_node_id = self._add_node(Node(layer.output_shape)) for node_id i...
[ "Add a layer to the Graph.\n Args:\n layer: An instance of the subclasses of StubLayer in layers.py.\n input_node_id: An integer. The ID of the input node of the layer.\n Returns:\n output_node_id: An integer. The ID of the output node of the layer.\n " ]
Please provide a description of the function:def _add_node(self, node): node_id = len(self.node_list) self.node_to_id[node] = node_id self.node_list.append(node) self.adj_list[node_id] = [] self.reverse_adj_list[node_id] = [] return node_id
[ "Add a new node to node_list and give the node an ID.\n Args:\n node: An instance of Node.\n Returns:\n node_id: An integer.\n " ]
Please provide a description of the function:def _add_edge(self, layer, input_id, output_id): 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_id_to_input_node_ids[layer_id]...
[ "Add a new layer to the graph. The nodes should be created in advance." ]
Please provide a description of the function:def _redirect_edge(self, u_id, v_id, new_v_id): layer_id = None for index, edge_tuple in enumerate(self.adj_list[u_id]): if edge_tuple[0] == v_id: layer_id = edge_tuple[1] self.adj_list[u_id][index] = (new_...
[ "Redirect the layer to a new node.\n Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`\n while keeping all other property of the edge the same.\n " ]
Please provide a description of the function:def _replace_layer(self, layer_id, 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_i...
[ "Replace the layer with a new layer." ]
Please provide a description of the function:def topological_order(self): 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]: in_degree[v] += 1 for i...
[ "Return the topological order of the node IDs from the input node to the output node." ]
Please provide a description of the function:def _get_pooling_layers(self, start_node_id, end_node_id): 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_list: layer ...
[ "Given two node IDs, return all the pooling layers between them." ]
Please provide a description of the function:def _depth_first_search(self, target_id, layer_id_list, node_list): assert len(node_list) <= self.n_nodes u = node_list[-1] if u == target_id: return True for v, layer_id in self.adj_list[u]: layer_id_list.app...
[ "Search for all the layers and nodes down the path.\n A recursive function to search all the layers and nodes between the node in the node_list\n and the node with target_id." ]
Please provide a description of the function:def _search(self, u, start_dim, total_dim, n_add): if (u, start_dim, total_dim, n_add) in self.vis: return self.vis[(u, start_dim, total_dim, n_add)] = True for v, layer_id in self.adj_list[u]: layer = self.layer_list[...
[ "Search the graph for all the layers to be widened caused by an operation.\n It is an recursive function with duplication check to avoid deadlock.\n It searches from a starting node u until the corresponding layers has been widened.\n Args:\n u: The starting node ID.\n sta...
Please provide a description of the function:def to_deeper_model(self, target_id, new_layer): self.operation_history.append(("to_deeper_model", target_id, new_layer)) input_id = self.layer_id_to_input_node_ids[target_id][0] output_id = self.layer_id_to_output_node_ids[target_id][0] ...
[ "Insert a relu-conv-bn block after the target block.\n Args:\n target_id: A convolutional layer ID. The new block should be inserted after the block.\n new_layer: An instance of StubLayer subclasses.\n " ]
Please provide a description of the function:def to_wider_model(self, pre_layer_id, n_add): self.operation_history.append(("to_wider_model", pre_layer_id, n_add)) pre_layer = self.layer_list[pre_layer_id] output_id = self.layer_id_to_output_node_ids[pre_layer_id][0] dim = layer_...
[ "Widen the last dimension of the output of the pre_layer.\n Args:\n pre_layer_id: The ID of a convolutional layer or dense layer.\n n_add: The number of dimensions to add.\n " ]
Please provide a description of the function:def _insert_new_layers(self, new_layers, start_node_id, end_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 = self.add_layer(l...
[ "Insert the new_layers after the node with start_node_id." ]
Please provide a description of the function:def to_add_skip_model(self, start_id, end_id): self.operation_history.append(("to_add_skip_model", start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] st...
[ "Add a weighted add skip-connection from after start node to end node.\n Args:\n start_id: The convolutional layer ID, after which to start the skip-connection.\n end_id: The convolutional layer ID, after which to end the skip-connection.\n " ]
Please provide a description of the function:def to_concat_skip_model(self, start_id, end_id): self.operation_history.append(("to_concat_skip_model", start_id, end_id)) filters_end = self.layer_list[end_id].output.shape[-1] filters_start = self.layer_list[start_id].output.shape[-1] ...
[ "Add a weighted add concatenate connection from after start node to end node.\n Args:\n start_id: The convolutional layer ID, after which to start the skip-connection.\n end_id: The convolutional layer ID, after which to end the skip-connection.\n " ]
Please provide a description of the function:def extract_descriptor(self): 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() for u in main_chain: ...
[ "Extract the the description of the Graph as an instance of NetworkDescriptor." ]
Please provide a description of the function:def clear_weights(self): ''' clear weights of the graph ''' self.weighted = False for layer in self.layer_list: layer.weights = None
[]
Please provide a description of the function:def get_main_chain_layers(self): 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(layer_id...
[ "Return a list of layer IDs in the main chain." ]
Please provide a description of the function:def get_main_chain(self): 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): fo...
[ "Returns the main chain node ID list." ]
Please provide a description of the function:def run(self): _logger.info('Start dispatcher') if dispatcher_env_vars.NNI_MODE == 'resume': self.load_checkpoint() while True: command, data = receive() if data: data = json_tricks.loads(d...
[ "Run the tuner.\n This function will never return unless raise.\n " ]
Please provide a description of the function:def command_queue_worker(self, command_queue): while True: try: # set timeout to ensure self.stopping is checked periodically command, data = command_queue.get(timeout=3) try: se...
[ "Process commands in command queues.\n " ]
Please provide a description of the function:def enqueue_command(self, command, data): if command == CommandType.TrialEnd or (command == CommandType.ReportMetricData and data['type'] == 'PERIODICAL'): self.assessor_command_queue.put((command, data)) else: self.default_co...
[ "Enqueue command into command queues\n " ]
Please provide a description of the function:def process_command_thread(self, request): command, data = request if multi_thread_enabled(): try: self.process_command(command, data) except Exception as e: _logger.exception(str(e)) ...
[ "Worker thread to process a command.\n " ]
Please provide a description of the function: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 i...
[]
Please provide a description of the function: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)] ...
[]
Please provide a description of the function: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) ...
[]
Please provide a description of the function: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 = [] fo...
[]
Please provide a description of the function: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),...
[]
Please provide a description of the function: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: ...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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(g...
[]
Please provide a description of the function: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'...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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....
[]
Please provide a description of the function: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, ...
[]
Please provide a description of the function: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
[]
Please provide a description of the function: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))
[]
Please provide a description of the function: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) *...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function: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)) ...
[]
Please provide a description of the function:def trial_end(self, trial_job_id, success): if success: if self.set_best_performance: self.completed_best_performance = max(self.completed_best_performance, self.trial_history[-1]) else: self.set_best_p...
[ "update the best performance of completed trial job\n \n Parameters\n ----------\n trial_job_id: int\n trial job id\n success: bool\n True if succssfully finish the experiment, False otherwise\n " ]
Please provide a description of the function:def assess_trial(self, trial_job_id, trial_history): self.trial_job_id = trial_job_id self.trial_history = trial_history if not self.set_best_performance: return AssessResult.Good curr_step = len(trial_history) if ...
[ "assess whether a trial should be early stop by curve fitting algorithm\n\n Parameters\n ----------\n trial_job_id: int\n trial job id\n trial_history: list\n The history performance matrix of each trial\n\n Returns\n -------\n bool\n ...
Please provide a description of the function:def handle_initialize(self, data): ''' data is search space ''' self.tuner.update_search_space(data) send(CommandType.Initialized, '') return True
[]
Please provide a description of the function:def generate_parameters(self, parameter_id): if not self.history: self.init_search() new_father_id = None generated_graph = None if not self.training_queue: new_father_id, generated_graph = self.generate() ...
[ "\n Returns a set of trial neural architecture, as a serializable object.\n\n Parameters\n ----------\n parameter_id : int\n " ]
Please provide a description of the function:def receive_trial_result(self, parameter_id, parameters, value): reward = extract_scalar_reward(value) if parameter_id not in self.total_data: raise RuntimeError("Received parameter_id not in total_data.") (_, father_id, model_i...
[ " Record an observation of the objective function.\n \n Parameters\n ----------\n parameter_id : int\n parameters : dict\n value : dict/float\n if value is dict, it should have \"default\" key.\n " ]
Please provide a description of the function:def init_search(self): if self.verbose: logger.info("Initializing search.") for generator in self.generators: graph = generator(self.n_classes, self.input_shape).generate( self.default_model_len, self.default_m...
[ "Call the generators to generate the initial architectures for the search." ]
Please provide a description of the function:def generate(self): generated_graph, new_father_id = self.bo.generate(self.descriptors) if new_father_id is None: new_father_id = 0 generated_graph = self.generators[0]( self.n_classes, self.input_shape ...
[ "Generate the next neural architecture.\n\n Returns\n -------\n other_info: any object\n Anything to be saved in the training queue together with the architecture.\n generated_graph: Graph\n An instance of Graph.\n " ]
Please provide a description of the function:def update(self, other_info, graph, metric_value, model_id): father_id = other_info self.bo.fit([graph.extract_descriptor()], [metric_value]) self.bo.add_child(father_id, model_id)
[ " Update the controller with evaluation result of a neural architecture.\n\n Parameters\n ----------\n other_info: any object\n In our case it is the father ID in the search tree.\n graph: Graph\n An instance of Graph. The trained neural architecture.\n metri...
Please provide a description of the function:def add_model(self, metric_value, model_id): if self.verbose: logger.info("Saving model.") # Update best_model text file ret = {"model_id": model_id, "metric_value": metric_value} self.history.append(ret) if model...
[ " Add model to the history, x_queue and y_queue\n\n Parameters\n ----------\n metric_value : float\n graph : dict\n model_id : int\n\n Returns\n -------\n model : dict\n " ]