代码:
import numpy as np
def conv_per_kernel(feat,kernel,s,p):
c, h, w = feat.shape
c, k, _ = kernel.shape
newh = int((h + 2 * p - k) / s) + 1
neww = int((w + 2 * p - k) / s) + 1
res = np.zeros([newh, neww])
temp=np.zeros([h+2*p,w+2*p])
temp[p:-p,p:-p]=feat
for i in range(newh):
for j in range(neww):
center_i=i+k/2+s*i
center_j=j+k/2+s*j
start_i=center_i-k/2
end_i=center_i+k/2
start_j=center_j-k/2
end_j=center_j+k/2
sum=0
for m in range(start_i,end_i+1):
for n in range(start_j,end_j+1):
for u in range(k):
sum+=temp[m,n,u]*kernel[m-start_i,n-start_j,u]
res[i,j]=sum
return res
def conv_per_batch(feat,kernel,s,p):
c, h, w = feat.shape
o, c, k, _ = kernel.shape
newh=int((h+2*p-k)/s)+1
neww=int((w+2*p-k)/s)+1
res=np.zeros([o,newh,neww])
for i in range(o):
res[i,:,:]=conv_per_kernel(feat,kernel[i,:,:,:],s,p)
return res
def conv3d(featuremap,kernel,stride,padding):
b,c,h,w=featuremap.shape
o,c,ks,_=kernel.shape
s=stride
p=padding
res=[]
for i in range(b):
out=conv_per_batch(featuremap[i,:,:,:],kernel,s,p)
res.append(out)
res=np.asarray(res)
return res
if __name__=='__main__':
pass
思路:
把整个过程梳理了一下,如有不对的地方,请指正;
|