tf.group 和 tensorflow 集合有什么不同?

Sou*_*uck 3 python machine-learning deep-learning tensorflow

我是 tensorflow 的新手

有两种方法可以同时运行多个张量。使用collectionandtf.gruop 但我不确定有两个区别

举个简单的例子

const0=tf.constant(8)
const1=tf.constant(11)

tf.add_to_collection('my_collection' , const0)
tf.add_to_collection('my_collection' , const1)

#or 
tf.group(const0 , const1)
Run Code Online (Sandbox Code Playgroud)

下面的代码是Mandelbrot fractal由 tensorflow 实现的 顺便说一句,使用tf.group和执行的代码没有区别collection

#step = tf.group(
#  tf.assign(zs, zs_add),
#  tf.assign_add(ns, zs_cast)
#)

#tf.add_to_collection('my_collection',tf.assign(zs, zs_add))
#tf.add_to_collection('my_collection',(ns, zs_cast))
#step = tf.get_collection('my_collection')
#

import tensorflow as tf
import numpy as np 
import matplotlib.pyplot as plt

# Concept
# input initial value
#Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]
Y, X = np.mgrid[-1.3:1.3:0.005, -2:1:0.005]

init_value = X + 1j*Y

#
xs = tf.constant(init_value )
zs = tf.Variable(xs)
zs_zeros = tf.zeros_like(xs, tf.float32)
ns = tf.Variable(zs_zeros)

zs_squre = tf.multiply(zs,zs)
zs_add = tf.add(zs_squre , xs)
zs_abs = tf.abs(zs_add)

zs_less = tf.math.less(zs_abs , 4)
zs_cast = tf.cast(zs_less , tf.float32)

#
step = tf.group(
  tf.assign(zs, zs_add),
  tf.assign_add(ns, zs_cast)
)


#
sess = tf.Session()
sess.run(tf.global_variables_initializer())

for i in range(200):
    sess.run(step)
value = sess.run(ns)
plt.imshow(value)
plt.show()
Run Code Online (Sandbox Code Playgroud)

所以这是我的问题
是什么是差异tf.groupcollection?谢谢你!

nes*_*uno 5

tf.group在计算图内创建一个操作,一旦评估,就会执行组中的所有张量:

op = tf.group(a,b)
Run Code Online (Sandbox Code Playgroud)

tf.add_to_collection相反,创建一组不在计算图中的操作,而只在 python 脚本中。

tf.add_to_collection('coll', a)
tf.add_to_collection('coll', b)
Run Code Online (Sandbox Code Playgroud)

您可以通过查看op和 `tf.get_collection('coll')的描述来看到这一点:

  • 操作: <tf.Operation 'group_deps' type=NoOp>
  • tf.get_collection: [<tf.Tensor 'Const:0' shape=() dtype=int32>, <tf.Tensor 'Const_1:0' shape=() dtype=int32>]

在你的榜样,使用tf.grouptf.add_to_collection+tf.get_collection是一样的:你只需要在所有的并行执行,因此操作sess.run(op)sess.run(tf.get_collection('coll'))具有相同的行为。

但是在导出计算图的情况下(这只是让您了解可能情况的示例),您不能依赖 python 列表,因此您必须使用 tf.group