gpt4 book ai didi

Tensorflow 中张量的 For 循环

转载 作者:行者123 更新时间:2023-12-02 03:41:02 26 4
gpt4 key购买 nike

我是 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函数,然后进入下一个循环进行训练。有谁知道如何做到这一点?我知道如何在 session 中以单一方式执行此操作。但我不知道如何在训练循环中做到这一点。

最佳答案

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.]]

关于Tensorflow 中张量的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com