tensorflowエッセイ-条件サイクル制御(1)

3164 ワード

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のデバイスはcontextと表示されます.context()を比較すると、同じ場合はinputを直接返し、異なる場合はdisable=protected-access権限のinputのcopyを返します.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018

"""

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]
tf.tuple(メタグループ)
tf.tuple( tensors, name=None, control_inputs=None )
複数のtensorをグループにマージします.
これにより、複数のテンソルパラメータと同じ値を持つテンソルメタグループが作成されます.ただし、各テンソルの値は、すべてのテンソルの値を計算した後にのみ返されます.
control_Inputsには追加のOPSが含まれており、OPが完了する前に完了する必要がありますが、その出力は返されません.
これは、パラレル計算の「接続」メカニズムとして使用できます.すべてのパラメータテンソルはパラレル計算できますが、すべてのパラレル計算が完了した後、メタグループが返す任意のテンソルの値は使用できます.
.
パラメータ:tensors:マルチtensorのリストまたはIndexedSlices、一部のエントリはNoneである可能性があります.name:(オプション)アクションのname_scopeの名前として使用します.control_inputs:戻る前に追加のアクションテーブルの戻りを完了します.
tensorsのように
Raises:
ValueError:tensorsにtensorまたはIndexedSlicesが含まれていない場合.TypeError:control_inputsはOperationオブジェクトまたはTensorオブジェクトのリストではありません.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 11:16:32 2018
@author: myhaspl
"""

import tensorflow as tf
x1 = tf.random_normal([1000,1000],mean=100)
x2 = tf.random_normal([1000,1000],mean=100)
x3 = tf.random_normal([1000,1000],mean=100)

y1 = tf.sqrt(x1)
y2 = tf.sqrt(x2)
y3 = tf.sqrt(x3)
z = tf.tuple([y1,y2,y3])

sess=tf.Session()
with sess: 
    res=sess.run(z)
    print res[0]

[[ 9.989998 9.980425 9.897268 … 10.010141 10.008263 10.005144] [ 9.970587 9.988404 10.011098 … 10.027785 9.956984 10.110886] [ 9.982615 9.952952 10.033136 … 9.999784 10.009718 9.915539] … [ 9.934934 9.926054 10.045075 … 10.0579 10.020126 9.959899] [10.031994 10.059689 10.05442 … 10.009988 9.977903 10.036525] [ 9.945853 9.955557 10.047363 … 10.067215 9.942139 10.06124 ]]