2017-06-19 69 views
1

假設我有一個列表創建布爾面具

x = [0, 1, 3, 5] 

而且我想與尺寸

s = (10, 7) 

使得x定義的索引行的第一列是一個張量1,否則爲0。

對於這個特殊的例子,我想獲得含有張量:

T = [[1, 0, 0, 0, 0, 0, 0], 
    [1, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0], 
    [1, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0], 
    [1, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0, 0, 0]] 

使用numpy的,這將是等價的:

t = np.zeros(s) 
t[x, 0] = 1 

我發現這個related answer,但它不真的解決了我的問題。

回答

2

試試這個:

import tensorflow as tf 

indices = tf.constant([[0, 1],[3, 5]], dtype=tf.int64) 
values = tf.constant([1, 1]) 
s = (10, 7) 

st = tf.SparseTensor(indices, values, s) 
st_ordered = tf.sparse_reorder(st) 
result = tf.sparse_tensor_to_dense(st_ordered) 

sess = tf.Session() 
sess.run(result) 

這裏是輸出:

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

我稍微修改您的索引,所以你可以看到指數

x,y格式爲最初獲得你問,集:

indices = tf.constant([[0, 0], [1, 0],[3, 0], [5, 0]], dtype=tf.int64) 

輸出:

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

謝謝!你知道我可以如何動態設置dense_shape嗎?我在這裏問過這個問題https://stackoverflow.com/questions/44650464/tensorflow-sparsetensor-with-dynamically-set-dense-shape –

+0

當然。在您發送的鏈接上發佈答案 – MZHm