作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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 中以单一方式执行此操作。但我不知道如何在训练循环中做到这一点。
最佳答案
您的特定示例很容易矢量化,因此不需要通过 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/
我是一名优秀的程序员,十分优秀!