【问题标题】:In Tensorflow, how to assign values in Tensor according to the indices?在 Tensorflow 中,如何根据索引在 Tensor 中赋值?
【发布时间】:2016-10-07 09:01:03
【问题描述】:

我想根据索引在张量中赋值。

例如, 根据tf.nn.max_pool_with_argmax的池化值和对应的索引输出,我想把这些池化值放回原来的带索引的unpooling Tensor中。

我发现tf.nn.max_pool_with_argmax 的输出索引是扁平的。 一个问题:如何将它们解开回到 Tensorflow 中的坐标?

另一个问题:给定索引,如何将池化张量的每个值分配到Tensorflow中原始解池化张量的位置?

非常感谢。

我尝试编写代码来实现这一点,但我可以使用numpy。我不知道如何在 tf.nn.max_pool_with_argmax 之后获取扁平化索引并将其分配到 Tensorflow 中的非池化张量中。

ksize = 3
stride = 1

input_image = tf.placeholder(tf.float32, name='input_image')

#conv1
kernel = tf.Variable(tf.truncated_normal([ksize, ksize, 3, 16],stddev=0.1),
                    name='kernel')
conv = tf.nn.conv2d(input_image, kernel, [1,stride,stride,1], padding='SAME')
biases = tf.Variable(tf.constant(0.0, shape = [16]), name = 'biases')
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name='conv1')

#pool1
pool1, pool1_indices = tf.nn.max_pool_with_argmax(conv1, ksize=[1, 2, 2, 1], 
                                                  strides=[1, 2, 2, 1], 
                                                  padding='SAME', name='pool1')

#upsample by assigning the values of pool1 to the position in unpooling Tensor according to pool1_indices                                                
indices = pool1_indices
unravel_pool1_indices = np.unravel_index(indices,[4,32,32,16])
unravel_pool1_coordinates = np.array(unravel_pool1_indices)
coor_shape = np.shape(unravel_pool1_coordinates)
unravel_pool1_coordinates = np.reshape(unravel_pool1_coordinates,(coor_shape[0],coor_shape[1]*coor_shape[2]*coor_shape[3]*coor_shape[4]))
unravel_pool1_coordinates = unravel_pool1_coordinates.T

values = pool1
values = np.reshape(values,(np.size(values)))

up1 = tf.constant(0.0, shape = [4,32,32,16])
delta = tf.SparseTensor(unravel_pool1_coordinates, values, shape = [4,32,32,16])

result = up1 + tf.sparse_tensor_to_dense(delta)


with tf.Session() as session:
    session.run(tf.initialize_all_variables())
    test_image = np.random.rand(4,32,32,3)
    sess_outputs = session.run([pool1, pool1_indices],
                               {input_image.name: test_image})

【问题讨论】:

标签: python tensorflow deep-learning


【解决方案1】:

有一个待处理的 PR 应该可以解决这个问题:

https://github.com/tensorflow/tensorflow/issues/1793

【讨论】:

  • 谢谢。我检查了那个问题。它是如何计算 max_pool_with_argmax op 的梯度。但是在这里,我想根据索引分配一个大张量中的值。我用numpy写的代码的中间部分,似乎不能用graph构建。如何在 TensorFlow 中实现这一点?
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2018-06-01
    • 1970-01-01
    • 2016-04-13
    • 2021-10-11
    • 1970-01-01
    • 2018-05-31
    • 2012-08-19
    • 2021-11-08
    相关资源
    最近更新 更多