我以前問過這個問題Create boolean mask on TensorFlow如何取得只能設置爲1某些指標張量,而其中0TensorFlow SparseTensor與動態設置dense_shape
其餘的我認爲通過@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.
如何以動態設置稀疏張量的形狀?有沒有更好的選擇來實現我的目標?
如果''reference_t的形狀是從一開始就固定的,加入'.as_list()'的'.shape'應該這樣做是不是從一開始就固定工作 –
。 reference_t本身的形狀是從給定爲輸入到佔位符形狀[無,無,無] –
然後我想你應該使用'tf.shape'功能的三維陣列的形狀推斷,如'shape_t = tf.shape(reference_t)',並用它來代替reference_t.shape'的',也許你需要設置'sparse_2d_shape'到張量爲好,以'tf.stack'或'tf.concat' –