Tensorflow 2.0: which the equivalent of numpy. take_along_axis

Viewed 291

This is my problem: I have implemented a simple function that return the peaks of signals organized as a matrix.

@tf.function
def get_peaks(X, X_err):
    prominence = 0.9
    # X shape (B, N, 1)
    max_pooled = tf.nn.pool(X, window_shape=(20, ), pooling_type='MAX', padding='SAME') 
    maxima = tf.equal(X, max_pooled) #shape (1, N, 1)
    maxima = tf.cast(maxima, tf.float32)
    peaks = tf.squeeze(X * maxima) #shape (1, N, 1) ==> shape (N,)
    peaks_err = X_err * tf.squeeze(maxima)
    peaks_idxs, idxs = tf.math.top_k(peaks, k=2)
    return peaks_idxs, idxs 

As you can see the input has shape (B, N, 1), i.e. batch samples, each of them is a mono-dimensional vector of N elements. The returned idxs are correct as well as peaks_idxs, they has shape (B, 2), i.e. the position (and peaks) of the two maxes for each sample in the batch.

The problem is that I would like to take also the peak_err corresponding to idxs. With numpy I will use:

np.take_along_axis(peaks_err, idxs, axis=1)

that actually return a correct matrix with shape (B, 2). How can I do the same with tf? I have actually tried using tf.gather:

tf.gather(peaks_err, idxs, axis=1)

but it is not working, the result is not correct with a shape (B, B, 2), and a lot of zeros. Do you know how can I solve? Thanks!

1 Answers

I have solved adding three lines:

@tf.function
def get_local_maxima3(XC, SXC):
    prominence = 0.9
    # x shape (1, N, 1)
    max_pooled = tf.nn.pool(XC, window_shape=(20, ), pooling_type='MAX', padding='SAME') 
    maxima = tf.equal(XC, max_pooled) #shape (1, N, 1)
    maxima = tf.cast(maxima, tf.float32)
    peaks = tf.squeeze(XC * maxima) #shape (1, N, 1) ==> shape (N,)
    peaks_err = SXC * tf.squeeze(maxima)
    #maxima = tf.where(tf.greater(peaks, prominence)) # shape (N,)
    peaks, idxs = tf.math.top_k(peaks, k=2)

    idxs_shape = tf.shape(idxs)
    grid = tf.meshgrid(*(tf.range(idxs_shape[i]) for i in range(idxs.shape.ndims)), indexing='ij')
    index_full = tf.stack(grid[:-1] + [idxs], axis=-1)
    peaks_err = tf.gather_nd(peaks_err, index_full)
    return peaks, peaks_err

It works! If you find/ have a smarter/faster solution I'll appreciate it.

Related