【问题标题】:How to pad multiple tensors with one on main diagonal and zeros elsewhere?如何在主对角线上用一个填充多个张量,在其他地方用零填充?
【发布时间】:2018-02-17 04:12:24
【问题描述】:

我有R 作为形状(N,2,2) 的二维旋转矩阵。现在我希望将每个矩阵扩展到(3,3) 3D 旋转矩阵,即在每个[:,:2,:2] 中放入零并将1 放入[:,2,2]

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

更新

我试过这种方式

    R = tf.get_variable(name='R', shape=np.shape(R_value), dtype=tf.float64,
                        initializer=tf.constant_initializer(R_value))
    eye = tf.eye(np.shape(R_value)[1]+1)
    right_column = eye[:2,2]
    bottom_row = eye[2,:]
    R = tf.concat([R, right_column], 3)
    R = tf.concat([R, bottom_row], 2)

但是失败了,因为concat 不做广播...

更新 2

我在concat 调用中进行了显式广播并修复了错误的索引:

    R = tf.get_variable(name='R', shape=np.shape(R_value), dtype=tf.float64,
                        initializer=tf.constant_initializer(R_value))
    eye = tf.eye(np.shape(R_value)[1]+1, dtype=tf.float64)

    right_column = eye[:2,2]
    right_column = tf.expand_dims(right_column, 0)
    right_column = tf.expand_dims(right_column, 2)
    right_column = tf.tile(right_column, (np.shape(R_value)[0], 1, 1))

    bottom_row = eye[2,:]
    bottom_row = tf.expand_dims(bottom_row, 0)
    bottom_row = tf.expand_dims(bottom_row, 0)
    bottom_row = tf.tile(bottom_row, (np.shape(R_value)[0], 1, 1))

    R = tf.concat([R, right_column], 2)
    R = tf.concat([R, bottom_row], 1)

解决方案看起来相当复杂。有没有更简单的?

【问题讨论】:

    标签: python indexing tensorflow padding rotational-matrices


    【解决方案1】:

    第一个填充零到[N, 2, 2] 成为[N, 3, 3]padded = tf.pad(R, [[0, 0], [0, 1], [0, 1]])

    然后将padded[N, 2, 2] 转换为1:

    由于tf.Tensor 不支持赋值,您可以通过初始化np.array 来做到这一点,然后将它们相加。

    arr = np.zeros((3, 3)) 
    arr[2, 2] = 1
    R = padded + arr # broadcast used here
    

    现在变量 R 是你需要的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-21
      • 2020-01-20
      • 2016-03-21
      • 2019-12-24
      • 2015-12-08
      • 2023-03-29
      • 2016-06-03
      相关资源
      最近更新 更多