0

I have a numpy array of shape [5sx,5sy,5sz] and I’d like to create a tensor with shape [sx,sy,sz] where the value of each element is:

new_array[x,y,z] = mean(array[5x:5x+5,5y:5y+5,5z:5z+5])

I could do this in a loop, but is there a faster one-line approach?

(I'd really ideally like to do it where the size of the origin array is not an integer multiple of the new one, but that seems like a much harder question, and I thought this would be a good first step at least.)

4
  • In pytorch I think the following broadly does it: kernel_size=[5,5,5] torch.nn.Conv3d(in_channels=1,out_channels=1,kernel_size=kernel_size, stride=kernel_size, padding=0)(tensor) Commented Feb 2, 2022 at 11:22
  • The new array must be smaller of at least 5 elements or you have to add a padding after the last elements. Think about the last element in x, if you do the mean from that element to the one 5 elements after, you point your index outside the matrix Commented Feb 2, 2022 at 11:24
  • Why the approach you wrote on the comments shouldn't be good for your purposes? Commented Feb 2, 2022 at 11:25
  • 1
    Well, it probably is to be honest DaSim Commented Feb 2, 2022 at 11:37

1 Answer 1

1

You could use scikit-image block_reduce:

import numpy as np
import skimage.measure

arr5 = np.random.rand(20, 20, 20)
arr  = skimage.measure.block_reduce(arr5, (5, 5, 5), np.mean)
print(f'arr.shape = {arr.shape}')
print(f'arr5[:5, :5, :5].mean() = {arr5[:5, :5, :5].mean()}')
print(f'arr[0, 0, 0] = {arr[0, 0, 0]}')

output:

arr.shape = (4, 4, 4)
arr5[:5, :5, :5].mean() = 0.47200241666948467
arr[0, 0, 0] = 0.4720024166694848

If you're dealing with large arrays and you have a GPU available I would advise you to look into pytorch's average pooling.

Sign up to request clarification or add additional context in comments.

2 Comments

Average pooling may be exactly what I'm looking for in the case the arrays aren't perfectly aligned - thanks, looking into it further.
what do you mean by "in the case the arrays aren't perfectly aligned"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.