Skip to main content
 首页 » 编程设计

python之动态设置 dense_shape 的 TensorFlow SparseTensor

2024年10月01日29zhoujg

我以前问过这个问题Create boolean mask on TensorFlow关于如何仅将某些索引设置为 1 并将其余索引设置为 0 来获取张量。

我认为@MZHm 给出的答案可以完全解决我的问题。虽然 tf.SparseTensor 的参数 dense_shape 只接受列表,我想传递一个从图中推断出的形状(从另一个具有变量的张量的形状形状)。所以在我的具体情况下,我想做这样的事情:

# The tensor from which the shape of the sparse tensor is to be inferred 
reference_t = tf.zeros([32, 50, 11]) 
 
# The indices that will be 1 
indices = [[0, 0], 
           [3, 0], 
           [5, 0], 
           [6, 0]] 
 
# Just setting all the values for the sparse tensor to be 1 
values = tf.ones([reference_t.shape[-1]]) 
 
# The 2d shape I want the sparse tensor to have 
sparse_2d_shape = [reference_t.shape[-2], 
                   reference_t.shape[-1]] 
 
st = tf.SparseTensor(indices, values, sparse_2d_shape) 

从这里我得到错误:

TypeError: Expected int64, got Dimension(50) of type 'Dimension' instead.

如何动态设置稀疏张量的形状?是否有更好的选择来实现我的目标?

请您参考如下方法:

您可以通过以下方式获得动态形状:

import tensorflow as tf  
import numpy as np 
 
indices = tf.constant([[0, 0],[1, 1]], dtype=tf.int64) 
values = tf.constant([1, 1]) 
dynamic_input = tf.placeholder(tf.float32, shape=[None, None]) 
s = tf.shape(dynamic_input, out_type=tf.int64) 
 
st = tf.SparseTensor(indices, values, s) 
st_ordered = tf.sparse_reorder(st) 
result = tf.sparse_tensor_to_dense(st_ordered) 
 
sess = tf.Session() 

具有(动态)形状的输入 [5, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([5, 3])}) 

将输出:

array([[1, 0, 0], 
       [0, 1, 0], 
       [0, 0, 0], 
       [0, 0, 0], 
       [0, 0, 0]], dtype=int32) 

具有(动态)形状的输入 [3, 3]:

sess.run(result, feed_dict={dynamic_input: np.zeros([3, 3])}) 

将输出:

array([[1, 0, 0], 
       [0, 1, 0], 
       [0, 0, 0]], dtype=int32) 

好了...动态稀疏形状。