Search is not available for this dataset
text
stringlengths
75
104k
def zero_state(self, batch_size, dtype=LayersConfig.tf_dtype): """Return zero-filled state tensor(s). Args: batch_size: int, float, or unit Tensor representing the batch size. Returns: tensor of shape '[batch_size x shape[0] x shape[1] x num_features] filled with ze...
def state_size(self): """State size of the LSTMStateTuple.""" return (LSTMStateTuple(self._num_units, self._num_units) if self._state_is_tuple else 2 * self._num_units)
def _to_bc_h_w(self, x, x_shape): """(b, h, w, c) -> (b*c, h, w)""" x = tf.transpose(x, [0, 3, 1, 2]) x = tf.reshape(x, (-1, x_shape[1], x_shape[2])) return x
def _to_b_h_w_n_c(self, x, x_shape): """(b*c, h, w, n) -> (b, h, w, n, c)""" x = tf.reshape(x, (-1, x_shape[4], x_shape[1], x_shape[2], x_shape[3])) x = tf.transpose(x, [0, 2, 3, 4, 1]) return x
def _tf_repeat(self, a, repeats): """Tensorflow version of np.repeat for 1D""" # https://github.com/tensorflow/tensorflow/issues/8521 if len(a.get_shape()) != 1: raise AssertionError("This is not a 1D Tensor") a = tf.expand_dims(a, -1) a = tf.tile(a, [1, repeats]) ...
def _tf_batch_map_coordinates(self, inputs, coords): """Batch version of tf_map_coordinates Only supports 2D feature maps Parameters ---------- inputs : ``tf.Tensor`` shape = (b*c, h, w) coords : ``tf.Tensor`` shape = (b*c, h, w, n, 2) R...
def _tf_batch_map_offsets(self, inputs, offsets, grid_offset): """Batch map offsets into input Parameters ------------ inputs : ``tf.Tensor`` shape = (b, h, w, c) offsets: ``tf.Tensor`` shape = (b, h, w, 2*n) grid_offset: `tf.Tensor`` ...
def minibatches(inputs=None, targets=None, batch_size=None, allow_dynamic_batch_size=False, shuffle=False): """Generate a generator that input a group of example in numpy.array and their labels, return the examples and labels by the given batch size. Parameters ---------- inputs : numpy.array ...
def seq_minibatches(inputs, targets, batch_size, seq_length, stride=1): """Generate a generator that return a batch of sequence inputs and targets. If `batch_size=100` and `seq_length=5`, one return will have 500 rows (examples). Parameters ---------- inputs : numpy.array The input features...
def seq_minibatches2(inputs, targets, batch_size, num_steps): """Generate a generator that iterates on two list of words. Yields (Returns) the source contexts and the target context by the given batch_size and num_steps (sequence_length). In TensorFlow's tutorial, this generates the `batch_size` pointers in...
def ptb_iterator(raw_data, batch_size, num_steps): """Generate a generator that iterates on a list of words, see `PTB example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_ptb_lstm_state_is_tuple.py>`__. Yields the source contexts and the target context by the given batch_size and num...
def deconv2d_bilinear_upsampling_initializer(shape): """Returns the initializer that can be passed to DeConv2dLayer for initializing the weights in correspondence to channel-wise bilinear up-sampling. Used in segmentation approaches such as [FCN](https://arxiv.org/abs/1605.06211) Parameters -------...
def save_model(self, network=None, model_name='model', **kwargs): """Save model architecture and parameters into database, timestamp will be added automatically. Parameters ---------- network : TensorLayer layer TensorLayer layer instance. model_name : str ...
def find_top_model(self, sess, sort=None, model_name='model', **kwargs): """Finds and returns a model architecture and its parameters from the database which matches the requirement. Parameters ---------- sess : Session TensorFlow session. sort : List of tuple ...
def delete_model(self, **kwargs): """Delete model. Parameters ----------- kwargs : logging information Find items to delete, leave it empty to delete all log. """ self._fill_project_info(kwargs) self.db.Model.delete_many(kwargs) logging.info("...
def save_dataset(self, dataset=None, dataset_name=None, **kwargs): """Saves one dataset into database, timestamp will be added automatically. Parameters ---------- dataset : any type The dataset you want to store. dataset_name : str The name of dataset. ...
def find_top_dataset(self, dataset_name=None, sort=None, **kwargs): """Finds and returns a dataset from the database which matches the requirement. Parameters ---------- dataset_name : str The name of dataset. sort : List of tuple PyMongo sort comment, se...
def find_datasets(self, dataset_name=None, **kwargs): """Finds and returns all datasets from the database which matches the requirement. In some case, the data in a dataset can be stored separately for better management. Parameters ---------- dataset_name : str The n...
def delete_datasets(self, **kwargs): """Delete datasets. Parameters ----------- kwargs : logging information Find items to delete, leave it empty to delete all log. """ self._fill_project_info(kwargs) self.db.Dataset.delete_many(kwargs) logg...
def save_training_log(self, **kwargs): """Saves the training log, timestamp will be added automatically. Parameters ----------- kwargs : logging information Events, such as accuracy, loss, step number and etc. Examples --------- >>> db.save_training_...
def save_validation_log(self, **kwargs): """Saves the validation log, timestamp will be added automatically. Parameters ----------- kwargs : logging information Events, such as accuracy, loss, step number and etc. Examples --------- >>> db.save_valid...
def delete_training_log(self, **kwargs): """Deletes training log. Parameters ----------- kwargs : logging information Find items to delete, leave it empty to delete all log. Examples --------- Save training log >>> db.save_training_log(accura...
def delete_validation_log(self, **kwargs): """Deletes validation log. Parameters ----------- kwargs : logging information Find items to delete, leave it empty to delete all log. Examples --------- - see ``save_training_log``. """ self...
def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs): """Uploads a task to the database, timestamp will be added automatically. Parameters ----------- task_name : str The task name. script : str File ...
def run_top_task(self, task_name=None, sort=None, **kwargs): """Finds and runs a pending task that in the first of the sorting list. Parameters ----------- task_name : str The task name. sort : List of tuple PyMongo sort comment, search "PyMongo find one ...
def delete_tasks(self, **kwargs): """Delete tasks. Parameters ----------- kwargs : logging information Find items to delete, leave it empty to delete all log. Examples --------- >>> db.delete_tasks() """ self._fill_project_info(kwar...
def check_unfinished_task(self, task_name=None, **kwargs): """Finds and runs a pending task. Parameters ----------- task_name : str The task name. kwargs : other parameters Users customized parameters such as description, version number. Examples...
def augment_with_ngrams(unigrams, unigram_vocab_size, n_buckets, n=2): """Augment unigram features with hashed n-gram features.""" def get_ngrams(n): return list(zip(*[unigrams[i:] for i in range(n)])) def hash_ngram(ngram): bytes_ = array.array('L', ngram).tobytes() hash_ = int(ha...
def load_and_preprocess_imdb_data(n_gram=None): """Load IMDb data and augment with hashed n-gram features.""" X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE) if n_gram is not None: X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x i...
def read_image(image, path=''): """Read one image. Parameters ----------- image : str The image file name. path : str The image folder path. Returns ------- numpy.array The image. """ return imageio.imread(os.path.join(path, image))
def read_images(img_list, path='', n_threads=10, printable=True): """Returns all images in list by given path and name of each image file. Parameters ------------- img_list : list of str The image file names. path : str The image folder path. n_threads : int The number o...
def save_image(image, image_path='_temp.png'): """Save a image. Parameters ----------- image : numpy array [w, h, c] image_path : str path """ try: # RGB imageio.imwrite(image_path, image) except Exception: # Greyscale imageio.imwrite(image_path, image...
def save_images(images, size, image_path='_temp.png'): """Save multiple images into one single image. Parameters ----------- images : numpy array (batch, w, h, c) size : list of 2 ints row and column number. number of images should be equal or less than size[0] * size[1] ...
def draw_boxes_and_labels_to_image( image, classes, coords, scores, classes_list, is_center=True, is_rescale=True, save_name=None ): """Draw bboxes and class labels on image. Return or save the image with bboxes, example in the docs of ``tl.prepro``. Parameters ----------- image : numpy.array ...
def draw_mpii_pose_to_image(image, poses, save_name='image.png'): """Draw people(s) into image using MPII dataset format as input, return or save the result image. This is an experimental API, can be changed in the future. Parameters ----------- image : numpy.array The RGB image [height, w...
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836): """Display a frame. Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image. second : int The display second(s) for the image(s), if saveable is Fals...
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362): """Display a group of RGB or Greyscale CNN masks. Parameters ---------- CNN : numpy.array The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64). second : int The display second(s) for the image(s), if savea...
def tsne_embedding(embeddings, reverse_dictionary, plot_only=500, second=5, saveable=False, name='tsne', fig_idx=9862): """Visualize the embeddings by using t-SNE. Parameters ---------- embeddings : numpy.array The embedding matrix. reverse_dictionary : dictionary id_to_word, mappin...
def draw_weights(W=None, second=10, saveable=True, shape=None, name='mnist', fig_idx=2396512): """Visualize every columns of the weight matrix to a group of Greyscale img. Parameters ---------- W : numpy.array The weight matrix second : int The display second(s) for the image(s), if...
def data_to_tfrecord(images, labels, filename): """Save data into TFRecord.""" if os.path.isfile(filename): print("%s exists" % filename) return print("Converting data into %s ..." % filename) # cwd = os.getcwd() writer = tf.python_io.TFRecordWriter(filename) for index, img in en...
def read_and_decode(filename, is_train=None): """Return tensor to read from TFRecord.""" filename_queue = tf.train.string_input_producer([filename]) reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, featur...
def print_params(self, details=True, session=None): """Print all info of parameters in the network""" for i, p in enumerate(self.all_params): if details: try: val = p.eval(session=session) logging.info( " param ...
def print_layers(self): """Print all info of layers in the network.""" for i, layer in enumerate(self.all_layers): # logging.info(" layer %d: %s" % (i, str(layer))) logging.info( " layer {:3}: {:20} {:15} {}".format(i, layer.name, str(layer.get_shape()), laye...
def count_params(self): """Returns the number of parameters in the network.""" n_params = 0 for _i, p in enumerate(self.all_params): n = 1 # for s in p.eval().shape: for s in p.get_shape(): try: s = int(s) ex...
def get_all_params(self, session=None): """Return the parameters in a list of array.""" _params = [] for p in self.all_params: if session is None: _params.append(p.eval()) else: _params.append(session.run(p)) return _params
def _get_init_args(self, skip=4): """Get all arguments of current layer for saving the graph.""" stack = inspect.stack() if len(stack) < skip + 1: raise ValueError("The length of the inspection stack is shorter than the requested start position.") args, _, _, values = inspe...
def roi_pooling(input, rois, pool_height, pool_width): """ returns a tensorflow operation for computing the Region of Interest Pooling @arg input: feature maps on which to perform the pooling operation @arg rois: list of regions of interest in the format (feature map index, upper left, bottom...
def _int64_feature(value): """Wrapper for inserting an int64 Feature into a SequenceExample proto, e.g, An integer label. """ return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value): """Wrapper for inserting a bytes Feature into a SequenceExample proto, e.g, an image in byte """ # return tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(value)])) return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature_list(values): """Wrapper for inserting an int64 FeatureList into a SequenceExample proto, e.g, sentence in list of ints """ return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
def _bytes_feature_list(values): """Wrapper for inserting a bytes FeatureList into a SequenceExample proto, e.g, sentence in list of bytes """ return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])
def distort_image(image, thread_id): """Perform random distortions on an image. Args: image: A float32 Tensor of shape [height, width, 3] with values in [0, 1). thread_id: Preprocessing thread id used to select the ordering of color distortions. There should be a multiple of 2 preprocess...
def prefetch_input_data( reader, file_pattern, is_training, batch_size, values_per_shard, input_queue_capacity_factor=16, num_reader_threads=1, shard_queue_name="filename_queue", value_queue_name="input_queue" ): """Prefetches string values from disk into an input queue. In training the capacit...
def batch_with_dynamic_pad(images_and_captions, batch_size, queue_capacity, add_summaries=True): """Batches input images and captions. This function splits the caption into an input sequence and a target sequence, where the target sequence is the input sequence right-shifted by 1. Input and target sequ...
def _to_channel_first_bias(b): """Reshape [c] to [c, 1, 1].""" channel_size = int(b.shape[0]) new_shape = (channel_size, 1, 1) # new_shape = [-1, 1, 1] # doesn't work with tensorRT return tf.reshape(b, new_shape)
def _bias_scale(x, b, data_format): """The multiplication counter part of tf.nn.bias_add.""" if data_format == 'NHWC': return x * b elif data_format == 'NCHW': return x * _to_channel_first_bias(b) else: raise ValueError('invalid data_format: %s' % data_format)
def _bias_add(x, b, data_format): """Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT.""" if data_format == 'NHWC': return tf.add(x, b) elif data_format == 'NCHW': return tf.add(x, _to_channel_first_bias(b)) else: raise ValueError('invalid data_form...
def batch_normalization(x, mean, variance, offset, scale, variance_epsilon, data_format, name=None): """Data Format aware version of tf.nn.batch_normalization.""" with ops.name_scope(name, 'batchnorm', [x, mean, variance, scale, offset]): inv = math_ops.rsqrt(variance + variance_epsilon) if scal...
def compute_alpha(x): """Computing the scale parameter.""" threshold = _compute_threshold(x) alpha1_temp1 = tf.where(tf.greater(x, threshold), x, tf.zeros_like(x, tf.float32)) alpha1_temp2 = tf.where(tf.less(x, -threshold), x, tf.zeros_like(x, tf.float32)) alpha_array = tf.add(alpha1_temp1, alpha1_t...
def flatten_reshape(variable, name='flatten'): """Reshapes a high-dimension vector input. [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask] Parameters ---------- variable : TensorFlow variable or tensor The variable or tensor to be flatten. name :...
def get_layers_with_name(net, name="", verbose=False): """Get a list of layers' output in a network by a given name scope. Parameters ----------- net : :class:`Layer` The last layer of the network. name : str Get the layers' output that contain this name. verbose : boolean ...
def get_variables_with_name(name=None, train_only=True, verbose=False): """Get a list of TensorFlow variables by a given name scope. Parameters ---------- name : str Get the variables that contain this name. train_only : boolean If Ture, only get the trainable variables. verbose...
def initialize_rnn_state(state, feed_dict=None): """Returns the initialized RNN state. The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`. Parameters ---------- state : RNN state. The TensorFlow's RNN state. feed_dict : dictionary Initial RNN s...
def list_remove_repeat(x): """Remove the repeated items in a list, and return the processed list. You may need it to create merged layer like Concat, Elementwise and etc. Parameters ---------- x : list Input Returns ------- list A list that after removing it's repeated ...
def merge_networks(layers=None): """Merge all parameters, layers and dropout probabilities to a :class:`Layer`. The output of return network is the first network in the list. Parameters ---------- layers : list of :class:`Layer` Merge all parameters, layers and dropout probabilities to the ...
def print_all_variables(train_only=False): """Print information of trainable or all variables, without ``tl.layers.initialize_global_variables(sess)``. Parameters ---------- train_only : boolean Whether print trainable variables only. - If True, print the trainable variables. ...
def ternary_operation(x): """Ternary operation use threshold computed with weights.""" g = tf.get_default_graph() with g.gradient_override_map({"Sign": "Identity"}): threshold = _compute_threshold(x) x = tf.sign(tf.add(tf.sign(tf.add(x, threshold)), tf.sign(tf.add(x, -threshold)))) r...
def _compute_threshold(x): """ ref: https://github.com/XJTUWYD/TWN Computing the threshold. """ x_sum = tf.reduce_sum(tf.abs(x), reduction_indices=None, keepdims=False, name=None) threshold = tf.div(x_sum, tf.cast(tf.size(x), tf.float32), name=None) threshold = tf.multiply(0.7, threshold, na...
def freeze_graph(graph_path, checkpoint_path, output_path, end_node_names, is_binary_graph): """Reimplementation of the TensorFlow official freeze_graph function to freeze the graph and checkpoint together: Parameters ----------- graph_path : string the path where your graph file save. chec...
def convert_model_to_onnx(frozen_graph_path, end_node_names, onnx_output_path): """Reimplementation of the TensorFlow-onnx official tutorial convert the proto buff to onnx file: Parameters ----------- frozen_graph_path : string the path where your frozen graph file save. end_node_names : st...
def convert_onnx_to_model(onnx_input_path): """Reimplementation of the TensorFlow-onnx official tutorial convert the onnx file to specific: model Parameters ----------- onnx_input_path : string the path where you save the onnx file. References ----------- - `onnx-tf exporting tutorial ...
def _add_deprecated_function_notice_to_docstring(doc, date, instructions): """Adds a deprecation notice to a docstring for deprecated functions.""" if instructions: deprecation_message = """ .. warning:: **THIS FUNCTION IS DEPRECATED:** It will be removed after %s. ...
def _add_notice_to_docstring(doc, no_doc_str, notice): """Adds a deprecation notice to a docstring.""" if not doc: lines = [no_doc_str] else: lines = _normalize_docstring(doc).splitlines() notice = [''] + notice if len(lines) > 1: # Make sure that we keep our distance from...
def alphas(shape, alpha_value, name=None): """Creates a tensor with all elements set to `alpha_value`. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to alpha. Parameters ---------- shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of typ...
def alphas_like(tensor, alpha_value, name=None, optimize=True): """Creates a tensor with all elements set to `alpha_value`. Given a single tensor (`tensor`), this operation returns a tensor of the same type and shape as `tensor` with all elements set to `alpha_value`. Parameters ---------- tens...
def example1(): """ Example 1: Applying transformation one-by-one is very SLOW ! """ st = time.time() for _ in range(100): # Try 100 times and compute the averaged speed xx = tl.prepro.rotation(image, rg=-20, is_random=False) xx = tl.prepro.flip_axis(xx, axis=1, is_random=False) xx ...
def example2(): """ Example 2: Applying all transforms in one is very FAST ! """ st = time.time() for _ in range(100): # Repeat 100 times and compute the averaged speed transform_matrix = create_transformation_matrix() result = tl.prepro.affine_transform_cv2(image, transform_matrix) # Tran...
def example3(): """ Example 3: Using TF dataset API to load and process image for training """ n_data = 100 imgs_file_list = ['tiger.jpeg'] * n_data train_targets = [np.ones(1)] * n_data def generator(): if len(imgs_file_list) != len(train_targets): raise RuntimeError('len(imgs_...
def example4(): """ Example 4: Transforming coordinates using affine matrix. """ transform_matrix = create_transformation_matrix() result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster # Transform keypoint coordinates coords = [[(50, 100), (100, 100), (100, 50), (200, 2...
def distort_fn(x, is_train=False): """ The images are processed as follows: .. They are cropped to 24 x 24 pixels, centrally for evaluation or randomly for training. .. They are approximately whitened to make the model insensitive to dynamic range. For training, we additionally apply a series of ran...
def fit( sess, network, train_op, cost, X_train, y_train, x, y_, acc=None, batch_size=100, n_epoch=100, print_freq=5, X_val=None, y_val=None, eval_train=True, tensorboard_dir=None, tensorboard_epoch_freq=5, tensorboard_weight_histograms=True, tensorboard_graph_vis=True ): """Training a given...
def predict(sess, network, X, x, y_op, batch_size=None): """ Return the predict results of given non time-series network. Parameters ---------- sess : Session TensorFlow Session. network : TensorLayer layer The network. X : numpy.array The inputs. x : placeholder...
def evaluation(y_test=None, y_predict=None, n_classes=None): """ Input the predicted results, targets results and the number of class, return the confusion matrix, F1-score of each class, accuracy and macro F1-score. Parameters ---------- y_test : list The target results y_predi...
def class_balancing_oversample(X_train=None, y_train=None, printable=True): """Input the features and labels, return the features and labels after oversampling. Parameters ---------- X_train : numpy.array The inputs. y_train : numpy.array The targets. Examples -------- ...
def get_random_int(min_v=0, max_v=10, number=5, seed=None): """Return a list of random integer by the given range and quantity. Parameters ----------- min_v : number The minimum value. max_v : number The maximum value. number : int Number of value. seed : int or None...
def list_string_to_dict(string): """Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.""" dictionary = {} for idx, c in enumerate(string): dictionary.update({c: idx}) return dictionary
def exit_tensorflow(sess=None, port=6006): """Close TensorFlow session, TensorBoard and Nvidia-process if available. Parameters ---------- sess : Session TensorFlow Session. tb_port : int TensorBoard port you want to close, `6006` as default. """ text = "[TL] Close tensorbo...
def open_tensorboard(log_dir='/tmp/tensorflow', port=6006): """Open Tensorboard. Parameters ---------- log_dir : str Directory where your tensorboard logs are saved port : int TensorBoard port you want to open, 6006 is tensorboard default """ text = "[TL] Open tensorboard, ...
def clear_all_placeholder_variables(printable=True): """Clears all the placeholder variables of keep prob, including keeping probabilities of all dropout, denoising, dropconnect etc. Parameters ---------- printable : boolean If True, print all deleted variables. """ tl.logging.info...
def set_gpu_fraction(gpu_fraction=0.3): """Set the GPU memory fraction for the application. Parameters ---------- gpu_fraction : float Fraction of GPU memory, (0 ~ 1] References ---------- - `TensorFlow using GPU <https://www.tensorflow.org/versions/r0.9/how_tos/using_gpu/index.htm...
def generate_skip_gram_batch(data, batch_size, num_skips, skip_window, data_index=0): """Generate a training batch for the Skip-Gram model. See `Word2Vec example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_word2vec_basic.py>`__. Parameters ---------- data : list of dat...
def sample(a=None, temperature=1.0): """Sample an index from a probability array. Parameters ---------- a : list of float List of probabilities. temperature : float or None The higher the more uniform. When a = [0.1, 0.2, 0.7], - temperature = 0.7, the distribution will ...
def sample_top(a=None, top_k=10): """Sample from ``top_k`` probabilities. Parameters ---------- a : list of float List of probabilities. top_k : int Number of candidates to be considered. """ if a is None: a = [] idx = np.argpartition(a, -top_k)[-top_k:] pr...
def process_sentence(sentence, start_word="<S>", end_word="</S>"): """Seperate a sentence string into a list of string words, add start_word and end_word, see ``create_vocab()`` and ``tutorial_tfrecord3.py``. Parameters ---------- sentence : str A sentence. start_word : str or None ...
def create_vocab(sentences, word_counts_output_file, min_word_count=1): """Creates the vocabulary of word to word_id. See ``tutorial_tfrecord3.py``. The vocabulary is saved to disk in a text file of word counts. The id of each word in the file is its corresponding 0-based line number. Parameters ...
def read_words(filename="nietzsche.txt", replace=None): """Read list format context from a file. For customized read_words method, see ``tutorial_generate_text.py``. Parameters ---------- filename : str a file path. replace : list of str replace original string by target string...
def read_analogies_file(eval_file='questions-words.txt', word2id=None): """Reads through an analogy question file, return its id format. Parameters ---------- eval_file : str The file name. word2id : dictionary a dictionary that maps word to ID. Returns -------- numpy.a...
def build_reverse_dictionary(word_to_id): """Given a dictionary that maps word to integer id. Returns a reverse dictionary that maps a id to word. Parameters ---------- word_to_id : dictionary that maps word to ID. Returns -------- dictionary A dictionary that maps IDs ...
def build_words_dataset(words=None, vocabulary_size=50000, printable=True, unk_key='UNK'): """Build the words dictionary and replace rare words with 'UNK' token. The most common word has the smallest integer id. Parameters ---------- words : list of str or byte The context in list format. Y...
def words_to_word_ids(data=None, word_to_id=None, unk_key='UNK'): """Convert a list of string (words) to IDs. Parameters ---------- data : list of string or byte The context in list format word_to_id : a dictionary that maps word to ID. unk_key : str Represent the unknow...