Issue
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?
Solution
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.]]]
Answered By - ali_m
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.