Fel*_*x L 2 for-loop vectorization multidimensional-array tensorflow tensor
我是张量流新手,我想使用多个 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
Run Code Online (Sandbox Code Playgroud)
之后我仍然想使用张量计算loos函数,然后进入下一个循环进行训练。有谁知道如何做到这一点?我知道如何在会话中以单一方式执行此操作。但我不知道如何在训练循环中做到这一点。
您的特定示例很容易矢量化,因此实际上不需要通过 for 循环来完成它。这是纯张量流解决方案:
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
一个完整的可运行示例:
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}))
Run Code Online (Sandbox Code Playgroud)
输出:
[[10. 5. 15.]
[61. 62. 63.]
[ 4. 4. 10.]]
[[10. 5. 15.]
[61. 62. 63.]
[ 4. 4. 10.]]
Run Code Online (Sandbox Code Playgroud)