text
stringlengths
81
112k
check input imdbs, make sure they have same classes def _check_classes(self): """ check input imdbs, make sure they have same classes """ try: self.classes = self.imdbs[0].classes self.num_classes = len(self.classes) except AttributeError: # f...
get total number of images, init indices Parameters ---------- shuffle : bool whether to shuffle the initial indices def _load_image_set_index(self, shuffle): """ get total number of images, init indices Parameters ---------- shuffle : bool ...
given index, find out sub-db and sub-index Parameters ---------- index : int index of a specific image Returns ---------- a tuple (sub-db, sub-index) def _locate_index(self, index): """ given index, find out sub-db and sub-index Par...
given image index, find out full path Parameters ---------- index: int index of a specific image Returns ---------- full path of this image def image_path_from_index(self, index): """ given image index, find out full path Parameters...
Callback to checkpoint Module to prefix every epoch. Parameters ---------- mod : subclass of BaseModule The module to checkpoint. prefix : str The file prefix for this checkpoint. period : int How many epochs to wait before checkpointing. Defaults to 1. save_optimizer_st...
A callback that saves a model checkpoint every few epochs. Each checkpoint is made up of a couple of binary files: a model description file and a parameters (weights and biases) file. The model description file is named `prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params ...
Callback to log the training evaluation result every period. Parameters ---------- period : int The number of batch to log the training evaluation metric. auto_reset : bool Reset the metric after each log. Returns ------- callback : function The callback function th...
install callback to executor. Supports installing to multiple exes. Parameters ---------- exe : mx.executor.Executor The Executor (returned by symbol.bind) to install to. def install(self, exe): """install callback to executor. Supports installing to multipl...
Start collecting stats for current batch. Call before calling forward. def tic(self): """Start collecting stats for current batch. Call before calling forward.""" if self.step % self.interval == 0: for exe in self.exes: for array in exe.arg_arrays: ...
End collecting for current batch and return results. Call after computation of current batch. Returns ------- res : list of def toc(self): """End collecting for current batch and return results. Call after computation of current batch. Returns ------- ...
End collecting and print results. def toc_print(self): """End collecting and print results.""" res = self.toc() for n, k, v in res: logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v))
make a random data iteration plan def make_data_iter_plan(self): "make a random data iteration plan" # truncate each bucket into multiple of batch-size bucket_n_batches = [] for i in range(len(self.data)): bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size)) ...
Expand the pending files in the current stage. Parameters ---------- x: str The file to expand. pending : str The list of pending files to expand. stage: str The current stage for file expansion, used for matching the prefix of files. def expand(x, pending, stage): "...
Dataset loader with preprocessing. def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'): """Dataset loader with preprocessing.""" train_dir = os.path.join(root, 'train') train_transform, val_transform = get_imagenet_transforms(data_shape, dtype) logging.info("Loadin...
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `pretrained_file_name`, use `mxnet.contrib.text.embedding.g...
Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `mxnet.contrib.text.embedding.create(embedding_name, pretrained_file_name)`. This method ret...
Load embedding vectors from the pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherw...
Sets the mapping between token indices and token embedding vectors. Parameters ---------- token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding` One or multiple pre-trained token embeddings to load. If it is a list of multiple embeddings, the...
Look up embedding vectors of tokens. Parameters ---------- tokens : str or list of strs A token or a list of tokens. lower_case_backup : bool, default False If False, each token in the original case will be looked up; if True, each token in the origi...
Updates embedding vectors for tokens. Parameters ---------- tokens : str or a list of strs A token or a list of tokens whose embedding vector are to be updated. new_vectors : mxnet.ndarray.NDArray An NDArray to be assigned to the embedding vectors of `tokens`. I...
Checks if a pre-trained token embedding file name is valid. Parameters ---------- pretrained_file_name : str The pre-trained token embedding file. def _check_pretrained_file_names(cls, pretrained_file_name): """Checks if a pre-trained token embedding file name is valid. ...
Calculate gradient def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None): """Calculate gradient""" exe.copy_params_from(params) exe.arg_dict['data'][:] = X if outgrad_f is None: exe.arg_dict[label_name][:] = Y exe.forward(is_train=True) exe.backward() ...
Generate the implementation of step HMC def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6): """Generate the implementation of step HMC""" init_params = {k: v.copyto(v.context) for k, v in exe_params.items()} end_params = {k: v.copyto(v.context) for k, v in...
Generate the implementation of HMC def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num, initializer=None, noise_precision=1 / 9.0, prior_precision=0.1, learning_rate=1E-6, L=10, dev=mx.gpu()): """Generate the implementation of HMC""" label_key = list(set(data_inputs.keys()) - set(['data'...
Generate the implementation of SGD def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num, lr=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None, minibatch_size=100, dev=mx.gpu()): """Generate the implementation of SGD""" if out_grad_f ...
Generate the implementation of SGLD def SGLD(sym, X, Y, X_test, Y_test, total_iter_num, data_inputs=None, learning_rate=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None, minibatch_size=100, thin_interval=100, burn_in_iter_num=1000, task...
Generate the implementation of DistilledSGLD def DistilledSGLD(teacher_sym, student_sym, teacher_data_inputs, student_data_inputs, X, Y, X_test, Y_test, total_iter_num, teacher_learning_rate, student_learning_rate, teacher_lr_scheduler=None, stude...
Get a list of architectures given our dockerfiles def get_platforms(path: str = get_dockerfiles_path()) -> List[str]: """Get a list of architectures given our dockerfiles""" dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*")) dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) files...
:return: docker tag to be used for the container def get_docker_tag(platform: str, registry: str) -> str: """:return: docker tag to be used for the container""" platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform) if not registry: registry = "mx...
Build a container for the given platform :param platform: Platform :param docker_binary: docker binary to use (docker/nvidia-docker) :param registry: Dockerhub registry name :param num_retries: Number of retries to build the docker image :param no_cache: pass no-cache to docker to rebuild the images...
Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag :return: Image id as string or None if tag does not exist def _get_local_image_id(docker_binary, docker_tag): """ Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag...
:return: ccache directory for the current platform def default_ccache_dir() -> str: """:return: ccache directory for the current platform""" # Share ccache across containers if 'CCACHE_DIR' in os.environ: ccache_dir = os.path.realpath(os.environ['CCACHE_DIR']) try: os.makedirs(c...
Run command in a container def container_run(platform: str, nvidia_runtime: bool, docker_registry: str, shared_memory_size: str, local_ccache_dir: str, command: List[str], cleanup: Cleanup, env...
Imports tagged container from the given docker registry def load_docker_cache(tag, docker_registry) -> None: """Imports tagged container from the given docker registry""" if docker_registry: # noinspection PyBroadException try: import docker_cache logging.info('Docker ca...
Load a list of arrays into a list of arrays specified by slices. def _load_general(data, targets, major_axis): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks if isinstance(d_ta...
Load data into sliced arrays. def _load_data(batch, targets, major_axis): """Load data into sliced arrays.""" if isinstance(batch, list): new_batch = [] for i in range(len(targets)): new_batch.append([b.data[i] for b in batch]) new_targets = [[dst for _, dst in d_target] for...
Merge outputs that lives on multiple context into one, so that they look like living on one context. def _merge_multi_context(outputs, major_axis): """Merge outputs that lives on multiple context into one, so that they look like living on one context. """ rets = [] for tensors, axis in zip(outp...
Prepare the group2contexts, will duplicate the context if some ctx_group map to only one context. def _prepare_group2ctxs(group2ctxs, ctx_len): """Prepare the group2contexts, will duplicate the context if some ctx_group map to only one context. """ if group2ctxs is None: return [None] * ctx...
Decide the slices for each context according to the workload. Parameters ---------- data_shapes : list list of (name, shape) specifying the shapes for the input data or label. def decide_slices(self, data_shapes): """Decide the slices for each context according to the workl...
Collect internal arrays from executors. def _collect_arrays(self): """Collect internal arrays from executors.""" # convenient data structures self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)] for name, _ in self.data_shapes] ...
Bind executors on their respective devices. Parameters ---------- data_shapes : list label_shapes : list shared_group : DataParallelExecutorGroup reshape : bool def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False): """Bind executors o...
Reshape executors. Parameters ---------- data_shapes : list label_shapes : list def reshape(self, data_shapes, label_shapes): """Reshape executors. Parameters ---------- data_shapes : list label_shapes : list """ if data_shapes =...
Assign, i.e. copy parameters to all the executors. Parameters ---------- arg_params : dict A dictionary of name to `NDArray` parameter mapping. aux_params : dict A dictionary of name to `NDArray` auxiliary variable mapping. allow_extra : boolean, optional...
Copy data from each executor to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the...
Split `data_batch` according to workload and run forward on each devices. Parameters ---------- data_batch : DataBatch Or could be any object implementing similar interface. is_train : bool The hint for the backend, indicating whether we are during training phase...
Get the shapes of the outputs. def get_output_shapes(self): """Get the shapes of the outputs.""" outputs = self.execs[0].outputs shapes = [out.shape for out in outputs] concat_shapes = [] for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts): ...
Get outputs of the previous forward computation. If begin or end is specified, return [begin, end)-th outputs, otherwise return all outputs. Parameters ---------- merge_multi_context : bool Default is `True`. In the case when data-parallelism is used, the outputs ...
Set value for states. Only one of states & value can be specified. Parameters ---------- states : list of list of NDArrays source states arrays formatted like [[state1_dev1, state1_dev2], [state2_dev1, state2_dev2]]. value : number a single scalar val...
Get the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A `True` value indicate that we ...
Run backward on all devices. A backward should be called after a call to the forward function. Backward cannot be called unless ``self.for_training`` is ``True``. Parameters ---------- out_grads : NDArray or list of NDArray, optional Gradient on the outputs to be pro...
Accumulate the performance according to `eval_metric` on all devices by comparing outputs from [begin, end) to labels. By default use all outputs. Parameters ---------- eval_metric : EvalMetric The metric used for evaluation. labels : list of NDArray ...
Internal utility function to bind the i-th executor. This function utilizes simple_bind python interface. def _bind_ith_exec(self, i, data_shapes, label_shapes, shared_group): """Internal utility function to bind the i-th executor. This function utilizes simple_bind python interface. ""...
Get the sliced shapes for the i-th executor. Parameters ---------- shapes : list of (str, tuple) The original (name, shape) pairs. i : int Which executor we are dealing with. def _sliced_shape(self, shapes, i, major_axis): """Get the sliced shapes for th...
parse # classes and class_names if applicable def parse_class_names(args): """ parse # classes and class_names if applicable """ num_class = args.num_class if len(args.class_names) > 0: if os.path.isfile(args.class_names): # try to open it to read class names with open(args....
Return True if ``data`` has instance of ``dtype``. This function is called after _init_data. ``data`` is a list of (str, NDArray) def _has_instance(data, dtype): """Return True if ``data`` has instance of ``dtype``. This function is called after _init_data. ``data`` is a list of (str, NDArray)""" ...
Shuffle the data. def _getdata_by_idx(data, idx): """Shuffle the data.""" shuffle_data = [] for k, v in data: if (isinstance(v, h5py.Dataset) if h5py else False): shuffle_data.append((k, v)) elif isinstance(v, CSRNDArray): shuffle_data.append((k, sparse_array(v.assc...
r"""MobileNet model from the `"MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861>`_ paper. Parameters ---------- multiplier : float The width multiplier for controling the model size. Only multipliers that are no le...
Get the canonical name for a symbol. This is the default implementation. If the user specifies a name, the user-specified name will be used. When user does not specify a name, we automatically generate a name based on the hint string. Parameters ---------- ...
Draw samples from log uniform distribution and returns sampled candidates, expected count for true classes and sampled classes. def draw(self, true_classes): """Draw samples from log uniform distribution and returns sampled candidates, expected count for true classes and sampled classes.""" ...
Inception_score function. The images will be divided into 'splits' parts, and calculate each inception_score separately, then return the mean and std of inception_scores of these parts. :param images: Images(num x c x w x h) that needs to calculate inception_score. :param splits: :return: me...
same as mx.model.load_checkpoint, but do not load symnet and will convert context def load_param(params, ctx=None): """same as mx.model.load_checkpoint, but do not load symnet and will convert context""" if ctx is None: ctx = mx.cpu() save_dict = mx.nd.load(params) arg_params = {} aux_param...
Deprecated. Please use cell.unroll instead def rnn_unroll(cell, length, inputs=None, begin_state=None, input_prefix='', layout='NTC'): """Deprecated. Please use cell.unroll instead""" warnings.warn('rnn_unroll is deprecated. Please call cell.unroll directly.') return cell.unroll(length=length, inputs=input...
Save checkpoint for model using RNN cells. Unpacks weight before saving. Parameters ---------- cells : mxnet.rnn.RNNCell or list of RNNCells The RNN cells used by this symbol. prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symb...
Load model checkpoint from file. Pack weights after loading. Parameters ---------- cells : mxnet.rnn.RNNCell or list of RNNCells The RNN cells used by this symbol. prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ...
Make a callback to checkpoint Module to prefix every epoch. unpacks weights used by cells before saving. Parameters ---------- cells : mxnet.rnn.RNNCell or list of RNNCells The RNN cells used by this symbol. prefix : str The file prefix to checkpoint to period : int How ...
Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. **kwargs : string Additional flags for hybridized operator. def hybridize(self...
Reads image specified by path into numpy.ndarray def read_img(path): """ Reads image specified by path into numpy.ndarray""" img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255 img = np.expand_dims(img.transpose(1, 0), 0) return img
Returns a tuple of names and zero arrays for LSTM init states def lstm_init_states(batch_size): """ Returns a tuple of names and zero arrays for LSTM init states""" hp = Hyperparams() init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden) init_...
Loads the model from checkpoint specified by prefix and epoch, binds it to an executor, and sets its parameters and returns a mx.mod.Module def load_module(prefix, epoch, data_names, data_shapes): """Loads the model from checkpoint specified by prefix and epoch, binds it to an executor, and sets its parame...
Program entry point def main(): """Program entry point""" parser = argparse.ArgumentParser() parser.add_argument("path", help="Path to the CAPTCHA image file") parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr') parser.add_argument("--epoch", help="Checkpoint ep...
invalid value in bbox_transform if this wrong (no overlap), note index 0 and 2 also note need to save before assignment :param bbox: [n][x1, y1, x2, y2] :param width: cv2 (height, width, channel) :param flip_x: will flip x1 and x2 :return: flipped box def bbox_flip(bbox, width, flip_x=False): "...
determine overlaps between boxes and query_boxes :param boxes: n * 4 bounding boxes :param query_boxes: k * 4 bounding boxes :return: overlaps: n * k overlaps def bbox_overlaps(boxes, query_boxes): """ determine overlaps between boxes and query_boxes :param boxes: n * 4 bounding boxes :para...
Clip boxes to image boundaries. :param boxes: [N, 4* num_classes] :param im_shape: tuple of 2 :return: [N, 4* num_classes] def clip_boxes(boxes, im_shape): """ Clip boxes to image boundaries. :param boxes: [N, 4* num_classes] :param im_shape: tuple of 2 :return: [N, 4* num_classes] ...
compute bounding box regression targets from ex_rois to gt_rois :param ex_rois: [N, 4] :param gt_rois: [N, 4] :return: [N, 4] def bbox_transform(ex_rois, gt_rois, box_stds): """ compute bounding box regression targets from ex_rois to gt_rois :param ex_rois: [N, 4] :param gt_rois: [N, 4] ...
Transform the set of class-agnostic boxes into class-specific boxes by applying the predicted offsets (box_deltas) :param boxes: !important [N 4] :param box_deltas: [N, 4 * num_classes] :return: [N 4 * num_classes] def bbox_pred(boxes, box_deltas, box_stds): """ Transform the set of class-agnos...
greedily select boxes with high confidence and overlap with current maximum <= thresh rule out overlap >= thresh :param dets: [[x1, y1, x2, y2 score]] :param thresh: retain overlap < thresh :return: indexes to keep def nms(dets, thresh): """ greedily select boxes with high confidence and overla...
rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3) def im_detect(rois, scores, bbox_deltas, im_info, bbox_stds, nms_thresh, conf_thresh): """rois (nroi, 4), scores (nrois, nclasses), bbox_deltas (nrois, 4 * nclasses), im_info (3)""" rois = rois.asnumpy() ...
Convert a python string to C string. def c_str(string): """"Convert a python string to C string.""" if not isinstance(string, str): string = string.decode('ascii') return ctypes.c_char_p(string.encode('utf-8'))
Find mxnet library. def _find_lib_path(): """Find mxnet library.""" curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) amalgamation_lib_path = os.path.join(curr_path, '../../lib/libmxnet_predict.so') if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_pa...
Load libary by searching possible path. def _load_lib(): """Load libary by searching possible path.""" lib_path = _find_lib_path() lib = ctypes.cdll.LoadLibrary(lib_path[0]) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib
Load ndarray file and return as list of numpy array. Parameters ---------- nd_bytes : str or bytes The internal ndarray bytes Returns ------- out : dict of str to numpy array or list of numpy array The output list or dict, depending on whether the saved type is list or dict. d...
Perform forward to get the output. Parameters ---------- **kwargs Keyword arguments of input variable name to data. Examples -------- >>> predictor.forward(data=mydata) >>> out = predictor.get_output(0) def forward(self, **kwargs): """Perfor...
Change the input shape of the predictor. Parameters ---------- input_shapes : dict of str to tuple The new shape of input data. Examples -------- >>> predictor.reshape({'data':data_shape_tuple}) def reshape(self, input_shapes): """Change the input s...
Get the index-th output. Parameters ---------- index : int The index of output. Returns ------- out : numpy array. The output array. def get_output(self, index): """Get the index-th output. Parameters ---------- ...
Begin an episode of a game instance. We can play the game for a maximum of `max_episode_step` and after that, we are forced to restart def begin_episode(self, max_episode_step=DEFAULT_MAX_EPISODE_STEP): """ Begin an episode of a game instance. We can play the game for a maximum of ...
Reset before re-using the cell for another graph. def reset(self): """Reset before re-using the cell for another graph.""" self._init_counter = -1 self._counter = -1 for cell in self._children.values(): cell.reset()
Initial state for this cell. Parameters ---------- func : callable, default symbol.zeros Function for creating initial state. For Symbol API, func can be `symbol.zeros`, `symbol.uniform`, `symbol.var etc`. Use `symbol.var` if you want to directly ...
Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None If `inputs` is a single Symbol (usually the output of Embedding symbol), it should have shape (ba...
Get activation function. Convert if is string def _get_activation(self, F, inputs, activation, **kwargs): """Get activation function. Convert if is string""" func = {'tanh': F.tanh, 'relu': F.relu, 'sigmoid': F.sigmoid, 'softsign': F.softsign}.get(activat...
Unrolls the recurrent cell for one time step. Parameters ---------- inputs : sym.Variable Input symbol, 2D, of shape (batch_size * num_units). states : list of sym.Variable RNN state from previous step or the output of begin_state(). Returns ----...
Check that all input names are in symbol's arguments. def _check_input_names(symbol, names, typename, throw): """Check that all input names are in symbol's arguments.""" args = symbol.list_arguments() for name in names: if name in args: continue candidates = [arg for arg in args...
Check that input names matches input data descriptors. def _check_names_match(data_names, data_shapes, name, throw): """Check that input names matches input data descriptors.""" actual = [x[0] for x in data_shapes] if sorted(data_names) != sorted(actual): msg = "Data provided by %s_shapes don't mat...
parse data_attrs into DataDesc format and check that names match def _parse_data_desc(data_names, label_names, data_shapes, label_shapes): """parse data_attrs into DataDesc format and check that names match""" data_shapes = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in data_shapes] _check_names_...
A convenient function that calls both ``forward`` and ``backward``. def forward_backward(self, data_batch): """A convenient function that calls both ``forward`` and ``backward``.""" self.forward(data_batch, is_train=True) self.backward()
Runs prediction on ``eval_data`` and evaluates the performance according to the given ``eval_metric``. Checkout `Module Tutorial <http://mxnet.io/tutorials/basic/module.html>`_ to see a end-to-end use-case. Parameters ---------- eval_data : DataIter Evaluati...
Iterates over predictions. Examples -------- >>> for pred, i_batch, batch in module.iter_predict(eval_data): ... # pred is a list of outputs from the module ... # i_batch is a integer ... # batch is the data batch from the data iterator Parameters ...
Runs prediction and collects the outputs. When `merge_batches` is ``True`` (by default), the return value will be a list ``[out1, out2, out3]``, where each element is formed by concatenating the outputs for all the mini-batches. When `always_output_list` is ``False`` (as by default), th...
Assigns parameter and aux state values. Parameters ---------- arg_params : dict Dictionary of name to value (`NDArray`) mapping. aux_params : dict Dictionary of name to value (`NDArray`) mapping. allow_missing : bool If ``True``, params could ...
Saves model parameters to file. Parameters ---------- fname : str Path to output param file. Examples -------- >>> # An example of saving module parameters. >>> mod.save_params('myfile') def save_params(self, fname): """Saves model parameter...
Loads model parameters from file. Parameters ---------- fname : str Path to input param file. Examples -------- >>> # An example of loading module parameters. >>> mod.load_params('myfile') def load_params(self, fname): """Loads model paramet...