【问题标题】:conditional assignment of tf.variable in Tensorflow 2Tensorflow 2中tf.variable的条件赋值
【发布时间】:2021-04-03 13:48:50
【问题描述】:

对于 numpy,我们有

threshold = 3
a = np.array([1,2,3,4,5,6])
a[a>=3] = 199

# a is [1, 2, 199, 199, 199, 199]

如何在tensorflow 2写类似的代码

b = tf.Variable(a)

谢谢。

【问题讨论】:

    标签: python python-3.x conditional-statements tensorflow2.0


    【解决方案1】:

    当然,您可以使用tf.where 有条件地设置值:

    b = tf.Variable(a)
    tf.where(b >= 3, 199, b)
    # <tf.Tensor: shape=(6,), dtype=int64, numpy=array([  1,   2, 199, 199, 199, 199])>
    

    【讨论】:

    • 嗨@cs95,感谢您的回答。 tf.where(b&gt;=3, 199, b) 是否会成为计算图的插件,并在反向传播中影响 b 的梯度?谢谢,
    • @jason 不能肯定地告诉你,抱歉。也许你可以提出一个后续问题。
    • 当然,问题出在这个帖子里stackoverflow.com/questions/65449945/…
    • @jason 祝你这个问题好运,我会看看我是否可以做任何挖掘。
    猜你喜欢
    • 2021-07-02
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-05-09
    • 1970-01-01
    相关资源
    最近更新 更多