[PYTHON] numpy memorandum 1 / np.pad

1.First of all

I didn't understand how to use ** np.pad **, so I will leave the result of my investigation as a memorandum.

2.1 dimensional array

#One-dimensional array
img = np.array([1, 2, 3])
print(img)
print('img.shape = ', img.shape)
img = np.pad(img, [(1,2)], 'constant')
print(img)

スクリーンショット 2020-02-06 11.09.53.png ʻImg = np.pad (img, [(left 0 padding, right 0 padding)],'constant') `

3.2 dimensional array

#A two-dimensional array
img = np.array([[1, 2, 3], [4, 5, 6]])
print(img)
print('img.shape = ', img.shape)
img = np.pad(img, [(1,2), (3, 4)], 'constant')
print(img)

スクリーンショット 2020-02-06 11.17.57.png ʻImg = np.pad (img, [(top 0 padding, bottom 0 padding), (left 0 padding, right 0 padding)],'constant') `

4.3 dimensional array

#3D array
img = np.array( [[[1, 2, 3], [4, 5, 6]],  [[7, 8, 9], [0, 1, 2]]])    
print(img)
print('img.shape = ', img.shape)
img = np.pad(img, [(1,0), (1, 1), (1, 1)], 'constant')
print(img)

スクリーンショット 2020-02-06 12.46.43.png

Until now, only image padding was performed, but this time, specify how many ** 0 images ** (all filled with 0s) should be inserted before and after the image. Here, I put one in front. In other words

ʻImg = np.pad (img, [(0 images before, 0 images after), (0 padded top, 0 padded bottom), (0 padded left, 0 padded right)],'constant' ) `

5.4 dimensional array

#4D array
img = np.array([[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9],[0, 1, 2]]]])
print(img)
print('img.shape = ', img.shape)
img = np.pad(img, [(1,0), (1,0), (1, 1), (1, 1)], 'constant')
print(img)

スクリーンショット 2020-02-06 12.51.02.png

This time, add 0 images for the number of images created so far (padded image + 0 images) for the specified set before and after. Here, I put one set in front. In other words

ʻImg = np.pad (img, [(0 front 0 image set, back 0 image set), (0 front, 0 back), (0 top 0 padding, 0 bottom 0 padding), (left) 0 padding, right 0 padding)],'constant') `

6. Actual usage example

Consider the case of padding a 4-dimensional array img (mini-batch size, number of channels, height, width). Let ** p_h ** be the vertical padding and ** p_w ** be the horizontal padding. No padding in batch or channel direction is required, so

img = np.pad(img, [(0, 0), (0, 0), (p_h, p_h), (p_w, p_w)], 'constant')

Recommended Posts

numpy memorandum 1 / np.pad
Numpy type hint memorandum (NDArray)
Matplotlib memorandum
numpy practice 1
linux memorandum
jinja2 memorandum
Numpy [Basic]
Django memorandum
Command memorandum
NumPy basics
Python Memorandum 2
Numpy Memorandum_Matrix
plotly memorandum
numpy tips
Slackbot memorandum (1)
multiprocessing memorandum
Memorandum MetaTrader 5
[Linux/LPIC] Memorandum
ShellScript memorandum
pip memorandum
Python memorandum
About numpy
pydoc memorandum
python memorandum
Pandas memorandum
python memorandum
DjangoGirls memorandum
NumPy axis
Use Numpy
Command memorandum
numpy part 2
Python memorandum
pandas memorandum
python memorandum
Python memorandum