[英]How to use tf.gather_nd for multi-dimensional tensor
I don't fully understand how I should use tf.gather_nd() to pick up elements along some axis if I have multi-dimensional tensor.如果我有多维张量,我不完全理解如何使用 tf.gather_nd() 沿某个轴拾取元素。 Let's take a small example (if I get answer for this simple example, it solves also my more complex original problem).
让我们举一个小例子(如果我得到这个简单例子的答案,它也解决了我更复杂的原始问题)。 Let's say that I have rgb image and I am trying to pick the smallest pixel value along channels (last dimension if data order is (B,H,W,C)).
假设我有 rgb 图像,并且我试图沿通道选择最小的像素值(如果数据顺序为 (B,H,W,C),则为最后一个维度)。 I know that this can be done with
tf.recude_min(x, axis=-1)
but I would like to know that is it also possible to do the same thing with tf.argmin()
and tf.gather_nd()
?我知道这可以用
tf.recude_min(x, axis=-1)
来完成,但我想知道是否也可以用tf.argmin()
和tf.gather_nd()
做同样的事情?
from skimage import data
import tensorflow as tf
import numpy as np
# Load RGB image from skimage, cast it to float32 and put it in order (B,H,W,C)
image = data.astronaut()
image = tf.cast(image, tf.float32)
image = tf.expand_dims(image, axis=0)
# Take minimum pixel value of each channel in a way number 1
min_along_channels_1 = tf.reduce_min(image, axis=-1)
# Take minimum pixel value of each channel in a way number 2
# The goal is that min_along_channels_1 is equal to min_along_channels_2
idxs = tf.argmin(image, axis=-1)
min_along_channels_2 = tf.gather_nd(image, idxs) # This line gives error :(
You will have to use tf.meshgrid
, which will create a rectangular grid of two one-dimensional arrays representing the tensor indexing of the first and second dimension, since tf.gather_nd
needs to know exactly where to extract values across the dimensions:您将不得不使用
tf.meshgrid
,它将创建一个由两个一维 arrays 组成的矩形网格,表示第一维和第二维的张量索引,因为tf.gather_nd
需要确切知道在哪里提取跨维度的值:
import tensorflow as tf
image = tf.random.normal((1, 4, 4, 3))
image = tf.squeeze(image, axis=0)
idx = tf.argmin(image, axis=-1)
ij = tf.stack(tf.meshgrid(
tf.range(image.shape[0], dtype=tf.int64),
tf.range(image.shape[1], dtype=tf.int64),
indexing='ij'), axis=-1)
gather_indices = tf.concat([ij, tf.expand_dims(idx, axis=-1)], axis=-1)
result = tf.gather_nd(image, gather_indices)
print('First option -->', tf.reduce_min(image, axis=-1))
print('Second option -->', result)
First option --> tf.Tensor(
[[-0.53245485 -0.29117298 -0.64434254 -0.8209638 ]
[-0.9386176 -0.5993224 -0.597746 -1.5392851 ]
[-0.5478666 -1.5280861 -1.0344954 -1.920418 ]
[-0.5580688 -1.425873 -1.9276617 -1.0668412 ]], shape=(4, 4), dtype=float32)
Second option --> tf.Tensor(
[[-0.53245485 -0.29117298 -0.64434254 -0.8209638 ]
[-0.9386176 -0.5993224 -0.597746 -1.5392851 ]
[-0.5478666 -1.5280861 -1.0344954 -1.920418 ]
[-0.5580688 -1.425873 -1.9276617 -1.0668412 ]], shape=(4, 4), dtype=float32)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.