INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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 zeros | 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... |
State size of the LSTMStateTuple. | 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) |
( b h w c ) - > ( b * c h w ) | 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 |
( b * c h w n ) - > ( b h w n c ) | 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 |
Tensorflow version of np. repeat for 1D | 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])
... |
Batch version of tf_map_coordinates | 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... |
Batch map offsets into input | 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``
... |
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. | 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
... |
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 ). | 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... |
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 into the raw PTB data and allows minibatch iteration along these pointers. | 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... |
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_steps ( sequence_length ). | 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... |
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 ) | 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
-------... |
Save model architecture and parameters into database timestamp will be added automatically. | 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
... |
Finds and returns a model architecture and its parameters from the database which matches the requirement. | 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
... |
Delete model. | 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("... |
Saves one dataset into database timestamp will be added automatically. | 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.
... |
Finds and returns a dataset from the database which matches the requirement. | 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... |
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. | 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... |
Delete datasets. | 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... |
Saves the training log timestamp will be added automatically. | 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_... |
Saves the validation log timestamp will be added automatically. | 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... |
Deletes training log. | 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... |
Deletes validation log. | 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... |
Uploads a task to the database timestamp will be added automatically. | 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 ... |
Finds and runs a pending task that in the first of the sorting list. | 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 ... |
Delete tasks. | 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... |
Finds and runs a pending task. | 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... |
Augment unigram features with hashed n - gram features. | 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... |
Load IMDb data and augment with hashed n - gram features. | 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... |
Read one image. | 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)) |
Returns all images in list by given path and name of each image file. | 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... |
Save a image. | 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... |
Save multiple images into one single 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]
... |
Draw bboxes and class labels on image. Return or save the image with bboxes example in the docs of tl. prepro. | 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
... |
Draw people ( s ) into image using MPII dataset format as input return or save the result image. | 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... |
Display a frame. Make sure OpenAI Gym render () is disable before using it. | 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... |
Display a group of RGB or Greyscale CNN masks. | 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... |
Visualize the embeddings by using t - SNE. | 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... |
Visualize every columns of the weight matrix to a group of Greyscale img. | 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... |
Save data into TFRecord. | 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... |
Return tensor to read from TFRecord. | 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... |
Print all info of parameters in the network | 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 ... |
Print all info of layers in the network. | 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... |
Returns the number of parameters in the network. | 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... |
Return the parameters in a list of array. | 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 |
Get all arguments of current layer for saving the graph. | 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... |
returns a tensorflow operation for computing the Region of Interest Pooling | 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... |
Wrapper for inserting an int64 Feature into a SequenceExample proto e. g An integer label. | 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])) |
Wrapper for inserting a bytes Feature into a SequenceExample proto e. g an image in byte | 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])) |
Wrapper for inserting an int64 FeatureList into a SequenceExample proto e. g sentence in list of ints | 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]) |
Wrapper for inserting a bytes FeatureList into a SequenceExample proto e. g sentence in list of bytes | 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]) |
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 preprocessing threads. Returns: distorted_image: A float32 Tensor of shape [ heig... | 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... |
Prefetches string values from disk into an input queue. | 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... |
Batches input images and captions. | 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... |
Reshape [ c ] to [ c 1 1 ]. | 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) |
The multiplication counter part of tf. nn. bias_add. | 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) |
Alternative implementation of tf. nn. bias_add which is compatiable with tensorRT. | 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... |
Data Format aware version of tf. nn. batch_normalization. | 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... |
Computing the scale parameter. | 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... |
Reshapes a high - dimension vector input. | 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 :... |
Get a list of layers output in a network by a given name scope. | 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
... |
Get a list of TensorFlow variables by a given name scope. | 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... |
Returns the initialized RNN state. The inputs are LSTMStateTuple or State of RNNCells and an optional feed_dict. | 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... |
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. | 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 ... |
Merge all parameters layers and dropout probabilities to a: class: Layer. The output of return network is the first network in the list. | 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 ... |
Print information of trainable or all variables without tl. layers. initialize_global_variables ( sess ). | 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.
... |
Ternary operation use threshold computed with weights. | 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... |
ref: https:// github. com/ XJTUWYD/ TWN Computing the threshold. | 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... |
Reimplementation of the TensorFlow official freeze_graph function to freeze the graph and checkpoint together: | 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... |
Reimplementation of the TensorFlow - onnx official tutorial convert the proto buff to onnx file: | 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... |
Reimplementation of the TensorFlow - onnx official tutorial convert the onnx file to specific: model | 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 ... |
Adds a deprecation notice to a docstring for deprecated functions. | 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.
... |
Adds a deprecation notice to a docstring. | 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... |
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. | 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... |
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. | 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... |
Example 1: Applying transformation one - by - one is very SLOW ! | 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 ... |
Example 2: Applying all transforms in one is very FAST ! | 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... |
Example 3: Using TF dataset API to load and process image for training | 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_... |
Example 4: Transforming coordinates using affine matrix. | 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... |
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 random distortions to artificially increase the data set size:.. R... | 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... |
Training a given non time - series network by the given cost function training data batch_size n_epoch etc. | 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... |
Return the predict results of given non time - series network. | 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... |
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. | 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... |
Input the features and labels return the features and labels after oversampling. | 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
--------
... |
Return a list of random integer by the given range and quantity. | 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... |
Inputs [ a b c ] returns { a: 0 b: 1 c: 2 }. | 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 |
Close TensorFlow session TensorBoard and Nvidia - process if available. | 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... |
Open Tensorboard. | 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, ... |
Clears all the placeholder variables of keep prob including keeping probabilities of all dropout denoising dropconnect etc. | 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... |
Set the GPU memory fraction for the application. | 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... |
Generate a training batch for the Skip - Gram model. | 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... |
Sample an index from a probability array. | 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 ... |
Sample from top_k probabilities. | 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... |
Seperate a sentence string into a list of string words add start_word and end_word see create_vocab () and tutorial_tfrecord3. py. | 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
... |
Creates the vocabulary of word to word_id. | 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
... |
Read list format context from a file. | 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... |
Reads through an analogy question file return its id format. | 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... |
Given a dictionary that maps word to integer id. Returns a reverse dictionary that maps a id to word. | 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 ... |
Build the words dictionary and replace rare words with UNK token. The most common word has the smallest integer id. | 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... |
Convert a list of string ( words ) to IDs. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.