【问题标题】:How to remove infinity values from a tensor in tensorflow?如何从张量流中的张量中删除无穷大值?
【发布时间】:2021-09-25 20:08:42
【问题描述】:

假设我有一个如下的张量:

var = tf.constant([0,0.05,0.2,0,0])
inverse_var = tf.math.reciprocal(var)
print(inverse_var)

Output :  tf.Tensor([inf, 20. , 5. ,inf inf], shape=(5,), dtype=float32)

我想从 inverse_var 张量创建一个新张量,以便在新张量中将无穷大值替换为零。 需要最终向量 - [ 0, 20, 5, 0, 0 ]

【问题讨论】:

    标签: python tensorflow machine-learning keras tensorflow2.0


    【解决方案1】:

    这是使用tf.tensor_scatter_nd_update 方法完成的解决方案

    import tensorflow as tf
    var = tf.constant([0,0.05,0.2,0,0])
    inverse_var = tf.math.reciprocal(var)
    print(inverse_var)
    mask = tf.math.is_inf(inverse_var)
    indices = tf.where(mask) # found indices where infinite values are 
    print(indices)
    updates=tf.zeros(len(indices)) # create 1D matrix of length of infinite values
    inverse_var_inf = tf.tensor_scatter_nd_update(inverse_var,indices,updates) #updated using scatter_nd_update method
    print(inverse_var_inf)
    

    谢谢! 提供gist供参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 2020-10-30
      • 2020-06-27
      相关资源
      最近更新 更多