本文整理汇总了Python中tensorflow.identity方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.identity方法的具体用法?Python tensorflow.identity怎么用?Python tensorflow.identity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.identity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_forward
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def build_forward(self):
verbalise = self.FLAGS.verbalise
# Placeholders
inp_size = [None] + self.meta['inp_size']
self.inp = tf.placeholder(tf.float32, inp_size, 'input')
self.feed = dict() # other placeholders
# Build the forward pass
state = identity(self.inp)
roof = self.num_layer - self.ntrain
self.say(HEADER, LINE)
for i, layer in enumerate(self.darknet.layers):
scope = '{}-{}'.format(str(i),layer.type)
args = [layer, state, i, roof, self.feed]
state = op_create(*args)
mess = state.verbalise()
self.say(mess)
self.say(LINE)
self.top = state
self.out = tf.identity(state.out, name='output')
示例2: autosummary
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def autosummary(name, value):
id = name.replace('/', '_')
if is_tf_expression(value):
with tf.name_scope('summary_' + id), tf.device(value.device):
update_op = _create_autosummary_var(name, value)
with tf.control_dependencies([update_op]):
return tf.identity(value)
else: # python scalar or numpy array
if name not in _autosummary_immediate:
with absolute_name_scope('Autosummary/' + id), tf.device(None), tf.control_dependencies(None):
update_value = tf.placeholder(tf.float32)
update_op = _create_autosummary_var(name, update_value)
_autosummary_immediate[name] = update_op, update_value
update_op, update_value = _autosummary_immediate[name]
run(update_op, {update_value: np.float32(value)})
return value
# Create the necessary ops to include autosummaries in TensorBoard report.
# Note: This should be done only once per graph.
示例3: _lm_loss
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def _lm_loss(self,
inputs,
emb_key='lm_embedded',
lstm_layer='lstm',
lm_loss_layer='lm_loss',
loss_name='lm_loss',
compute_loss=True):
embedded = self.layers['embedding'](inputs.tokens)
self.tensors[emb_key] = embedded
lstm_out, next_state = self.layers[lstm_layer](embedded, inputs.state,
inputs.length)
if compute_loss:
loss = self.layers[lm_loss_layer](
[lstm_out, inputs.labels, inputs.weights])
with tf.control_dependencies([inputs.save_state(next_state)]):
loss = tf.identity(loss)
tf.summary.scalar(loss_name, loss)
return loss
示例4: build_structured_training
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def build_structured_training(self, state, network_states):
"""Builds a beam search based training loop for this component.
The default implementation builds a dummy graph and raises a
TensorFlow runtime exception to indicate that structured training
is not implemented.
Args:
state: MasterState from the 'AdvanceMaster' op that advances the
underlying master to this component.
network_states: dictionary of component NetworkState objects.
Returns:
(handle, cost, correct, total) -- These are TF ops corresponding
to the final handle after unrolling, the total cost, and the
total number of actions. Since the number of correctly predicted
actions is not applicable in the structured training setting, a
dummy value should returned.
"""
del network_states # Unused.
with tf.control_dependencies([tf.Assert(False, ['Not implemented.'])]):
handle = tf.identity(state.handle)
cost = tf.constant(0.)
correct, total = tf.constant(0), tf.constant(0)
return handle, cost, correct, total
示例5: _update_value_step
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def _update_value_step(self, observ, reward, length):
"""Compute the current value loss and perform a gradient update step.
Args:
observ: Sequences of observations.
reward: Sequences of reward.
length: Batch of sequence lengths.
Returns:
Tuple of loss tensor and summary tensor.
"""
loss, summary = self._value_loss(observ, reward, length)
gradients, variables = (
zip(*self._value_optimizer.compute_gradients(loss)))
optimize = self._value_optimizer.apply_gradients(
zip(gradients, variables))
summary = tf.summary.merge([
summary,
tf.summary.scalar('gradient_norm', tf.global_norm(gradients)),
utility.gradient_summaries(
zip(gradients, variables), dict(value=r'.*'))])
with tf.control_dependencies([optimize]):
return [tf.identity(loss), tf.identity(summary)]
示例6: reset
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [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)
示例7: simulate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def simulate(self, action):
# There is subtlety here. We need to collect data
# obs, action = policy(obs), done, reward = env(abs, action)
# Thus we need to enqueue data before assigning new observation
reward, done = self._batch_env.simulate(action)
with tf.control_dependencies([reward, done]):
enqueue_op = self.speculum.enqueue(
[self._observ.read_value(), reward, done, action])
with tf.control_dependencies([enqueue_op]):
assign = self._observ.assign(self._batch_env.observ)
with tf.control_dependencies([assign]):
return tf.identity(reward), tf.identity(done)
示例8: simulate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [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])
示例9: simulate
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def simulate(self, action):
"""Step the batch of environments.
The results of the step can be accessed from the variables defined below.
Args:
action: Tensor holding the batch of actions to apply.
Returns:
Operation.
"""
with tf.name_scope('environment/simulate'):
if action.dtype in (tf.float16, tf.float32, tf.float64):
action = tf.check_numerics(action, 'action')
observ_dtype = utils.parse_dtype(self._batch_env.observation_space)
observ, reward, done = tf.py_func(
lambda a: self._batch_env.step(a)[:3], [action],
[observ_dtype, tf.float32, tf.bool], name='step')
observ = tf.check_numerics(observ, 'observ')
reward = tf.check_numerics(reward, 'reward')
reward.set_shape((len(self),))
done.set_shape((len(self),))
with tf.control_dependencies([self._observ.assign(observ)]):
return tf.identity(reward), tf.identity(done)
示例10: _reset_non_empty
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def _reset_non_empty(self, indices):
"""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.
"""
observ_dtype = utils.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')
with tf.control_dependencies([
tf.scatter_update(self._observ, indices, observ)]):
return tf.identity(observ)
示例11: weight_decay_and_noise
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
"""Apply weight decay and weight noise."""
if var_list is None:
var_list = tf.trainable_variables()
decay_vars = [v for v in var_list]
noise_vars = [v for v in var_list if "/body/" in v.name]
weight_decay_loss = weight_decay(hparams.weight_decay, decay_vars)
if hparams.weight_decay:
tf.summary.scalar("losses/weight_decay", weight_decay_loss)
weight_noise_ops = weight_noise(hparams.weight_noise, learning_rate,
noise_vars)
with tf.control_dependencies(weight_noise_ops):
loss = tf.identity(loss)
loss += weight_decay_loss
return loss
示例12: get_channel_embeddings
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def get_channel_embeddings(self,
io_depth,
targets,
hidden_size,
name="channel"):
"""Get separate embedding for each of the channels."""
targets_split = tf.split(targets, io_depth, axis=3)
rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name,
[256 * io_depth, hidden_size])
rgb_embedding_var = tf.identity(rgb_embedding_var)
rgb_embedding_var *= float(hidden_size)**0.5
channel_target_embs = []
for i in range(io_depth):
# Adding the channel offsets to get the right embedding since the
# embedding tensor has shape 256 * io_depth, hidden_size
target_ids = tf.squeeze(targets_split[i], axis=3) + i * 256
target_embs = common_layers.gather(rgb_embedding_var, target_ids)
channel_target_embs.append(target_embs)
return tf.concat(channel_target_embs, axis=-1)
示例13: get_channel_embeddings
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def get_channel_embeddings(io_depth, targets, hidden_size, name="channel"):
"""Get separate embedding for each of the channels."""
targets_split = tf.split(targets, io_depth, axis=3)
rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name,
[256 * io_depth, hidden_size])
rgb_embedding_var = tf.identity(rgb_embedding_var)
rgb_embedding_var *= float(hidden_size)**0.5
channel_target_embs = []
for i in range(io_depth):
# Adding the channel offsets to get the right embedding since the
# embedding tensor has shape 256 * io_depth, hidden_size
target_ids = tf.squeeze(targets_split[i], axis=3) + i * 256
target_embs = common_layers.gather(rgb_embedding_var, target_ids)
channel_target_embs.append(target_embs)
return tf.concat(channel_target_embs, axis=-1)
示例14: calculate_mmd
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def calculate_mmd(x, y, param, batch_size):
xt = tf.transpose(x)
yt = tf.transpose(y)
x0 = tf.identity(x)
y0 = tf.identity(y)
x1 = tf.identity(xt)
y1 = tf.identity(yt)
for i in range(batch_size - 1):
x0 = tf.concat([x0, x], axis=1)
y0 = tf.concat([y0, y], axis=1)
x1 = tf.concat([x1, xt], axis=0)
y1 = tf.concat([y1, yt], axis=0)
gaussian_mmd = calculate_gaussian_mmd(x0, y0, x1, y1, param, batch_size)
logistic_mmd = calculate_logistic_mmd(x0, y0, x1, y1, param, batch_size)
mmd = param['logistic'] * logistic_mmd + param['gaussian'] * gaussian_mmd
return mmd
示例15: build_forward
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import identity [as 别名]
def build_forward(self):
verbalise = self.FLAGS.verbalise
# Placeholders
inp_size = [None] + self.meta['inp_size']
self.inp = tf.placeholder(tf.float32, inp_size, 'input')
self.feed = dict() # other placeholders
# Build the forward pass
state = identity(self.inp)
roof = self.num_layer - self.ntrain
self.say(HEADER, LINE)
for i, layer in enumerate(self.darknet.layers):
scope = '{}-{}'.format(str(i), layer.type)
args = [layer, state, i, roof, self.feed]
state = op_create(*args)
mess = state.verbalise()
self.say(mess)
self.say(LINE)
self.top = state
self.out = tf.identity(state.out, name='output')