MobileNet是針對移動端優化的卷積,所以當需要壓縮模型時,可以考慮使用MobileNet替換卷積。下面我們開始學習MobileNet原理,並且先通過Tensorflow函數接口實現MobileNet,再手寫python代碼實現MobileNet。
轉載請註明出處:【huachao1001的專欄:https://blog.csdn.net/huachao1001/article/details/79171447】
1 對比普通卷積和MobileNet原理
MobileNet是用於替換普通卷積,相比普通卷積,MobileNet參數更少,計算速度更快。我們先看一下輸入爲(h=12,w=12,c=4),卷積爲3*3,輸出爲(h=12,w=12,c=2)前向計算中,普通卷積的參數量、乘法計算次數。普通卷積如下圖所示:
從上圖可以很簡單的計算到,普通卷積參數總數爲72個,需要做10368次乘法計算。
相比普通卷積,MobileNet採用的方法是,將卷積分解爲2個操作:depthwise和pointwise。pointwise比較容易理解,就是普通的卷積核爲1*1的卷積。depthwise採用的方法不是普通卷積方式,我們知道,對於輸入通道數爲4的feature map在計算卷積時,輸出的每個通道都需要對應4個3*3卷積核參數。這一步是最主要的耗時,爲了提升計算速度,MobileNet把每個輸入feature map對應一個3*3卷積核,輸出通道數不變,即爲4。而真正對通道數做改變的是在pointwise,也就是1*1的卷積。
注意:上面面論述針對的是輸入爲(h=12,w=12,c=4),卷積爲3*3,輸出爲(h=12,w=12,c=2) 這種情況舉例說明。
下面圖很清晰的理解mobilenet原理:
從上圖可以很簡單的計算到,普通卷積參數總數爲44個,需要做6336次乘法計算。可以看到,mobilenet的參數和乘法計算次數明顯比普通卷積要小。這還僅僅是我列舉的簡單例子,在實際網絡中,幾十層的網絡很常見,feature map也是遠遠大於12*12*4。根據我的經驗,普通100M的網絡模型,將所有卷積替換成mobilenet後,能降到20M以下,計算速度更是不在一個量級。
2 Tensorflow中使用MobileNet
在Tensorflow中,有depthwise對應的函數接口,直接調用就可以了。由於pointwise就是普通的卷積核大小爲1*1的卷積,而卷積的原理,我們在《Tensorflow卷積實現原理+手寫python代碼實現卷積》一文中已經講的很清楚了。所以我們只要關注depthwise即可。
在Tensorflow中,depthwise操作接口是:
tf.nn.depthwise_conv2d(
input,
filter,
strides,
padding,
rate=None,
name=None,
data_format=None
)
假設我們的輸入和卷積核如下:
#輸入,shape=[c,h,w]=[2,5,5]
input_data=[
[[1,0,1,2,1],
[0,2,1,0,1],
[1,1,0,2,0],
[2,2,1,1,0],
[2,0,1,2,0]],
[[2,0,2,1,1],
[0,1,0,0,2],
[1,0,0,2,1],
[1,1,2,1,0],
[1,0,1,1,1]],
]
#卷積核,shape=[in_c,k,k]=[2,3,3]
weights_data=[
[[ 1, 0, 1],
[-1, 1, 0],
[ 0,-1, 0]],
[[-1, 0, 1],
[ 0, 0, 1],
[ 1, 1, 1]]
]
下面我們貼上完整調用depthwise的代碼:
import tensorflow as tf
def get_shape(tensor):
[s1,s2,s3]= tensor.get_shape()
s1=int(s1)
s2=int(s2)
s3=int(s3)
return s1,s2,s3
def chw2hwc(chw_tensor):
[c,h,w]=get_shape(chw_tensor)
cols=[]
for i in range(c):
#每個通道里面的二維數組轉爲[w*h,1]即1列
line = tf.reshape(chw_tensor[i],[h*w,1])
cols.append(line)
#橫向連接,即將所有豎直數組橫向排列連接
input = tf.concat(cols,1)#[w*h,c]
#[w*h,c]-->[h,w,c]
input = tf.reshape(input,[h,w,c])
return input
def hwc2chw(hwc_tensor):
[h,w,c]=get_shape(hwc_tensor)
cs=[]
for i in range(c):
#[h,w]-->[1,h,w]
channel=tf.expand_dims(hwc_tensor[:,:,i],0)
cs.append(channel)
#[1,h,w]...[1,h,w]---->[c,h,w]
input = tf.concat(cs,0)#[c,h,w]
return input
def tf_depthwise(input,weights ):
depthwise=tf.nn.depthwise_conv2d( input, weights, [1, 1, 1, 1], padding='SAME' )
return depthwise
def main():
const_input = tf.constant(input_data , tf.float32)
const_weights = tf.constant(weights_data , tf.float32 )
input = tf.Variable(const_input,name="input")
#[2,5,5]------>[5,5,2]
input=chw2hwc(input)
#[5,5,2]------>[1,5,5,2]
input=tf.expand_dims(input,0)
weights = tf.Variable(const_weights,name="weights")
#[2,3,3]-->[3,3,2]
weights=chw2hwc(weights)
#[3,3,2]-->[3,3,2,1]
weights=tf.expand_dims(weights,3)
print(weights.get_shape().as_list())
#[b,h,w,c]
conv=tf_depthwise(input,weights )
rs=hwc2chw(conv[0])
init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
conv_val = sess.run(rs)
print(conv_val)
if __name__=='__main__':
main()
打印結果如下:
[[[ 1. -3. 0. 1. -2.]
[-1. 3. 1. -1. 3.]
[ 1. -1. 0. 3. -2.]
[ 1. 1. 1. -2. 1.]
[ 4. 1. 4. 2. -1.]]
[[ 1. 3. 2. 3. 2.]
[ 2. 1. 3. 4. 2.]
[ 3. 4. 5. 6. 1.]
[ 2. 3. 5. 4. 0.]
[ 1. 2. 1. -1. -1.]]]
我們通過一個動畫演示計算過程:
3 手寫python代碼實現depthwise
import numpy as np
input_data=[
[[1,0,1,2,1],
[0,2,1,0,1],
[1,1,0,2,0],
[2,2,1,1,0],
[2,0,1,2,0]],
[[2,0,2,1,1],
[0,1,0,0,2],
[1,0,0,2,1],
[1,1,2,1,0],
[1,0,1,1,1]]
]
weights_data=[
[[ 1, 0, 1],
[-1, 1, 0],
[ 0,-1, 0]],
[[-1, 0, 1],
[ 0, 0, 1],
[ 1, 1, 1]]
]
#fm:[h,w]
#kernel:[k,k]
#return rs:[h,w]
def compute_conv(fm,kernel):
[h,w]=fm.shape
[k,_]=kernel.shape
r=int(k/2)
#定義邊界填充0後的map
padding_fm=np.zeros([h+2,w+2],np.float32)
#保存計算結果
rs=np.zeros([h,w],np.float32)
#將輸入在指定該區域賦值,即除了4個邊界後,剩下的區域
padding_fm[1:h+1,1:w+1]=fm
#對每個點爲中心的區域遍歷
for i in range(1,h+1):
for j in range(1,w+1):
#取出當前點爲中心的k*k區域
roi=padding_fm[i-r:i+r+1,j-r:j+r+1]
#計算當前點的卷積,對k*k個點點乘後求和
rs[i-1][j-1]=np.sum(roi*kernel)
return rs
def my_depthwise(chw_input,chw_weights):
[c,_,_]=chw_input.shape
[_,k,_]=chw_weights.shape
#outputs=np.zeros([h,w],np.float32)
outputs=[] #注意跟conv的區別
#對每個feature map遍歷,從而對每個feature map進行卷積
for i in range(c):
#feature map==>[h,w]
f_map=chw_input[i]
#kernel ==>[k,k]
w=chw_weights[i]
rs =compute_conv(f_map,w)
#outputs=outputs+rs
outputs.append(rs) #注意跟conv的區別
return np.array( outputs)
def main():
#shape=[c,h,w]
input = np.asarray(input_data,np.float32)
#shape=[in_c,k,k]
weights = np.asarray(weights_data,np.float32)
rs=my_depthwise(input,weights)
print(rs)
if __name__=='__main__':
main()
同樣,註釋寫的很清楚,不再解釋代碼。運行結果如下:
[[[ 1. -3. 0. 1. -2.]
[-1. 3. 1. -1. 3.]
[ 1. -1. 0. 3. -2.]
[ 1. 1. 1. -2. 1.]
[ 4. 1. 4. 2. -1.]]
[[ 1. 3. 2. 3. 2.]
[ 2. 1. 3. 4. 2.]
[ 3. 4. 5. 6. 1.]
[ 2. 3. 5. 4. 0.]
[ 1. 2. 1. -1. -1.]]]
可以看到,跟tensorflow的結果是一模一樣。
我的博客即將搬運同步至騰訊雲+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=1dx8guzo2jdpp