繁体   English   中英

具有向量值的 Tensorflow 稀疏张量到密集张量

[英]Tensorflow sparse tensor with vector value to dense tensor

我有一些稀疏索引:

[[0 0]
 [0 1]
 [1 0]
 [1 1]
 [1 2]
 [2 0]]

每个索引对应的值为:

[[0.1 0.2 0.3]
 [0.4 0.5 0.6]
 [0.7 0.8 0.9]
 [1.0 1.1 1.2]
 [1.3 1.4 1.5]
 [1.6 1.7 1.8]]

如何将 6x3 值张量转换为 tensorflow 中的 3x3x3 密集张量? 索引中未指定的索引值为零向量 [0. 0. 0.]。 稠密张量是这样的:

[[[0.1 0.2 0.3]
  [0.4 0.5 0.6]
  [0.0 0.0 0.0]]

 [[0.7 0.8 0.9]
  [1.0 1.1 1.2]
  [1.3 1.4 1.5]]

 [[1.6 1.7 1.8]
  [0.0 0.0 0.0]
  [0.0 0.0 0.0]]]

你可以用tf.scatter_nd做到这tf.scatter_nd

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    indices = tf.constant(
        [[0, 0],
         [0, 1],
         [1, 0],
         [1, 1],
         [1, 2],
         [2, 0]])
    values = tf.constant(
        [[0.1, 0.2, 0.3],
         [0.4, 0.5, 0.6],
         [0.7, 0.8, 0.9],
         [1.0, 1.1, 1.2],
         [1.3, 1.4, 1.5],
         [1.6, 1.7, 1.8]])
    out = tf.scatter_nd(indices, values, [3, 3, 3])
    print(sess.run(out))

输出:

[[[0.1 0.2 0.3]
  [0.4 0.5 0.6]
  [0.  0.  0. ]]

 [[0.7 0.8 0.9]
  [1.  1.1 1.2]
  [1.3 1.4 1.5]]

 [[1.6 1.7 1.8]
  [0.  0.  0. ]
  [0.  0.  0. ]]]

在 Tensorflow 中没有明确的方法可以使用任何reshape类型的函数来做到这一点。 我只能通过创建列表并将其转换回张量来考虑迭代解决方案。 这可能不是最有效的解决方案,但这可能适用于您的代码。

# list of indices 
idx=[[0,0],[0,1], [1,0],[1,1], [1,2], [2,0]]

# Original Tensor to reshape
dense_tensor=tf.Variable([[0.1, 0.2 ,0.3],[0.4, 0.5, 0.6], [0.7, 0.8, 0.9], [1.0,1.1,1.2],[1.3,1.4,1.5], [1.6,1.7,1.8]])

# creating a temporary list to later convert to Tensor
c=np.zeros([3,3,3]).tolist()

for i in range(3):
    count=0
    for j in range(3):
        if([i,j] in idx):
            c[i][j]=dense_tensor[count]
            count=count+1
        else:
            c[i][j]=tf.Variable([0,0,0], dtype=tf.float32)

# Convert obtained list to Tensor
converted_tensor = tf.convert_to_tensor(c, dtype=tf.float32)

您可以根据所需的张量大小定义范围。 对于您的情况,我选择了 3,因为您需要一个 3x3x3 张量。 我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM