Tensorflow 中张量中的 For 循环

For-loop in a tensor in Tensorflow

我是 tensorflow 的新手,我想使用一些 if-else 条件来制作一个张量。我只是不知道该怎么做。

在 python 中,如果张量类似于 [3,3,3],我可以使用 for 循环,如下所示:

for i in range(3):
   for j in range(3):
      for k in range(3):
         if tensor[i,j,k]>10:
            tensor[i,j,k]=tensor[i,j,k]-10
         elif tensor[i,j,k]<4:
            tensor[i,j,k]=tensor[i,j,k]+60

在这之后我仍然想用张量计算loos函数,然后进入下一个循环进行训练。 有谁知道如何做到这一点? 我知道如何在会话中以单一方式执行此操作。但是我不知道如何在训练循环中做到这一点。

Tensorflow 方式

您的特定示例很容易向量化,因此没有必要通过 for 循环来完成。这是纯 tensorflow 解决方案:

x = tf.placeholder(shape=[3, 3], dtype=tf.float32)
cond1 = tf.where(x > 10, x - 10, tf.zeros_like(x))
cond2 = tf.where(x < 4, x + 60, tf.zeros_like(x))
cond3 = tf.where(tf.logical_and(x >= 4, x <= 10), x, tf.zeros_like(x))
y = cond1 + cond2 + cond3

py_func 方式

如果碰巧你必须进行细粒度处理,你总是可以回退到 tf.py_func:

def process(tensor):
  mask1 = tensor > 10
  mask2 = tensor < 4
  tensor[mask1] -= 10
  tensor[mask2] += 60
  return tensor
z = tf.py_func(process, [x], tf.float32)

将它们结合在一起

完整的可运行示例:

import tensorflow as tf

x = tf.placeholder(shape=[3, 3], dtype=tf.float32)

cond1 = tf.where(x > 10, x - 10, tf.zeros_like(x))
cond2 = tf.where(x < 4, x + 60, tf.zeros_like(x))
cond3 = tf.where(tf.logical_and(x >= 4, x <= 10), x, tf.zeros_like(x))
y = cond1 + cond2 + cond3

def process(tensor):
  mask1 = tensor > 10
  mask2 = tensor < 4
  tensor[mask1] -= 10
  tensor[mask2] += 60
  return tensor
z = tf.py_func(process, [x], tf.float32)

sample = [[10, 15, 25], [1, 2, 3], [4, 4, 10]]
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  print(sess.run(y, feed_dict={x: sample}))
  print(sess.run(z, feed_dict={x: sample}))

输出:

[[10.  5. 15.]
 [61. 62. 63.]
 [ 4.  4. 10.]]
[[10.  5. 15.]
 [61. 62. 63.]
 [ 4.  4. 10.]]