np.pad()常用与深度学习中的数据预处理,可以将numpy数组按指定的方法填充成指定的形状。
np.pad()
对一维数组的填充
import numpy as np arr1D = np.array([1, 1, 2, 2, 3, 4]) ‘‘‘不同的填充方法‘‘‘ print ‘constant: ‘ + str(np.pad(arr1D, (2, 3), ‘constant‘)) print ‘edge: ‘ + str(np.pad(arr1D, (2, 3), ‘edge‘)) print ‘linear_ramp: ‘ + str(np.pad(arr1D, (2, 3), ‘linear_ramp‘)) print ‘maximum: ‘ + str(np.pad(arr1D, (2, 3), ‘maximum‘)) print ‘mean: ‘ + str(np.pad(arr1D, (2, 3), ‘mean‘)) print ‘median: ‘ + str(np.pad(arr1D, (2, 3), ‘median‘)) print ‘minimum: ‘ + str(np.pad(arr1D, (2, 3), ‘minimum‘)) print ‘reflect: ‘ + str(np.pad(arr1D, (2, 3), ‘reflect‘)) print ‘symmetric: ‘ + str(np.pad(arr1D, (2, 3), ‘symmetric‘)) print ‘wrap: ‘ + str(np.pad(arr1D, (2, 3), ‘wrap‘))
- 解释:
- 第一个参数是待填充数组
- 第二个参数是填充的形状,(2,3)表示前面两个,后面三个
- 第三个参数是填充的方法
- 填充方法:
- constant连续一样的值填充,有关于其填充值的参数。
constant_values=(x, y)
时前面用x填充,后面用y填充。缺参数是为0000。。。 - edge用边缘值填充
- linear_ramp边缘递减的填充方式
- maximum, mean, median, minimum分别用最大值、均值、中位数和最小值填充
- reflect, symmetric都是对称填充。前一个是关于边缘对称,后一个是关于边缘外的空气对称╮(╯▽╰)╭
- wrap用原数组后面的值填充前面,前面的值填充后面
- 也可以有其他自定义的填充方法
对多维数组的填充
import numpy as np arr3D = np.array([[[1, 1, 2, 2, 3, 4], [1, 1, 2, 2, 3, 4], [1, 1, 2, 2, 3, 4]], [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]], [[1, 1, 2, 2, 3, 4], [1, 1, 2, 2, 3, 4], [1, 1, 2, 2, 3, 4]]]) ‘‘‘对于多维数组‘‘‘ print ‘constant: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘constant‘)) print ‘edge: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘edge‘)) print ‘linear_ramp: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘linear_ramp‘)) print ‘maximum: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘maximum‘)) print ‘mean: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘mean‘)) print ‘median: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘median‘)) print ‘minimum: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘minimum‘)) print ‘reflect: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘reflect‘)) print ‘symmetric: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘symmetric‘)) print ‘wrap: \n‘ + str(np.pad(arr3D, ((0, 0), (1, 1), (2, 2)), ‘wrap‘))
原文地址:https://www.cnblogs.com/zongfa/p/8995739.html
时间: 2024-11-02 03:41:45