【问题标题】:TensorFlow SparseTensor with dynamically set dense_shape具有动态设置dense_shape的TensorFlow SparseTensor
【发布时间】: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.stacktf.concat
  • 我的最终目标是然后在稀疏张量上使用tf.tile,以便 1 将沿第三维重复(这样,最后,稀疏张量将具有相同的形状为reference_t)。我认为使用tf.zeros_like 可能是一个不错的选择,但我不知道如何仅将零张量的特定切片设置为 1。

标签: python tensorflow


【解决方案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)

所以你去...动态稀疏形状。

【讨论】:

  • 很好的答案!经过数小时试图理解 Tensorflow 错误后即将放弃......谢谢! :')
猜你喜欢
  • 1970-01-01
  • 2017-09-20
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 2018-02-07
  • 2022-01-22
相关资源
最近更新 更多