[Python Cookbook] Numpy: How to Apply a Function to 1D Slices along the Given Axis
Here is a function in Numpy module which could apply a function to 1D slices along the Given Axis. It works like apply funciton in Pandas.
numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)
Parameters: |
|
---|---|
Returns: |
|
Here is an example to shift the image one pixel down through numpy.apply_along_axis method.
1 import numpy as np 2 from scipy.ndimage.interpolation import shift 3 def shift_one_pixel(image, dx,dy): 4 image=image.reshape(28,28) 5 image_shifted=shift(image,[dy,dx],cval=0,mode='constant') 6 return image_shifted.reshape(28*28) 7 8 X_train_expanded = np.apply_along_axis(shift_one_pixel,1,X_train,1,0)