This code appears to be performing local spatial averaging (when agg > 0) followed by vector normalization. Here are several potential optimizations:
- For the sliding window operation:
# Instead of sliding_window_view + mean, you could use a 2D convolution
if agg:
kernel = np.ones((agg + 1, agg + 1)) / ((agg + 1) ** 2)
data = scipy.ndimage.convolve(data, kernel[:, :, None], mode='reflect')
- For the normalization:
# Avoid creating an extra array with keepdims
norms = np.sqrt(np.sum(data * data, axis=-1))
data /= norms[..., None] # Broadcasting will handle zeros automatically
Additional optimizations to consider:
-
If you're using this in a loop, you could pre-compute the convolution kernel
-
If you don't need the highest precision, you could use:
data = data.astype(np.float32) # Instead of float64
- If you have GPU access, consider using CuPy or similar libraries:
import cupy as cp
# Convert data to GPU
data_gpu = cp.asarray(data)
if agg:
kernel = cp.ones((agg + 1, agg + 1)) / ((agg + 1) ** 2)
data_gpu = cp.ndimage.convolve(data_gpu, kernel[:, :, None], mode='reflect')
norms = cp.sqrt(cp.sum(data_gpu * data_gpu, axis=-1))
data_gpu /= norms[..., None]
# Convert back to CPU if needed
data = cp.asnumpy(data_gpu)
- If you don't need the full precision of the sliding window average, you could downsample first:
if agg:
# Downsample
h, w = data.shape[:2]
new_h, new_w = h//(agg+1), w//(agg+1)
data_small = data.reshape(new_h, agg+1, new_w, agg+1, -1).mean(axis=(1,3))
# Then upsample back
data = scipy.ndimage.zoom(data_small, (h/data_small.shape[0], w/data_small.shape[1], 1))
The best approach depends on your specific needs regarding precision, memory usage, and whether you have GPU access. Could you tell me more about your constraints and requirements?