2017-06-19 80 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