Alternative solution for 87.
FirefoxMetzger opened this issue · 5 comments
FirefoxMetzger commented
Numpy has (finally) "upstreamed" skimage's view_as_windows
under the name sliding_window_view
. With this we can write exercise 87 using more verbose clear syntax
Z = np.ones((16,16))
k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
relevant_windows = windows[::k, ::k, ...]
S = np.sum(np.sum(relevant_windows, axis=-1), axis=-1)
or if we prefer (potentially hard to maintain) one-liners
Z = np.ones((16,16))
k = 4
S = np.sum(
np.sum(
np.lib.stride_tricks.sliding_window_view(Z, (k, k))[::k, ::k, ...]
axis=-1),
axis=-1)
rougier commented
I'm not a big fan of this syntax,windows
and relevant_windows
are quite redundant.
FirefoxMetzger commented
Sure, we can also write
Z = np.ones((16,16))
k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = np.sum(np.sum(windows[::k, ::k, ...], axis=-1), axis=-1)
The main point is that there is an alternative solution. Do you think it is worthwhile to add it here? If so, we can discuss how to best formulate it and I can submit a PR.
FirefoxMetzger commented
If you don't like the double sum, there is of course
S = windows[::k, ::k].reshape(*(x//k for x in Z.shape), -1).sum(-1)
rougier commented
Sorry for the delay and yes, it's worth a PR to show the alternative. Can you do it?
FirefoxMetzger commented
@rougier sure. This should do the trick.