【发布时间】:2017-06-20 20:27:56
【问题描述】:
我之前曾问过这个问题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:预期为 int64,得到 Dimension(50) 类型为“Dimension” 而是。
如何动态设置稀疏张量的形状?有没有更好的选择来实现我的目标?
【问题讨论】:
-
如果
reference_t的形状从一开始就固定,将.as_list()添加到.shape应该可以完成这项工作 -
从一开始就不是固定的。 reference_t 本身的形状是从 3d 数组的形状推断出来的,该数组作为输入提供给形状为 [None, None, None] 的占位符
-
那么我认为你应该使用
tf.shape函数,如shape_t = tf.shape(reference_t),并使用它代替reference_t.shape,也许你还必须将sparse_2d_shape设置为张量,tf.stack或tf.concat -
我的最终目标是然后在稀疏张量上使用
tf.tile,以便 1 将沿第三维重复(这样,最后,稀疏张量将具有相同的形状为reference_t)。我认为使用tf.zeros_like可能是一个不错的选择,但我不知道如何仅将零张量的特定切片设置为 1。
标签: python tensorflow