【问题标题】:Create a tensor based on another tensor in TensorFlow基于 TensorFlow 中的另一个张量创建一个张量
【发布时间】:2021-04-07 07:31:34
【问题描述】:

我有以下张量:

indices = tf.constant([[1, 2], [0, 2], [1, 0]])

我想创建以下张量:

[[0, 1, 1],
 [1, 0, 1],
 [1, 1, 0]]

基本上,我想要一个形状为indices.shape[0] 的方阵,其中除了indices 张量中的相应索引之外,它的元素都为零。

我尝试了tf.scatter_nd,但没有成功!

【问题讨论】:

  • 根据您的数据流,您可能会发现使用sparse tensors 很有用。请注意,矩阵的格式与稀疏张量的表示非常相似。需要时,可以通过调用 `sparse.to_dense' 方法将稀疏张量转换为常用张量。

标签: python tensorflow


【解决方案1】:

indices张量带有一些你应该明确的隐含信息。要使scatter_nd 起作用,您需要提供一些对(i,j),其中i 是第一个维度的索引,j 是第二个维度的索引。

你可以通过以下方式重构你的indicesTensor:

indices = tf.constant([[1, 2], [0, 2], [1, 0]])
j_indices = tf.reshape(indices, [-1, 1])
i_indices = tf.expand_dims(tf.repeat(tf.range(3), 2), axis=-1)
new_indices = tf.concat([i_indices, j_indices], axis=-1)

新索引包含(i,j) 索引:

>>> new_indices
<tf.Tensor: shape=(6, 2), dtype=int32, numpy=
array([[0, 1],
       [0, 2],
       [1, 0],
       [1, 2],
       [2, 1],
       [2, 0]], dtype=int32)>

您可以将其与scatter_nd 一起使用:

>>> tf.scatter_nd(new_indices, updates=tf.ones(tf.shape(new_indices)[0]), shape=[3, 3])
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[0., 1., 1.],
       [1., 0., 1.],
       [1., 1., 0.]], dtype=float32)>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多