【问题标题】:Update tensor with arrays in tensorflow使用 tensorflow 中的数组更新张量
【发布时间】:2017-12-05 14:24:27
【问题描述】:

我有一个 3-D 张量,我想在其中更新一些值,就像在这个 numpy 代码中一样:

x_np = np.zeros((2,3,2))
updates_np = np.ones((2,2))
indices_1 = np.array([0, 1])
indices_2 = np.array([1, 1])

x_np[indices_1, indices_2, :] = updates_np

结果如下:

>>> x_np

array([[[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 1.,  1.],
        [ 0.,  0.]]])

我想更新最后一个维度上的完整行,为此我尝试使用scatter_update(我也尝试使用dynamic_stitch)。但似乎 scatter_update 不接受超过一维作为更新索引。

如何在张量流中做到这一点?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    我提供了一个在我看来很糟糕的解决方案,因此欢迎任何改进

    sess = tf.InteractiveSession()
    x = tf.zeros((2,3,2))
    indices_1 = tf.constant([0, 1])
    indices_2 = tf.constant([1, 1])
    updates_tf = tf.ones((2, 2))  
    
    x_temp = tf.Variable(tf.reshape(x, [-1, 2]))
    
    indices_flat = tf.shape(x)[1]*indices_1 + indices_2
    sess.run(tf.initialize_all_variables())
    print(sess.run(tf.reshape(tf.scatter_update(x_temp, indices_flat,  updates_tf), tf.shape(x))))
    

    结果

    [[[ 0.  0.]
      [ 1.  1.]
      [ 0.  0.]]
    
     [[ 0.  0.]
      [ 1.  1.]
      [ 0.  0.]]]
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2023-03-11
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 2016-02-15
      相关资源
      最近更新 更多