Reputation: 67
I'm a bit confused about how numpy's ndarray's min/max function with a given axis
argument works.
import numpy as np
x = np.random.rand(2,3,4)
x.min(axis=0)
produces
array([[[0.4139181 , 0.24235588, 0.50214552, 0.38806332],
[0.63775691, 0.08142376, 0.69722379, 0.1968098 ],
[0.50496744, 0.54245416, 0.75325114, 0.67245846]],
[[0.79760899, 0.35819981, 0.5043491 , 0.75274284],
[0.54778544, 0.5597848 , 0.52325408, 0.66775091],
[0.71255276, 0.85835137, 0.60197253, 0.33060771]]])
array([[0.4139181 , 0.24235588, 0.50214552, 0.38806332],
[0.54778544, 0.08142376, 0.52325408, 0.1968098 ],
[0.50496744, 0.54245416, 0.60197253, 0.33060771]])
a 3x4 numpy array. I was thinking it would produce a size 2 array with the minimum for x[0]
and x[1]
.
Can someone explain how this min function is working?
Upvotes: 2
Views: 408
Reputation: 260640
When you do x.min(axis=0)
, you request the min to be computed along the axis 0, which means this dimension is aggregated into a single value and thus the output has a (3,4) shape.
What you want is to compute the min on the combined axes 1 and 2:
x.min(axis=(1,2))
# array([0.38344152, 0.0202184 ])
You can also first reshape the array to combine those two dimensions, then compute the min along this new dimension (here, 1):
x.reshape(2,-1).min(axis=1)
# array([0.38344152, 0.0202184 ])
intermediate, reshaped, array:
x.reshape(2,-1)
array([[0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 ,
0.64589411, 0.43758721, 0.891773 , 0.96366276, 0.38344152,
0.79172504, 0.52889492],
[0.56804456, 0.92559664, 0.07103606, 0.0871293 , 0.0202184 ,
0.83261985, 0.77815675, 0.87001215, 0.97861834, 0.79915856,
0.46147936, 0.78052918]])
used input:
np.random.seed(0)
x = np.random.rand(2,3,4)
Upvotes: 1