本文整理汇总了Python中tensorflow.range方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.range方法的具体用法?Python tensorflow.range怎么用?Python tensorflow.range使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.range方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stp_transformation
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def stp_transformation(prev_image, stp_input, num_masks):
"""Apply spatial transformer predictor (STP) to previous image.
Args:
prev_image: previous image to be transformed.
stp_input: hidden layer to be used for computing STN parameters.
num_masks: number of masks and hence the number of STP transformations.
Returns:
List of images transformed by the predicted STP parameters.
"""
# Only import spatial transformer if needed.
from spatial_transformer import transformer
identity_params = tf.convert_to_tensor(
np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0], np.float32))
transformed = []
for i in range(num_masks - 1):
params = slim.layers.fully_connected(
stp_input, 6, scope='stp_params' + str(i),
activation_fn=None) + identity_params
transformed.append(transformer(prev_image, params))
return transformed
示例2: scheduled_sample
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def scheduled_sample(ground_truth_x, generated_x, batch_size, num_ground_truth):
"""Sample batch with specified mix of ground truth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
num_ground_truth: number of ground-truth examples to include in batch.
Returns:
New batch with num_ground_truth sampled from ground_truth_x and the rest
from generated_x.
"""
idx = tf.random_shuffle(tf.range(int(batch_size)))
ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))
generated_idx = tf.gather(idx, tf.range(num_ground_truth, int(batch_size)))
ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)
generated_examps = tf.gather(generated_x, generated_idx)
return tf.dynamic_stitch([ground_truth_idx, generated_idx],
[ground_truth_examps, generated_examps])
示例3: clip_tensor
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def clip_tensor(t, length):
"""Clips the input tensor along the first dimension up to the length.
Args:
t: the input tensor, assuming the rank is at least 1.
length: a tensor of shape [1] or an integer, indicating the first dimension
of the input tensor t after clipping, assuming length <= t.shape[0].
Returns:
clipped_t: the clipped tensor, whose first dimension is length. If the
length is an integer, the first dimension of clipped_t is set to length
statically.
"""
clipped_t = tf.gather(t, tf.range(length))
if not _is_tensor(length):
clipped_t = _set_dim_0(clipped_t, length)
return clipped_t
示例4: _define_experience
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def _define_experience(self, observ, action, reward):
"""Implement the branch of experience() entered during training."""
update_filters = tf.summary.merge([
self._observ_filter.update(observ),
self._reward_filter.update(reward)])
with tf.control_dependencies([update_filters]):
if self._config.train_on_agent_action:
# NOTE: Doesn't seem to change much.
action = self._last_action
batch = observ, action, self._last_mean, self._last_logstd, reward
append = self._episodes.append(batch, tf.range(len(self._batch_env)))
with tf.control_dependencies([append]):
norm_observ = self._observ_filter.transform(observ)
norm_reward = tf.reduce_mean(self._reward_filter.transform(reward))
# pylint: disable=g-long-lambda
summary = tf.cond(self._should_log, lambda: tf.summary.merge([
update_filters,
self._observ_filter.summary(),
self._reward_filter.summary(),
tf.summary.scalar('memory_size', self._memory_index),
tf.summary.histogram('normalized_observ', norm_observ),
tf.summary.histogram('action', self._last_action),
tf.summary.scalar('normalized_reward', norm_reward)]), str)
return summary
示例5: _update_value
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def _update_value(self, observ, reward, length):
"""Perform multiple update steps of the value baseline.
We need to decide for the summary of one iteration, and thus choose the one
after half of the iterations.
Args:
observ: Sequences of observations.
reward: Sequences of reward.
length: Batch of sequence lengths.
Returns:
Summary tensor.
"""
with tf.name_scope('update_value'):
loss, summary = tf.scan(
lambda _1, _2: self._update_value_step(observ, reward, length),
tf.range(self._config.update_epochs_value),
[0., ''], parallel_iterations=1)
print_loss = tf.Print(0, [tf.reduce_mean(loss)], 'value loss: ')
with tf.control_dependencies([loss, print_loss]):
return summary[self._config.update_epochs_value // 2]
示例6: _mask
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def _mask(self, tensor, length):
"""Set padding elements of a batch of sequences to zero.
Useful to then safely sum along the time dimension.
Args:
tensor: Tensor of sequences.
length: Batch of sequence lengths.
Returns:
Masked sequences.
"""
with tf.name_scope('mask'):
range_ = tf.range(tensor.shape[1].value)
mask = tf.cast(range_[None, :] < length[:, None], tf.float32)
masked = tensor * mask
return tf.check_numerics(masked, 'masked')
示例7: replace
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def replace(self, episodes, length, rows=None):
"""Replace full episodes.
Args:
episodes: Tuple of transition quantities with batch and time dimensions.
length: Batch of sequence lengths.
rows: Episodes to replace, defaults to all.
Returns:
Operation.
"""
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
assert_capacity = tf.assert_less(
rows, self._capacity, message='capacity exceeded')
with tf.control_dependencies([assert_capacity]):
assert_max_length = tf.assert_less_equal(
length, self._max_length, message='max length exceeded')
replace_ops = []
with tf.control_dependencies([assert_max_length]):
for buffer_, elements in zip(self._buffers, episodes):
replace_op = tf.scatter_update(buffer_, rows, elements)
replace_ops.append(replace_op)
with tf.control_dependencies(replace_ops):
return tf.scatter_update(self._length, rows, length)
示例8: data
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def data(self, rows=None):
"""Access a batch of episodes from the memory.
Padding elements after the length of each episode are unspecified and might
contain old data.
Args:
rows: Episodes to select, defaults to all.
Returns:
Tuple containing a tuple of transition quantiries with batch and time
dimensions, and a batch of sequence lengths.
"""
rows = tf.range(self._capacity) if rows is None else rows
assert rows.shape.ndims == 1
episode = [tf.gather(buffer_, rows) for buffer_ in self._buffers]
length = tf.gather(self._length, rows)
return episode, length
示例9: reset
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def reset(self, indices=None):
"""Reset the batch of environments.
Args:
indices: The batch indices of the environments to reset; defaults to all.
Returns:
Batch tensor of the new observations.
"""
if indices is None:
indices = tf.range(len(self._batch_env))
observ_dtype = self._parse_dtype(self._batch_env.observation_space)
observ = tf.py_func(
self._batch_env.reset, [indices], observ_dtype, name='reset')
observ = tf.check_numerics(observ, 'observ')
reward = tf.zeros_like(indices, tf.float32)
done = tf.zeros_like(indices, tf.bool)
with tf.control_dependencies([
tf.scatter_update(self._observ, indices, observ),
tf.scatter_update(self._reward, indices, reward),
tf.scatter_update(self._done, indices, done)]):
return tf.identity(observ)
示例10: simulate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def simulate(self, action):
with tf.name_scope("environment/simulate"): # Do we need this?
initializer = (tf.zeros_like(self._observ),
tf.fill((len(self),), 0.0), tf.fill((len(self),), False))
def not_done_step(a, _):
reward, done = self._batch_env.simulate(action)
with tf.control_dependencies([reward, done]):
# TODO(piotrmilos): possibly ignore envs with done
r0 = tf.maximum(a[0], self._batch_env.observ)
r1 = tf.add(a[1], reward)
r2 = tf.logical_or(a[2], done)
return (r0, r1, r2)
simulate_ret = tf.scan(not_done_step, tf.range(self.skip),
initializer=initializer, parallel_iterations=1,
infer_shape=False)
simulate_ret = [ret[-1, ...] for ret in simulate_ret]
with tf.control_dependencies([self._observ.assign(simulate_ret[0])]):
return tf.identity(simulate_ret[1]), tf.identity(simulate_ret[2])
示例11: scheduled_sample
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def scheduled_sample(self,
ground_truth_x,
generated_x,
batch_size,
num_ground_truth):
"""Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data points.
batch_size: batch size
num_ground_truth: number of ground-truth examples to include in batch.
Returns:
New batch with num_ground_truth sampled from ground_truth_x and the rest
from generated_x.
"""
idx = tf.random_shuffle(tf.range(batch_size))
ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))
generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_size))
ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)
generated_examps = tf.gather(generated_x, generated_idx)
return tf.dynamic_stitch([ground_truth_idx, generated_idx],
[ground_truth_examps, generated_examps])
示例12: stacked_lstm
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def stacked_lstm(self, inputs, states, hidden_size, output_size, nlayers):
"""Stacked LSTM layers with FC layers as input and output embeddings.
Args:
inputs: input tensor
states: a list of internal lstm states for each layer
hidden_size: number of lstm units
output_size: size of the output
nlayers: number of lstm layers
Returns:
net: output of the network
skips: a list of updated lstm states for each layer
"""
net = inputs
net = slim.layers.fully_connected(
net, hidden_size, activation_fn=None, scope="af1")
for i in range(nlayers):
net, states[i] = self.basic_lstm(
net, states[i], hidden_size, scope="alstm%d"%i)
net = slim.layers.fully_connected(
net, output_size, activation_fn=tf.tanh, scope="af2")
return net, states
示例13: lstm_gaussian
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def lstm_gaussian(self, inputs, states, hidden_size, output_size, nlayers):
"""Stacked LSTM layers with FC layer as input and gaussian as output.
Args:
inputs: input tensor
states: a list of internal lstm states for each layer
hidden_size: number of lstm units
output_size: size of the output
nlayers: number of lstm layers
Returns:
mu: mean of the predicted gaussian
logvar: log(var) of the predicted gaussian
skips: a list of updated lstm states for each layer
"""
net = inputs
net = slim.layers.fully_connected(net, hidden_size,
activation_fn=None, scope="bf1")
for i in range(nlayers):
net, states[i] = self.basic_lstm(
net, states[i], hidden_size, scope="blstm%d"%i)
mu = slim.layers.fully_connected(
net, output_size, activation_fn=None, scope="bf2mu")
logvar = slim.layers.fully_connected(
net, output_size, activation_fn=None, scope="bf2log")
return mu, logvar, states
示例14: get_timing_signal
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def get_timing_signal(length,
min_timescale=1,
max_timescale=1e4,
num_timescales=16):
"""Create Tensor of sinusoids of different frequencies.
Args:
length: Length of the Tensor to create, i.e. Number of steps.
min_timescale: a float
max_timescale: a float
num_timescales: an int
Returns:
Tensor of shape (length, 2*num_timescales)
"""
positions = tf.to_float(tf.range(length))
log_timescale_increment = (
math.log(max_timescale / min_timescale) / (num_timescales - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = tf.expand_dims(positions, 1) * tf.expand_dims(inv_timescales, 0)
return tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
示例15: smoothing_cross_entropy_factored
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import range [as 别名]
def smoothing_cross_entropy_factored(a, b, labels, confidence):
"""Memory-efficient computation of smoothing cross-entropy.
Avoids realizing the entire logits matrix at once.
Args:
a: a Tensor with shape [batch, inner_dim]
b: a Tensor with shape [vocab_size, inner_dim]
labels: an integer Tensor with shape [batch]
confidence: a float
Returns:
A Tensor with shape [batch]
"""
num_splits = 16
vocab_size = shape_list(b)[0]
labels = approximate_split(labels, num_splits)
a = approximate_split(a, num_splits)
parts = []
for part in range(num_splits):
with tf.control_dependencies(parts[-1:]):
logits = tf.matmul(a[part], b, transpose_b=True)
parts.append(
smoothing_cross_entropy(logits, labels[part], vocab_size, confidence))
return tf.concat(parts, 0)