Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def url_for(self, *args: str, **kwargs: str) -> URL: return self._resource.url_for(*args, **kwargs)
[ "Construct url for route with additional params." ]
Please provide a description of the function:def add_static(self, prefix: str, path: PathLike, *, name: Optional[str]=None, expect_handler: Optional[_ExpectHandler]=None, chunk_size: int=256 * 1024, show_index: bool=False, follow_symlinks: bool...
[ "Add static files view.\n\n prefix - url prefix\n path - folder with files\n\n " ]
Please provide a description of the function:def add_head(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs)
[ "\n Shortcut for add_route with method HEAD\n " ]
Please provide a description of the function:def add_options(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs)
[ "\n Shortcut for add_route with method OPTIONS\n " ]
Please provide a description of the function:def add_get(self, path: str, handler: _WebHandler, *, name: Optional[str]=None, allow_head: bool=True, **kwargs: Any) -> AbstractRoute: resource = self.add_resource(path, name=name) if allow_head: resource....
[ "\n Shortcut for add_route with method GET, if allow_head is true another\n route is added allowing head requests to the same endpoint\n " ]
Please provide a description of the function:def add_post(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_POST, path, handler, **kwargs)
[ "\n Shortcut for add_route with method POST\n " ]
Please provide a description of the function:def add_put(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_PUT, path, handler, **kwargs)
[ "\n Shortcut for add_route with method PUT\n " ]
Please provide a description of the function:def add_patch(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs)
[ "\n Shortcut for add_route with method PATCH\n " ]
Please provide a description of the function:def add_delete(self, path: str, handler: _WebHandler, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs)
[ "\n Shortcut for add_route with method DELETE\n " ]
Please provide a description of the function:def add_view(self, path: str, handler: AbstractView, **kwargs: Any) -> AbstractRoute: return self.add_route(hdrs.METH_ANY, path, handler, **kwargs)
[ "\n Shortcut for add_route with ANY methods for a class-based view\n " ]
Please provide a description of the function:def add_routes(self, routes: Iterable[AbstractRouteDef]) -> None: for route_def in routes: route_def.register(self)
[ "Append routes to route table.\n\n Parameter should be a sequence of RouteDef objects.\n " ]
Please provide a description of the function:def parse_headers( self, lines: List[bytes] ) -> Tuple['CIMultiDictProxy[str]', RawHeaders, Optional[bool], Optional[str], bool, bool]: headers, raw_header...
[ "Parses RFC 5322 headers from a stream.\n\n Line continuations are supported. Returns list of header name\n and value pairs. Header name is in upper case.\n " ]
Please provide a description of the function:def get_extra_info(self, name: str, default: Any=None) -> Any: conn = self._response.connection if conn is None: return default transport = conn.transport if transport is None: return default return tra...
[ "extra info from connection transport" ]
Please provide a description of the function:def user_agent(style=None) -> _UserAgent: global useragent if (not useragent) and style: useragent = UserAgent() return useragent[style] if style else DEFAULT_USER_AGENT
[ "Returns an apparently legit user-agent, if not requested one of a specific\n style. Defaults to a Chrome-style User-Agent.\n " ]
Please provide a description of the function:def raw_html(self) -> _RawHTML: if self._html: return self._html else: return etree.tostring(self.element, encoding='unicode').strip().encode(self.encoding)
[ "Bytes representation of the HTML content.\n (`learn more <http://www.diveintopython3.net/strings.html>`_).\n " ]
Please provide a description of the function:def html(self) -> _BaseHTML: if self._html: return self.raw_html.decode(self.encoding, errors='replace') else: return etree.tostring(self.element, encoding='unicode').strip()
[ "Unicode representation of the HTML content\n (`learn more <http://www.diveintopython3.net/strings.html>`_).\n " ]
Please provide a description of the function:def encoding(self) -> _Encoding: if self._encoding: return self._encoding # Scan meta tags for charset. if self._html: self._encoding = html_to_unicode(self.default_encoding, self._html)[0] # Fall back to ...
[ "The encoding string to be used, extracted from the HTML and\n :class:`HTMLResponse <HTMLResponse>` headers.\n " ]
Please provide a description of the function:def pq(self) -> PyQuery: if self._pq is None: self._pq = PyQuery(self.lxml) return self._pq
[ "`PyQuery <https://pythonhosted.org/pyquery/>`_ representation\n of the :class:`Element <Element>` or :class:`HTML <HTML>`.\n " ]
Please provide a description of the function:def lxml(self) -> HtmlElement: if self._lxml is None: try: self._lxml = soup_parse(self.html, features='html.parser') except ValueError: self._lxml = lxml.html.fromstring(self.raw_html) return ...
[ "`lxml <http://lxml.de>`_ representation of the\n :class:`Element <Element>` or :class:`HTML <HTML>`.\n " ]
Please provide a description of the function:def find(self, selector: str = "*", *, containing: _Containing = None, clean: bool = False, first: bool = False, _encoding: str = None) -> _Find: # Convert a single containing into a list. if isinstance(containing, str): containing = [co...
[ "Given a CSS Selector, returns a list of\n :class:`Element <Element>` objects or a single one.\n\n :param selector: CSS Selector to use.\n :param clean: Whether or not to sanitize the found HTML of ``<script>`` and ``<style>`` tags.\n :param containing: If specified, only return elements...
Please provide a description of the function:def xpath(self, selector: str, *, clean: bool = False, first: bool = False, _encoding: str = None) -> _XPath: selected = self.lxml.xpath(selector) elements = [ Element(element=selection, url=self.url, default_encoding=_encoding or self.e...
[ "Given an XPath selector, returns a list of\n :class:`Element <Element>` objects or a single one.\n\n :param selector: XPath Selector to use.\n :param clean: Whether or not to sanitize the found HTML of ``<script>`` and ``<style>`` tags.\n :param first: Whether or not to return just the ...
Please provide a description of the function:def search_all(self, template: str) -> _Result: return [r for r in findall(template, self.html)]
[ "Search the :class:`Element <Element>` (multiple times) for the given parse\n template.\n\n :param template: The Parse template to use.\n " ]
Please provide a description of the function:def links(self) -> _Links: def gen(): for link in self.find('a'): try: href = link.attrs['href'].strip() if href and not (href.startswith('#') and self.skip_anchors) and not href.startswit...
[ "All found links on page, in as–is form." ]
Please provide a description of the function:def _make_absolute(self, link): # Parse the link with stdlib. parsed = urlparse(link)._asdict() # If link is relative, then join it with base_url. if not parsed['netloc']: return urljoin(self.base_url, link) # L...
[ "Makes a given link absolute." ]
Please provide a description of the function:def absolute_links(self) -> _Links: def gen(): for link in self.links: yield self._make_absolute(link) return set(gen())
[ "All found links on page, in absolute form\n (`learn more <https://www.navegabem.com/absolute-or-relative-links.html>`_).\n " ]
Please provide a description of the function:def base_url(self) -> _URL: # Support for <base> tag. base = self.find('base', first=True) if base: result = base.attrs.get('href', '').strip() if result: return result # Parse the url to sepa...
[ "The base URL for the page. Supports the ``<base>`` tag\n (`learn more <https://www.w3schools.com/tags/tag_base.asp>`_)." ]
Please provide a description of the function:def attrs(self) -> _Attrs: if self._attrs is None: self._attrs = {k: v for k, v in self.element.items()} # Split class and rel up, as there are ussually many of them: for attr in ['class', 'rel']: if attr ...
[ "Returns a dictionary of the attributes of the :class:`Element <Element>`\n (`learn more <https://www.w3schools.com/tags/ref_attributes.asp>`_).\n " ]
Please provide a description of the function:def next(self, fetch: bool = False, next_symbol: _NextSymbol = DEFAULT_NEXT_SYMBOL) -> _Next: def get_next(): candidates = self.find('a', containing=next_symbol) for candidate in candidates: if candidate.attrs.get('h...
[ "Attempts to find the next page, if there is one. If ``fetch``\n is ``True`` (default), returns :class:`HTML <HTML>` object of\n next page. If ``fetch`` is ``False``, simply returns the next URL.\n\n " ]
Please provide a description of the function:async def _async_render(self, *, url: str, script: str = None, scrolldown, sleep: int, wait: float, reload, content: Optional[str], timeout: Union[float, int], keep_page: bool): try: page = await self.browser.newPage() # Wait before ...
[ " Handle page creation and js rendering. Internal use for render/arender methods. " ]
Please provide a description of the function:def render(self, retries: int = 8, script: str = None, wait: float = 0.2, scrolldown=False, sleep: int = 0, reload: bool = True, timeout: Union[float, int] = 8.0, keep_page: bool = False): self.browser = self.session.browser # Automatically create a event ...
[ "Reloads the response in Chromium, and replaces HTML content\n with an updated version, with JavaScript executed.\n\n :param retries: The number of times to retry loading the page in Chromium.\n :param script: JavaScript to execute upon page load (optional).\n :param wait: The number of ...
Please provide a description of the function:def response_hook(self, response, **kwargs) -> HTMLResponse: if not response.encoding: response.encoding = DEFAULT_ENCODING return HTMLResponse._from_response(response, self)
[ " Change response enconding and replace it by a HTMLResponse. " ]
Please provide a description of the function:def close(self): if hasattr(self, "_browser"): self.loop.run_until_complete(self._browser.close()) super().close()
[ " If a browser was created close it first. " ]
Please provide a description of the function:def request(self, *args, **kwargs): func = partial(super().request, *args, **kwargs) return self.loop.run_in_executor(self.thread_pool, func)
[ " Partial original request func and run it in a thread. " ]
Please provide a description of the function:def run(self, *coros): tasks = [ asyncio.ensure_future(coro()) for coro in coros ] done, _ = self.loop.run_until_complete(asyncio.wait(tasks)) return [t.result() for t in done]
[ " Pass in all the coroutines you want to run, it will wrap each one\n in a task, run it and wait for the result. Return a list with all\n results, this is returned in the same order coros are passed in. " ]
Please provide a description of the function:def add_depth_channel(img_tensor, pad_mode): ''' img_tensor: N, C, H, W ''' img_tensor[:, 1] = get_depth_tensor(pad_mode) img_tensor[:, 2] = img_tensor[:, 0] * get_depth_tensor(pad_mode)
[]
Please provide a description of the function:def get_pre_compute(self, s): ''' :param s: [src_sequence, batch_size, src_dim] :return: [src_sequence, batch_size. hidden_dim] ''' hidden_dim = self.hidden_dim src_dim = s.get_shape().as_list()[-1] assert src_dim is no...
[]
Please provide a description of the function:def get_prob(self, src, tgt, mask, pre_compute, return_logits=False): ''' :param s: [src_sequence_length, batch_size, src_dim] :param h: [batch_size, tgt_dim] or [tgt_sequence_length, batch_size, tgt_dim] :param mask: [src_sequence_length, bat...
[]
Please provide a description of the function:def get_att(self, s, prob): ''' :param s: [src_sequence_length, batch_size, src_dim] :param prob: [src_sequence_length, batch_size]\ or [tgt_sequence_length, src_sequence_length, batch_size] :return: [batch_size, src_dim] or [tgt_s...
[]
Please provide a description of the function:def shape(tensor): ''' Get shape of variable. Return type is tuple. ''' temp_s = tensor.get_shape() return tuple([temp_s[i].value for i in range(0, len(temp_s))])
[]
Please provide a description of the function:def get_variable(name, temp_s): ''' Get variable by name. ''' return tf.Variable(tf.zeros(temp_s), name=name)
[]
Please provide a description of the function:def dropout(tensor, drop_prob, is_training): ''' Dropout except test. ''' if not is_training: return tensor return tf.nn.dropout(tensor, 1.0 - drop_prob)
[]
Please provide a description of the function:def get_elapsed(self, restart=True): ''' Calculate time span. ''' end = time.time() span = end - self.__start if restart: self.__start = end return span
[]
Please provide a description of the function:def do_tta_predict(args, model, ckp_path, tta_num=4): ''' return 18000x128x128 np array ''' model.eval() preds = [] meta = None # i is tta index, 0: no change, 1: horizon flip, 2: vertical flip, 3: do both for flip_index in range(tta_num): ...
[]
Please provide a description of the function:def partition_dataset(): dataset = datasets.MNIST( './data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, )) ])) size = ...
[ " Partitioning MNIST " ]
Please provide a description of the function:def average_gradients(model): size = float(dist.get_world_size()) for param in model.parameters(): dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM, group=0) param.grad.data /= size
[ " Gradient averaging. " ]
Please provide a description of the function:def run(params): rank = dist.get_rank() torch.manual_seed(1234) train_set, bsz = partition_dataset() model = Net() model = model optimizer = optim.SGD(model.parameters(), lr=params['learning_rate'], momentum=params['momentum']) num_batches =...
[ " Distributed Synchronous SGD Example " ]
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['type'], layer['input'], layer['output'], layer['size']) layer_info.is_delete = layer['is_delete'] layers.appen...
[]
Please provide a description of the function:def set_size(self, graph_id, size): ''' Set size. ''' if self.graph_type == LayerType.attention.value: if self.input[0] == graph_id: self.size = size if self.graph_type == LayerType.rnn.value: se...
[]
Please provide a description of the function:def clear_size(self): ''' Clear size ''' if self.graph_type == LayerType.attention.value or \ LayerType.rnn.value or LayerType.self_attention.value: self.size = None
[]
Please provide a description of the function:def is_topology(self, layers=None): ''' valid the topology ''' if layers is None: layers = self.layers layers_nodle = [] result = [] for i, layer in enumerate(layers): if layer.is_delete is False...
[]
Please provide a description of the function:def is_legal(self, layers=None): ''' Judge whether is legal for layers ''' if layers is None: layers = self.layers for layer in layers: if layer.is_delete is False: if len(layer.input) != layer....
[]
Please provide a description of the function:def mutation(self, only_add=False): ''' Mutation for a graph ''' types = [] if self.layer_num() < self.max_layer_num: types.append(0) types.append(1) if self.layer_num() > 5 and only_add is False: ...
[]
Please provide a description of the function:def _main_cli(self): self.logger.info("SMAC call: %s" % (" ".join(sys.argv))) cmd_reader = CMDReader() args, _ = cmd_reader.read_cmd() root_logger = logging.getLogger() root_logger.setLevel(args.verbose_level) logger...
[ "Main function of SMAC for CLI interface\n \n Returns\n -------\n instance\n optimizer\n " ]
Please provide a description of the function:def update_search_space(self, search_space): if not self.update_ss_done: self.categorical_dict = generate_scenario(search_space) if self.categorical_dict is None: raise RuntimeError('categorical dict is not correctly r...
[ "TODO: this is urgly, we put all the initialization work in this method, because initialization relies\n on search space, also because update_search_space is called at the beginning.\n NOTE: updating search space is not supported.\n\n Parameters\n ----------\n search_space:\n ...
Please provide a description of the function:def receive_trial_result(self, parameter_id, parameters, value): reward = extract_scalar_reward(value) if self.optimize_mode is OptimizeMode.Maximize: reward = -reward if parameter_id not in self.total_data: raise Run...
[ "receive_trial_result\n \n Parameters\n ----------\n parameter_id: int\n parameter id\n parameters:\n parameters\n value:\n value\n \n Raises\n ------\n RuntimeError\n Received parameter id not in total_...
Please provide a description of the function:def convert_loguniform_categorical(self, challenger_dict): converted_dict = {} for key, value in challenger_dict.items(): # convert to loguniform if key in self.loguniform_key: converted_dict[key] = np.exp(chal...
[ "Convert the values of type `loguniform` back to their initial range\n Also, we convert categorical:\n categorical values in search space are changed to list of numbers before,\n those original values will be changed back in this function\n \n Parameters\n ----------\n ...
Please provide a description of the function:def generate_parameters(self, parameter_id): if self.first_one: init_challenger = self.smbo_solver.nni_smac_start() self.total_data[parameter_id] = init_challenger return self.convert_loguniform_categorical(init_challenger...
[ "generate one instance of hyperparameters\n \n Parameters\n ----------\n parameter_id: int\n parameter id\n \n Returns\n -------\n list\n new generated parameters\n " ]
Please provide a description of the function:def generate_multiple_parameters(self, parameter_id_list): if self.first_one: params = [] for one_id in parameter_id_list: init_challenger = self.smbo_solver.nni_smac_start() self.total_data[one_id] = i...
[ "generate mutiple instances of hyperparameters\n \n Parameters\n ----------\n parameter_id_list: list\n list of parameter id\n \n Returns\n -------\n list\n list of new generated parameters\n " ]
Please provide a description of the function:def lovasz_grad(gt_sorted): p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union = gts + (1 - gt_sorted).float().cumsum(0) jaccard = 1. - intersection / union if p > 1: # cover 1-pixel case jacca...
[ "\n Computes gradient of the Lovasz extension w.r.t sorted errors\n See Alg. 1 in paper\n " ]
Please provide a description of the function:def iou_binary(preds, labels, EMPTY=1., ignore=None, per_image=True): if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label in zip(preds, labels): intersection = ((label == 1) & (pred == 1)).sum() union = ((l...
[ "\n IoU for foreground class\n binary: 1 foreground, 0 background\n " ]
Please provide a description of the function:def iou(preds, labels, C, EMPTY=1., ignore=None, per_image=False): if not per_image: preds, labels = (preds,), (labels,) ious = [] for pred, label in zip(preds, labels): iou = [] for i in range(C): if i != ignore: # Th...
[ "\n Array of IoU for each (non ignored) class\n " ]
Please provide a description of the function:def lovasz_hinge(logits, labels, per_image=True, ignore=None): if per_image: loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore)) for log, lab in zip(logits, labels)) else: lo...
[ "\n Binary Lovasz hinge loss\n logits: [B, H, W] Variable, logits at each pixel (between -\\infty and +\\infty)\n labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)\n per_image: compute the loss per image instead of per batch\n ignore: void class id\n " ]
Please provide a description of the function:def lovasz_hinge_flat(logits, labels): if len(labels) == 0: # only void pixels, the gradients should be 0 return logits.sum() * 0. signs = 2. * labels.float() - 1. errors = (1. - logits * Variable(signs)) errors_sorted, perm = torch.sort(...
[ "\n Binary Lovasz hinge loss\n logits: [P] Variable, logits at each prediction (between -\\infty and +\\infty)\n labels: [P] Tensor, binary ground truth labels (0 or 1)\n ignore: label to ignore\n " ]
Please provide a description of the function:def flatten_binary_scores(scores, labels, ignore=None): scores = scores.view(-1) labels = labels.view(-1) if ignore is None: return scores, labels valid = (labels != ignore) vscores = scores[valid] vlabels = labels[valid] return vscor...
[ "\n Flattens predictions in the batch (binary case)\n Remove labels equal to 'ignore'\n " ]
Please provide a description of the function:def binary_xloss(logits, labels, ignore=None): logits, labels = flatten_binary_scores(logits, labels, ignore) loss = StableBCELoss()(logits, Variable(labels.float())) return loss
[ "\n Binary Cross entropy loss\n logits: [B, H, W] Variable, logits at each pixel (between -\\infty and +\\infty)\n labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)\n ignore: void class id\n " ]
Please provide a description of the function:def lovasz_softmax(probas, labels, only_present=False, per_image=False, ignore=None): if per_image: loss = mean(lovasz_softmax_flat(*flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore), only_present=only_present) for prob, l...
[ "\n Multi-class Lovasz-Softmax loss\n probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1)\n labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)\n only_present: average only on classes present in ground truth\n per_image: compute the loss per...
Please provide a description of the function:def lovasz_softmax_flat(probas, labels, only_present=False): C = probas.size(1) losses = [] for c in range(C): fg = (labels == c).float() # foreground for class c if only_present and fg.sum() == 0: continue errors = (Varia...
[ "\n Multi-class Lovasz-Softmax loss\n probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)\n labels: [P] Tensor, ground truth labels (between 0 and C - 1)\n only_present: average only on classes present in ground truth\n " ]
Please provide a description of the function:def flatten_probas(probas, labels, ignore=None): B, C, H, W = probas.size() probas = probas.permute(0, 2, 3, 1).contiguous().view(-1, C) # B * H * W, C = P, C labels = labels.view(-1) if ignore is None: return probas, labels valid = (labels ...
[ "\n Flattens predictions in the batch\n " ]
Please provide a description of the function:def xloss(logits, labels, ignore=None): return F.cross_entropy(logits, Variable(labels), ignore_index=255)
[ "\n Cross entropy loss\n " ]
Please provide a description of the function:def mean(l, ignore_nan=False, empty=0): l = iter(l) if ignore_nan: l = ifilterfalse(np.isnan, l) try: n = 1 acc = next(l) except StopIteration: if empty == 'raise': raise ValueError('Empty mean') return...
[ "\n nanmean compatible with generators.\n " ]
Please provide a description of the function:def main_loop(args): '''main loop logic for trial keeper''' if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) stdout_file = open(STDOUT_FULL_PATH, 'a+') stderr_file = open(STDERR_FULL_PATH, 'a+') trial_keeper_syslogger = RemoteLogger(...
[]
Please provide a description of the function:def forward(self, x): '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]''' N,C,H,W = x.size() g = self.groups return x.view(N,g,C/g,H,W).permute(0,2,1,3,4).contiguous().view(N,C,H,W)
[]
Please provide a description of the function:def load_embedding(path): ''' return embedding for a specific file by given file path. ''' EMBEDDING_DIM = 300 embedding_dict = {} with open(path, 'r', encoding='utf-8') as file: pairs = [line.strip('\r\n').split() for line in file.readlines()...
[]
Please provide a description of the function:def generate_predict_json(position1_result, position2_result, ids, passage_tokens): ''' Generate json by prediction. ''' predict_len = len(position1_result) logger.debug('total prediction num is %s', str(predict_len)) answers = {} for i in range(...
[]
Please provide a description of the function:def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False): ''' Generate data ''' global root_path qp_pairs = data.load_from_file(path=path, is_training=is_training) tokenized_sent = 0 # qp_pairs = qp_pairs[:1000]1 for qp_pair ...
[]
Please provide a description of the function:def f1_score(prediction, ground_truth): ''' Calculate the f1 score. ''' prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = Counter(prediction_tokens) & Counter(ground_truth_to...
[]
Please provide a description of the function:def _evaluate(dataset, predictions): ''' Evaluate function. ''' f1_result = exact_match = total = 0 count = 0 for article in dataset: for paragraph in article['paragraphs']: for qa_pair in paragraph['qas']: total +=...
[]
Please provide a description of the function:def evaluate(data_file, pred_file): ''' Evaluate. ''' expected_version = '1.1' with open(data_file) as dataset_file: dataset_json = json.load(dataset_file) if dataset_json['version'] != expected_version: print('Evaluation expec...
[]
Please provide a description of the function:def evaluate_with_predictions(data_file, predictions): ''' Evalutate with predictions/ ''' expected_version = '1.1' with open(data_file) as dataset_file: dataset_json = json.load(dataset_file) if dataset_json['version'] != expected_version...
[]
Please provide a description of the function:def send(command, data): global _lock try: _lock.acquire() data = data.encode('utf8') assert len(data) < 1000000, 'Command too long' msg = b'%b%06d%b' % (command.value, len(data), data) logging.getLogger(__name__).debug('S...
[ "Send command to Training Service.\n command: CommandType object.\n data: string payload.\n " ]
Please provide a description of the function:def receive(): header = _in_file.read(8) logging.getLogger(__name__).debug('Received command, header: [%s]' % header) if header is None or len(header) < 8: # Pipe EOF encountered logging.getLogger(__name__).debug('Pipe EOF encountered') ...
[ "Receive a command from Training Service.\n Returns a tuple of command (CommandType) and payload (str)\n " ]
Please provide a description of the function:def json2space(in_x, name=ROOT): out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type _value = json2space(in_x[VALUE], name=name) if _t...
[ "\n Change json to search space in hyperopt.\n\n Parameters\n ----------\n in_x : dict/list/str/int/float\n The part of json.\n name : str\n name could be ROOT, TYPE, VALUE or INDEX.\n " ]
Please provide a description of the function:def json2parameter(in_x, parameter, name=ROOT): out_y = copy.deepcopy(in_x) if isinstance(in_x, dict): if TYPE in in_x.keys(): _type = in_x[TYPE] name = name + '-' + _type if _type == 'choice': _index =...
[ "\n Change json to parameters.\n " ]
Please provide a description of the function:def _add_index(in_x, parameter): if TYPE not in in_x: # if at the top level out_y = dict() for key, value in parameter.items(): out_y[key] = _add_index(in_x[key], value) return out_y elif isinstance(in_x, dict): value_...
[ "\n change parameters in NNI format to parameters in hyperopt format(This function also support nested dict.).\n For example, receive parameters like:\n {'dropout_rate': 0.8, 'conv_size': 3, 'hidden_size': 512}\n Will change to format in hyperopt, like:\n {'dropout_rate': 0.8, 'conv_size': {'...
Please provide a description of the function:def _split_index(params): if isinstance(params, list): return [params[0], _split_index(params[1])] elif isinstance(params, dict): if INDEX in params.keys(): return _split_index(params[VALUE]) result = dict() for key in...
[ "\n Delete index infromation from params\n " ]
Please provide a description of the function:def _choose_tuner(self, algorithm_name): if algorithm_name == 'tpe': return hp.tpe.suggest if algorithm_name == 'random_search': return hp.rand.suggest if algorithm_name == 'anneal': return hp.anneal.sugges...
[ "\n Parameters\n ----------\n algorithm_name : str\n algorithm_name includes \"tpe\", \"random_search\" and anneal\"\n " ]
Please provide a description of the function:def update_search_space(self, search_space): self.json = search_space search_space_instance = json2space(self.json) rstate = np.random.RandomState() trials = hp.Trials() domain = hp.Domain(None, search_space_instance, ...
[ "\n Update search space definition in tuner by search_space in parameters.\n\n Will called when first setup experiemnt or update search space in WebUI.\n\n Parameters\n ----------\n search_space : dict\n " ]
Please provide a description of the function:def generate_parameters(self, parameter_id): total_params = self.get_suggestion(random_search=False) # avoid generating same parameter with concurrent trials because hyperopt doesn't support parallel mode if total_params in self.total_data.va...
[ "\n Returns a set of trial (hyper-)parameters, as a serializable object.\n\n Parameters\n ----------\n parameter_id : int\n\n Returns\n -------\n params : dict\n " ]
Please provide a description of the function:def receive_trial_result(self, parameter_id, parameters, value): reward = extract_scalar_reward(value) # restore the paramsters contains '_index' if parameter_id not in self.total_data: raise RuntimeError('Received parameter_id no...
[ "\n 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 value is final metrics of the trial.\n " ]
Please provide a description of the function:def miscs_update_idxs_vals(self, miscs, idxs, vals, assert_all_vals_used=True, idxs_map=None): if idxs_map is None: idxs_map = {} assert set(idxs.keys()) == set(vals.keys()) ...
[ "\n Unpack the idxs-vals format into the list of dictionaries that is\n `misc`.\n\n Parameters\n ----------\n idxs_map : dict\n idxs_map is a dictionary of id->id mappings so that the misc['idxs'] can\n contain different numbers than the idxs argument.\n "...
Please provide a description of the function:def get_suggestion(self, random_search=False): rval = self.rval trials = rval.trials algorithm = rval.algo new_ids = rval.trials.new_trial_ids(1) rval.trials.refresh() random_state = rval.rstate.randint(2**31-1) ...
[ "get suggestion from hyperopt\n\n Parameters\n ----------\n random_search : bool\n flag to indicate random search or not (default: {False})\n\n Returns\n ----------\n total_params : dict\n parameter suggestion\n " ]
Please provide a description of the function:def import_data(self, data): _completed_num = 0 for trial_info in data: logger.info("Importing data, current processing progress %s / %s" %(_completed_num, len(data))) _completed_num += 1 if self.algorithm_name == ...
[ "Import additional data for tuning\n\n Parameters\n ----------\n data:\n a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'\n " ]
Please provide a description of the function:def next_hyperparameter_lowest_mu(fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_starting_points, minimize_constraints_fu...
[]
Please provide a description of the function:def _lowest_mu(x, fun_prediction, fun_prediction_args, x_bounds, x_types, minimize_constraints_fun): ''' Calculate the lowest mu ''' # This is only for step-wise optimization x = lib_data.match_val_type(x, x_bounds, x_types) mu = sys.m...
[]
Please provide a description of the function:def build_char_states(self, char_embed, is_training, reuse, char_ids, char_lengths): max_char_length = self.cfg.max_char_length inputs = dropout(tf.nn.embedding_lookup(char_embed, char_ids), self.cfg.dropout, is_training) ...
[ "Build char embedding network for the QA model." ]
Please provide a description of the function:def handle_report_metric_data(self, data): if data['type'] == 'FINAL': self._handle_final_metric_data(data) elif data['type'] == 'PERIODICAL': if self.assessor is not None: self._handle_intermediate_metric_data...
[ "\n data: a dict received from nni_manager, which contains:\n - 'parameter_id': id of the trial\n - 'value': metric value reported by nni.report_final_result()\n - 'type': report type, support {'FINAL', 'PERIODICAL'}\n " ]
Please provide a description of the function:def handle_trial_end(self, data): trial_job_id = data['trial_job_id'] _ended_trials.add(trial_job_id) if trial_job_id in _trial_history: _trial_history.pop(trial_job_id) if self.assessor is not None: se...
[ "\n data: it has three keys: trial_job_id, event, hyper_params\n - trial_job_id: the id generated by training service\n - event: the job's state\n - hyper_params: the hyperparameters generated and returned by tuner\n " ]
Please provide a description of the function:def _handle_final_metric_data(self, data): id_ = data['parameter_id'] value = data['value'] if id_ in _customized_parameter_ids: self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value) else: ...
[ "Call tuner to process final results\n " ]
Please provide a description of the function:def _handle_intermediate_metric_data(self, data): if data['type'] != 'PERIODICAL': return if self.assessor is None: return trial_job_id = data['trial_job_id'] if trial_job_id in _ended_trials: retu...
[ "Call assessor to process intermediate results\n " ]
Please provide a description of the function:def _earlystop_notify_tuner(self, data): _logger.debug('Early stop notify tuner data: [%s]', data) data['type'] = 'FINAL' if multi_thread_enabled(): self._handle_final_metric_data(data) else: self.enqueue_comma...
[ "Send last intermediate result as final result to tuner in case the\n trial is early stopped.\n " ]