【问题标题】:Tensorflow: set column of tensor to infinityTensorflow:将张量列设置为无穷大
【发布时间】:2021-02-10 23:11:12
【问题描述】:

假设我有一个张量

import tensorflow as tf
import numpy as np
arr = np.array([[1,2,3], [4,5,6], [7,8,9]])
tensor = tf.convert_to_tensor(arr)

在 numpy 中,我可以这样做: arr[:,[0,2]] = -np.inf,但是由于“TF不支持项目分配”,我不确定在TF 2.3中是否有办法做到这一点?

【问题讨论】:

    标签: python numpy tensorflow matrix


    【解决方案1】:

    这是一种可能的方式:

    import tensorflow as tf
    import numpy as np
    arr = np.array([[1,2,3], [4,5,6], [7,8,9]])
    tensor = tf.convert_to_tensor(arr)
    mask = tf.constant(list(range(2))) != 1
    tf.where(mask, tensor, tf.constant(-np.inf))
    

    【讨论】:

      【解决方案2】:

      这是一种方法:

      import tensorflow as tf
      
      # Input data
      # Tensor must be float type to hold infinity
      tensor = tf.convert_to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=tf.float32)
      inf_cols = [0, 2]
      # Make mask of replaced columns
      col_mask = tf.scatter_nd(tf.expand_dims(inf_cols, 1),
                               tf.ones_like(inf_cols, dtype=tf.bool),
                               [tf.shape(tensor)[1]])
      # Replace columns
      res = tf.where(tf.expand_dims(col_mask, 0), -np.inf, tensor)
      tf.print(res)
      # [[-inf 2 -inf]
      #  [-inf 5 -inf]
      #  [-inf 8 -inf]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-13
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 2021-09-25
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多