import numpy as np
def MaxPooling(image,kernel,step,padding):'''W`=((W-kernel+2*padding)/step)+1H`=((H-kernel+2*padding)/step)+1输入格式:image=(C,W,H)Kernel_size=(C,kernel_W,kernel_H)返回格式:result=(C,W`,H`)'''image_shape=image.shapeC=image_shape[0]W=image_shape[1]H=image_shape[2]Kernel_size=kernel.shapeHorizon_end=((H-Kernel_size[2]+2*padding)//step)+1Vertical_end=((W-Kernel_size[1]+2*padding)//step)+1result=[Kernel_size[0],Vertical_end,Horizon_end]result=np.zeros((result[0],result[1],result[2]))temp=0print("result.shape=",result.shape)
# for k in range (Kernel_size[0]):for v_sum in range (Vertical_end):for h_sum in range (Horizon_end):for c in range (C):
# temp+=np.sum((image[c][v_sum:v_sum+2,h_sum:h_sum+2])*(kernel[k][c]))temp=np.max((image[c][v_sum:v_sum+Kernel_size[1],h_sum:h_sum+Kernel_size[2]]))print("temp=",temp)result[c][v_sum][h_sum]=temp
# temp=0return result
a=np.array([[1,2],[3,4]])
print(np.max(a))
4
image=np.array([[[1,2,3,4],[1,2,3,4],[1,2,3,4],[0,1,2,3]]]*3)
kernel=np.array([[[2,2],[2,2]],[[1,1],[2,2]],[[1,1],[2,2]]])
print(image,'\n\n',kernel)
print(image.shape,kernel.shape)
[[[1 2 3 4][1 2 3 4][1 2 3 4][0 1 2 3]][[1 2 3 4][1 2 3 4][1 2 3 4][0 1 2 3]][[1 2 3 4][1 2 3 4][1 2 3 4][0 1 2 3]]] [[[2 2][2 2]][[1 1][2 2]][[1 1][2 2]]]
(3, 4, 4) (3, 2, 2)
print(MaxPooling(image,kernel,step=1,padding=0))
result.shape= (3, 3, 3)
temp= 2
temp= 2
temp= 2
temp= 3
temp= 3
temp= 3
temp= 4
temp= 4
temp= 4
temp= 2
temp= 2
temp= 2
temp= 3
temp= 3
temp= 3
temp= 4
temp= 4
temp= 4
temp= 2
temp= 2
temp= 2
temp= 3
temp= 3
temp= 3
temp= 4
temp= 4
temp= 4
[[[ 2. 3. 4.][ 2. 3. 4.][ 2. 3. 4.]][[ 2. 3. 4.][ 2. 3. 4.][ 2. 3. 4.]][[ 2. 3. 4.][ 2. 3. 4.][ 2. 3. 4.]]]
注意:
上面的kernel我就没有改成只是一个size的格式了,正常的池化层应该指定一个kernel的size就可以了,这里的kernel的size应该是(2,2)