Skip to main content
 首页 » 编程设计

python之具有矢量值的 Tensorflow 稀疏张量到密集张量

2024年09月03日29jackei

我有一些稀疏索引:

[[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]] 

如何在tensorflow中将6x3值张量转换为3x3x3稠密张量? indices 中未指定的索引值为零向量 [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 做到这一点:

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. ]]]