I would like to pad a numpy tensor with 0 along the chosen axis.
For instance, I have tensor r
with shape (4,3,2)
but I am only interested in padding only the last two axis (that is, pad only the matrix). Is it possible to do it with the one-line python code?
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.
You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.
pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.
zeros() and ones() are the NumPy library functions to create two different arrays. zeros() function is used to create an array based on the particular shape and type. All array elements are initialized to 0, which is created by the zeros() function. ones() function works like the zeros() function.
You can use np.pad()
:
a = np.ones((4, 3, 2))
# npad is a tuple of (n_before, n_after) for each dimension
npad = ((0, 0), (1, 2), (2, 1))
b = np.pad(a, pad_width=npad, mode='constant', constant_values=0)
print(b.shape)
# (4, 6, 5)
print(b)
# [[[ 0. 0. 0. 0. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0.]]
# [[ 0. 0. 0. 0. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0.]]
# [[ 0. 0. 0. 0. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0.]]
# [[ 0. 0. 0. 0. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 1. 1. 0.]
# [ 0. 0. 0. 0. 0.]
# [ 0. 0. 0. 0. 0.]]]
This function would pad at the end of certain axis.
If you wish to pad both side, just modify it.
def pad_along_axis(array: np.ndarray, target_length: int, axis: int = 0) -> np.ndarray:
pad_size = target_length - array.shape[axis]
if pad_size <= 0:
return array
npad = [(0, 0)] * array.ndim
npad[axis] = (0, pad_size)
return np.pad(array, pad_width=npad, mode='constant', constant_values=0)
example:
>>> import numpy as np
>>> a = np.identity(5)
>>> b = pad_along_axis(a, 7, axis=1)
>>> print(a, a.shape)
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]] (5, 5)
>>> print(b, b.shape)
[[1. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0.]] (5, 7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With