python - Simplify Matrix by Averaging Multiple Cells -
python - Simplify Matrix by Averaging Multiple Cells -
i have big 2d numpy matrix needs made smaller (ex: convert 100x100 10x10).
my goal essentially: break nxn matrix smaller mxm matrices, average cells in these mxm slices, , build new (smaller) matrix out of these mxm slices.
i'm thinking using matrix[a::b, c::d]
extract smaller matrices, , averaging values, seems overly complex. there improve way accomplish this?
you split array blocks view_as_blocks
function (in scikit-image).
for 2d array, returns 4d array blocks ordered row-wise:
>>> import skimage.util ski >>> import numpy np >>> = np.arange(16).reshape(4,4) # 4x4 array >>> ski.view_as_blocks(a, (2,2)) array([[[[ 0, 1], [ 4, 5]], [[ 2, 3], [ 6, 7]]], [[[ 8, 9], [12, 13]], [[10, 11], [14, 15]]]])
taking mean along lastly 2 axes returns 2d array mean in each block:
>>> ski.view_as_blocks(a, (2,2)).mean(axis=(2,3)) array([[ 2.5, 4.5], [ 10.5, 12.5]])
note: view_as_blocks
returns view of array modifying strides (it works arrays more 2 dimensions). implemented purely in numpy using as_strided
, if don't have access scikit-image library can copy code here.
python arrays list numpy matrix
Comments
Post a Comment