【问题标题】:Tensorflow - constructing a tensor from particular values extracted from two different tensorsTensorflow - 从两个不同张量中提取的特定值构造张量
【发布时间】:2022-12-11 16:54:39
【问题描述】:

我正在尝试以与 TensorFlow autodiff 兼容的方式使用来自两个不同张量的值和一个二维索引数组来构造一个张量。

在第一步中,我想提取形状为 (n,n) 的张量 D 的元素,其值与另一个张量 a 中的值相同。特别是,我正在寻找一种更好的方法来实现以下循环:

a = []
for i in range(len(f)):
    a.append(tf.where(tf.experimental.numpy.isclose(f[I], D, atol=1e-6))[0])
P_x = tf.gather(D,a)

在附加步骤中,我只使用值相等的第一个实例,因为我感兴趣的函数独立于此选择。我需要使用 isclose,因为这两个数组是 float32 数组并且彼此不完全相等。

然后在第二步中,我想将 P_xP_y = tf.gather(g, indices) 结合起来构造一个张量 P。假设P_xP_y的形状都是(n, )。然后,

P = [[P_x[0], P_y[0]],[P_x[1], P_y[1]], ..., [P_x[n], P_y[n]] ]

我是 TensorFlow 的新手,所以尽管浏览了文档,但我没有看到使用收集、分散等来完成所有这些操作的方法,这似乎是使 autodiff 工作所必需的。当我使用循环和其他方法时,我得到 gradients = none。

【问题讨论】:

    标签: numpy tensorflow autodiff


    【解决方案1】:

    对于第一步,您可以通过使用 broadcasting 找到最接近的匹配来将循环减少为矩阵运算。

    indices = tf.reduce_sum(tf.math.abs(D[:,None] - a), 2)     
    #numpy is_close
    
    tf.gather(D,tf.where(indices < 1e-6)[:,0])
    

    例子:

    D = tf.random.normal(shape=(5,3))
    a = tf.concat([tf.random.normal(shape=(2,3)), D[:2],], axis=0)
    
    #Here a last 2 rows of `a` are made same as first two rows of D.
    #D is array([[ 0.6221494 ,  0.39071774,  0.5728211 ],
       [ 0.926828  ,  0.8460992 ,  0.08634651],
       [-0.39511812, -0.02012417,  1.0490925 ],
       [-0.31207308,  0.41652176,  0.85152763],
       [-1.27271   , -0.09542792, -0.16090107]]
    #a is array([[ 0.9826471 ,  0.25055575, -0.4920534 ],
       [-0.3222343 ,  0.91883016,  1.2904693 ],
       [ 0.6221494 ,  0.39071774,  0.5728211 ],
       [ 0.926828  ,  0.8460992 ,  0.08634651]]
    

    numpy.is_close() 操作

    indices = tf.reduce_sum(tf.math.abs(D[:,None] - a), 2)  
    #this compares each row of D with each row of a. So we get a (5,4) matrix for the above example.
    

    收集 D 靠近 a:

    tf.gather(D,tf.where(indices < 1e-6)[:,0])
    #output
    array([[0.6221494 , 0.39071774, 0.5728211 ],
           [0.926828  , 0.8460992 , 0.08634651]],
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多