2017-06-20 59 views
2

我以前問過這個問題Create boolean mask on TensorFlow如何取得只能設置爲1某些指標張量,而其中0TensorFlow SparseTensor與動態設置dense_shape

其餘的我認爲通過@MZHm給出的答案將完全解決我的問題。雖然,參數的tf.SparseTensordense_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.

如何以動態設置稀疏張量的形狀?有沒有更好的選擇來實現我的目標?

+0

如果''reference_t的形狀是從一開始就固定的,加入'.as_list()'的'.shape'應該這樣做是不是從一開始就固定工作 –

+0

。 reference_t本身的形狀是從給定爲輸入到佔位符形狀[無,無,無] –

+0

然後我想你應該使用'tf.shape'功能的三維陣列的形狀推斷,如'shape_t = tf.shape(reference_t)',並用它來代替reference_t.shape'的',也許你需要設置'sparse_2d_shape'到張量爲好,以'tf.stack'或'tf.concat' –

回答

1

這裏是你可以做的有動感的外形:

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) 

所以你去...動態稀疏的形狀。

+0

大答案的想法!在嘗試瞭解Tensorflow錯誤之後,要放棄幾小時......感謝! :') – Gosu