gpt4 book ai didi

python - Tensorflow中如何根据索引给Tensor赋值?

转载 作者:太空狗 更新时间:2023-10-29 19:29:53 25 4
gpt4 key购买 nike

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

例如,根据tf.nn.max_pool_with_argmax的pooling值和对应的指标输出,我想将这些池值与索引一起放回原始的非池化张量中。

我发现 tf.nn.max_pool_with_argmax 的输出索引被展平了。一个问题:如何将它们分解回 Tensorflow 中的坐标?

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

非常感谢。

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

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})

最佳答案

有一个悬而未决的 PR 应该可以解决这个问题:

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

关于python - Tensorflow中如何根据索引给Tensor赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com