_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q252200 | get_zca_whitening_principal_components_img | validation | def get_zca_whitening_principal_components_img(X):
"""Return the ZCA whitening principal components matrix.
Parameters
-----------
x : numpy.array
Batch of images with dimension of [n_example, row, col, channel] (default).
Returns
-------
numpy.array
A processed image.
... | python | {
"resource": ""
} |
q252201 | zca_whitening | validation | def zca_whitening(x, principal_components):
"""Apply ZCA whitening on an image by given principal components matrix.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
principal_components : matrix
Matrix from ``get_zca_whitening_princip... | python | {
"resource": ""
} |
q252202 | drop | validation | def drop(x, keep=0.5):
"""Randomly set some pixels to zero by a given keeping probability.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] or [row, col].
keep : float
The keeping probability (0, 1), the lower more values will be set to zero.
... | python | {
"resource": ""
} |
q252203 | pt2map | validation | def pt2map(list_points=None, size=(100, 100), val=1):
"""Inputs a list of points, return a 2D image.
Parameters
--------------
list_points : list of 2 int
[[x, y], [x, y]..] for point coordinates.
size : tuple of 2 int
(w, h) for output size.
val : float or int
For the c... | python | {
"resource": ""
} |
q252204 | parse_darknet_ann_str_to_list | validation | def parse_darknet_ann_str_to_list(annotations):
r"""Input string format of class, x, y, w, h, return list of list format.
Parameters
-----------
annotations : str
The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n".
Returns
-------
list of list of 4 number... | python | {
"resource": ""
} |
q252205 | parse_darknet_ann_list_to_cls_box | validation | def parse_darknet_ann_list_to_cls_box(annotations):
"""Parse darknet annotation format into two lists for class and bounding box.
Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...].
Parameters
------------
annotations : list of list | python | {
"resource": ""
} |
q252206 | obj_box_horizontal_flip | validation | def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False):
"""Left-right flip the image and coordinates for object detection.
Parameters
----------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 in... | python | {
"resource": ""
} |
q252207 | obj_box_imresize | validation | def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False):
"""Resize an image, and compute the new bounding box coordinates.
Parameters
-------------
im : numpy.array
An image with dimension of [row, col, channel] (default).
coords : list of list of 4 i... | python | {
"resource": ""
} |
q252208 | remove_pad_sequences | validation | def remove_pad_sequences(sequences, pad_id=0):
"""Remove padding.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
pad_id : int
The pad ID.
Returns
----------
list of list of int
The processed sequences.
Exa... | python | {
"resource": ""
} |
q252209 | sequences_get_mask | validation | def sequences_get_mask(sequences, pad_val=0):
"""Return mask for sequences.
Parameters
-----------
sequences : list of list of int
All sequences where each row is a sequence.
pad_val : int
The pad value.
Returns
----------
list of list of int
The mask.
Exam... | python | {
"resource": ""
} |
q252210 | keypoint_random_crop | validation | def keypoint_random_crop(image, annos, mask=None, size=(368, 368)):
"""Randomly crop an image and corresponding keypoints without influence scales, given by ``keypoint_random_resize_shortestedge``.
Parameters
-----------
image : 3 channel image
The given image for augmentation.
annos : list... | python | {
"resource": ""
} |
q252211 | keypoint_random_flip | validation | def keypoint_random_flip(
image, annos, mask=None, prob=0.5, flip_list=(0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16, 18)
):
"""Flip an image and corresponding keypoints.
Parameters
-----------
image : 3 channel image
The given image for augmentation.
annos : list of... | python | {
"resource": ""
} |
q252212 | keypoint_random_resize | validation | def keypoint_random_resize(image, annos, mask=None, zoom_range=(0.8, 1.2)):
"""Randomly resize an image and corresponding keypoints.
The height and width of image will be changed independently, so the scale will be changed.
Parameters
-----------
image : 3 channel image
The given image for ... | python | {
"resource": ""
} |
q252213 | discount_episode_rewards | validation | def discount_episode_rewards(rewards=None, gamma=0.99, mode=0):
"""Take 1D float array of rewards and compute discounted rewards for an
episode. When encount a non-zero value, consider as the end a of an episode.
Parameters
----------
rewards : list
List of rewards
gamma : float
... | python | {
"resource": ""
} |
q252214 | cross_entropy_reward_loss | validation | def cross_entropy_reward_loss(logits, actions, rewards, name=None):
"""Calculate the loss for Policy Gradient Network.
Parameters
----------
logits : tensor
The network outputs without softmax. This function implements softmax inside.
actions : tensor or placeholder
The agent action... | python | {
"resource": ""
} |
q252215 | log_weight | validation | def log_weight(probs, weights, name='log_weight'):
"""Log weight.
Parameters
-----------
probs : tensor
If it is a network output, usually we should scale it to [0, 1] via softmax.
weights : tensor
The weights.
Returns
--------
Tensor | python | {
"resource": ""
} |
q252216 | choice_action_by_probs | validation | def choice_action_by_probs(probs=(0.5, 0.5), action_list=None):
"""Choice and return an an action by given the action probability distribution.
Parameters
------------
probs : list of float.
The probability distribution of all actions.
action_list : None or a list of int or others
A... | python | {
"resource": ""
} |
q252217 | cross_entropy | validation | def cross_entropy(output, target, name=None):
"""Softmax cross-entropy operation, returns the TensorFlow expression of cross-entropy for two distributions,
it implements softmax internally. See ``tf.nn.sparse_softmax_cross_entropy_with_logits``.
Parameters
----------
output : Tensor
A batch... | python | {
"resource": ""
} |
q252218 | sigmoid_cross_entropy | validation | def sigmoid_cross_entropy(output, target, name=None):
"""Sigmoid cross-entropy operation, see ``tf.nn.sigmoid_cross_entropy_with_logits``.
Parameters
----------
output : Tensor
A batch of distribution with shape: [batch_size, num of classes].
target : Tensor
A batch of index with sh... | python | {
"resource": ""
} |
q252219 | binary_cross_entropy | validation | def binary_cross_entropy(output, target, epsilon=1e-8, name='bce_loss'):
"""Binary cross entropy operation.
Parameters
----------
output : Tensor
Tensor with type of `float32` or `float64`.
target : Tensor
The target distribution, format the same with `output`.
epsilon : float
... | python | {
"resource": ""
} |
q252220 | normalized_mean_square_error | validation | def normalized_mean_square_error(output, target, name="normalized_mean_squared_error_loss"):
"""Return the TensorFlow expression of normalized mean-square-error of two distributions.
Parameters
----------
output : Tensor
2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, wid... | python | {
"resource": ""
} |
q252221 | cross_entropy_seq_with_mask | validation | def cross_entropy_seq_with_mask(logits, target_seqs, input_mask, return_details=False, name=None):
"""Returns the expression of cross-entropy of two sequences, implement
softmax internally. Normally be used for Dynamic RNN with Synced sequence input and output.
Parameters
-----------
logits : Tenso... | python | {
"resource": ""
} |
q252222 | maxnorm_regularizer | validation | def maxnorm_regularizer(scale=1.0):
"""Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.
More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.
The implementation follows `TensorFlow contrib <https://github.com/... | python | {
"resource": ""
} |
q252223 | ramp | validation | def ramp(x, v_min=0, v_max=1, name=None):
"""Ramp activation function.
Parameters
----------
x : Tensor
input.
v_min : float
cap input to v_min as a lower bound.
v_max : float
cap input to v_max as a upper bound.
name : str
| python | {
"resource": ""
} |
q252224 | swish | validation | def swish(x, name='swish'):
"""Swish function.
See `Swish: a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941>`__.
Parameters
----------
x : Tensor
input.
name: str
function name (optional).
| python | {
"resource": ""
} |
q252225 | pixel_wise_softmax | validation | def pixel_wise_softmax(x, name='pixel_wise_softmax'):
"""Return the softmax outputs of images, every pixels have multiple label, the sum of a pixel is 1.
Usually be used for image segmentation.
Parameters
----------
x : Tensor
input.
- For 2d image, 4D tensor (batch_size, heigh... | python | {
"resource": ""
} |
q252226 | retrieve_seq_length_op3 | validation | def retrieve_seq_length_op3(data, pad_val=0): # HangSheng: return tensor for sequence length, if input is tf.string
"""Return tensor for sequence length, if input is ``tf.string``."""
data_shape_size = data.get_shape().ndims
if data_shape_size == 3:
return tf.reduce_sum(tf.cast(tf.reduce_any(tf.not... | python | {
"resource": ""
} |
q252227 | BasicConvLSTMCell.state_size | validation | def state_size(self):
"""State size of the LSTMStateTuple."""
| python | {
"resource": ""
} |
q252228 | DeformableConv2d._tf_repeat | validation | 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")
| python | {
"resource": ""
} |
q252229 | DeformableConv2d._tf_batch_map_coordinates | validation | 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... | python | {
"resource": ""
} |
q252230 | DeformableConv2d._tf_batch_map_offsets | validation | 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``
... | python | {
"resource": ""
} |
q252231 | minibatches | validation | 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
... | python | {
"resource": ""
} |
q252232 | TensorHub.save_model | validation | 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
... | python | {
"resource": ""
} |
q252233 | TensorHub.find_top_model | validation | 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
... | python | {
"resource": ""
} |
q252234 | TensorHub.delete_model | validation | def delete_model(self, **kwargs):
"""Delete model.
Parameters
-----------
kwargs : logging information
| python | {
"resource": ""
} |
q252235 | TensorHub.save_dataset | validation | 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.
... | python | {
"resource": ""
} |
q252236 | TensorHub.find_top_dataset | validation | 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... | python | {
"resource": ""
} |
q252237 | TensorHub.find_datasets | validation | 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... | python | {
"resource": ""
} |
q252238 | TensorHub.delete_datasets | validation | def delete_datasets(self, **kwargs):
"""Delete datasets.
Parameters
-----------
kwargs : logging information
Find items to delete, leave it empty to delete all log.
"""
| python | {
"resource": ""
} |
q252239 | TensorHub.save_training_log | validation | 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_... | python | {
"resource": ""
} |
q252240 | TensorHub.save_validation_log | validation | 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... | python | {
"resource": ""
} |
q252241 | TensorHub.delete_training_log | validation | 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... | python | {
"resource": ""
} |
q252242 | TensorHub.delete_validation_log | validation | 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
---------
- | python | {
"resource": ""
} |
q252243 | TensorHub.create_task | validation | 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 ... | python | {
"resource": ""
} |
q252244 | TensorHub.run_top_task | validation | 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 ... | python | {
"resource": ""
} |
q252245 | TensorHub.delete_tasks | validation | 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() | python | {
"resource": ""
} |
q252246 | TensorHub.check_unfinished_task | validation | 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... | python | {
"resource": ""
} |
q252247 | augment_with_ngrams | validation | 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)])) | python | {
"resource": ""
} |
q252248 | load_and_preprocess_imdb_data | validation | 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:
| python | {
"resource": ""
} |
q252249 | read_image | validation | def read_image(image, path=''):
"""Read one image.
Parameters
-----------
image : str
The image file name.
path : str
The image folder path.
Returns
-------
| python | {
"resource": ""
} |
q252250 | read_images | validation | 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... | python | {
"resource": ""
} |
q252251 | save_image | validation | def save_image(image, image_path='_temp.png'):
"""Save a image.
Parameters
-----------
image : numpy array
[w, h, c]
image_path : str
path
"""
try: # RGB
| python | {
"resource": ""
} |
q252252 | save_images | validation | 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]
... | python | {
"resource": ""
} |
q252253 | draw_boxes_and_labels_to_image | validation | 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
... | python | {
"resource": ""
} |
q252254 | CNN2d | validation | 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... | python | {
"resource": ""
} |
q252255 | tsne_embedding | validation | 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... | python | {
"resource": ""
} |
q252256 | draw_weights | validation | 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... | python | {
"resource": ""
} |
q252257 | data_to_tfrecord | validation | 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... | python | {
"resource": ""
} |
q252258 | read_and_decode | validation | 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... | python | {
"resource": ""
} |
q252259 | Layer.print_params | validation | 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 ... | python | {
"resource": ""
} |
q252260 | Layer.print_layers | validation | 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(
| python | {
"resource": ""
} |
q252261 | Layer.count_params | validation | 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)
| python | {
"resource": ""
} |
q252262 | Layer.get_all_params | validation | 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:
| python | {
"resource": ""
} |
q252263 | Layer._get_init_args | validation | 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... | python | {
"resource": ""
} |
q252264 | roi_pooling | validation | 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... | python | {
"resource": ""
} |
q252265 | prefetch_input_data | validation | 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... | python | {
"resource": ""
} |
q252266 | batch_with_dynamic_pad | validation | 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... | python | {
"resource": ""
} |
q252267 | _bias_scale | validation | def _bias_scale(x, b, data_format):
"""The multiplication counter part of tf.nn.bias_add."""
if data_format == 'NHWC':
| python | {
"resource": ""
} |
q252268 | _bias_add | validation | def _bias_add(x, b, data_format):
"""Alternative implementation of tf.nn.bias_add which is compatiable with tensorRT."""
if data_format == 'NHWC': | python | {
"resource": ""
} |
q252269 | batch_normalization | validation | 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... | python | {
"resource": ""
} |
q252270 | compute_alpha | validation | 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 | python | {
"resource": ""
} |
q252271 | flatten_reshape | validation | 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 :... | python | {
"resource": ""
} |
q252272 | get_layers_with_name | validation | 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
... | python | {
"resource": ""
} |
q252273 | get_variables_with_name | validation | 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... | python | {
"resource": ""
} |
q252274 | initialize_rnn_state | validation | 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.
| python | {
"resource": ""
} |
q252275 | list_remove_repeat | validation | 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
----------
| python | {
"resource": ""
} |
q252276 | ternary_operation | validation | 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)
| python | {
"resource": ""
} |
q252277 | _add_notice_to_docstring | validation | 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 | python | {
"resource": ""
} |
q252278 | alphas | validation | 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... | python | {
"resource": ""
} |
q252279 | predict | validation | 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... | python | {
"resource": ""
} |
q252280 | evaluation | validation | 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... | python | {
"resource": ""
} |
q252281 | get_random_int | validation | 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... | python | {
"resource": ""
} |
q252282 | exit_tensorflow | validation | 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... | python | {
"resource": ""
} |
q252283 | open_tensorboard | validation | 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, ... | python | {
"resource": ""
} |
q252284 | clear_all_placeholder_variables | validation | 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... | python | {
"resource": ""
} |
q252285 | set_gpu_fraction | validation | 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... | python | {
"resource": ""
} |
q252286 | generate_skip_gram_batch | validation | 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... | python | {
"resource": ""
} |
q252287 | sample | validation | 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 ... | python | {
"resource": ""
} |
q252288 | sample_top | validation | 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 | python | {
"resource": ""
} |
q252289 | create_vocab | validation | 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
... | python | {
"resource": ""
} |
q252290 | read_words | validation | 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... | python | {
"resource": ""
} |
q252291 | read_analogies_file | validation | 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... | python | {
"resource": ""
} |
q252292 | build_reverse_dictionary | validation | 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 | python | {
"resource": ""
} |
q252293 | build_words_dataset | validation | 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... | python | {
"resource": ""
} |
q252294 | save_vocab | validation | def save_vocab(count=None, name='vocab.txt'):
"""Save the vocabulary to a file so the model can be reloaded.
Parameters
----------
count : a list of tuple and list
count[0] is a list : the number of rare words,
count[1:] are tuples : the number of occurrence of each word,
e.g. [... | python | {
"resource": ""
} |
q252295 | sentence_to_token_ids | validation | def sentence_to_token_ids(
sentence, vocabulary, tokenizer=None, normalize_digits=True, UNK_ID=3, _DIGIT_RE=re.compile(br"\d")
):
"""Convert a string to list of integers representing token-ids.
For example, a sentence "I have a dog" may become tokenized into
["I", "have", "a", "dog"] and with vocab... | python | {
"resource": ""
} |
q252296 | data_to_token_ids | validation | def data_to_token_ids(
data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True, UNK_ID=3,
_DIGIT_RE=re.compile(br"\d")
):
"""Tokenize data file and turn into token-ids using given vocabulary file.
This function loads data line-by-line from data_path, calls the above
s... | python | {
"resource": ""
} |
q252297 | moses_multi_bleu | validation | def moses_multi_bleu(hypotheses, references, lowercase=False):
"""Calculate the bleu score for hypotheses and references
using the MOSES ulti-bleu.perl script.
Parameters
------------
hypotheses : numpy.array.string
A numpy array of strings where each string is a single example.
referen... | python | {
"resource": ""
} |
q252298 | SimpleVocabulary.word_to_id | validation | def word_to_id(self, word):
"""Returns the integer id of a word string."""
if word in self._vocab:
| python | {
"resource": ""
} |
q252299 | Vocabulary.word_to_id | validation | def word_to_id(self, word):
"""Returns the integer word id of a word string."""
if word in self.vocab:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.