1. 程式人生 > >tensorflow-條件循環控制(1)

tensorflow-條件循環控制(1)

urn import ESS optional one port eat != entity

TensorFlow 提供了一些操作和類,您可以使用它們來控制操作的執行,並向圖表添加條件依賴項。

tf.identity
tf.tuple
tf.group
tf.no_op
tf.count_up_to
tf.cond
tf.case
tf.while_loop

tf.identity

?
tf.identity(
? ? input,
? ? name=None
)

返回和輸入大小與內容一致的tensor

參數:

input: 一個Tensor.
name: 操作名字(可選)
這個方法的源碼:

def identity(input, name=None):  # pylint: disable=redefined-builtin
  r"""Return a tensor with the same shape and contents as input.
  Args:
    input: A `Tensor`.
    name: A name for the operation (optional).
  Returns:
    A `Tensor`. Has the same type as `input`.
  """
  if context.executing_eagerly():
    input = ops.convert_to_tensor(input)
    in_device = input.device

    # TODO(ashankar): Does ‘identity‘ need to invoke execution callbacks?
    context_device = context.context().device_name
    if not context_device:
      context_device = "/job:localhost/replica:0/task:0/device:CPU:0"
    if context_device != in_device:
      return input._copy()  # pylint: disable=protected-access
    return input
  else:
    return gen_array_ops.identity(input, name=name)

從源碼可看出,input的device會與context.context()相比較,如果相同,則直接返回input,如果不相同則返回disable=protected-access權限的input的copy。

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018
@author: myhaspl
"""

import tensorflow as tf
x1 = tf.constant(2.)
x2 = [1,2,3]
y1=tf.identity(x1,name="my_y1")
y2=tf.identity(x2,name="my_y")
sess=tf.Session()
with sess: 
    print sess.run(y1)
    print sess.run(y2)
2.0
[1 2 3]

tensorflow-條件循環控制(1)