theano實現k-max poling for CNNs

    各位大神都有自己實現自己的k-max Poling的方法,簡單搜索了下用theano實現k-max poling的相關文章,但是確實比較少,也許是各種大神覺得這是個特別簡單的問題,所以不屑於發佈或者給予發佈問題者回答此類問題,下面我給出我自己的實現代碼,希望可以解決一部分人的問題:


def k_max_poling(x_conv_hidden, k, hid_dim, map_count):
    '''
         k-max poling for CNNs if the feature maps are columns argsort(axis = 0)[-k:, :] else argsort(axis = 1)[:, -k:] 
         @ x_conv_hidden: hidden map generated by convolution layer
         @ k: number for max values<pre name="code" class="python">         @ hid_dim: dimension of hidden units'''<pre name="code" class="python">    sorted_indices = x_conv_hidden.argsort(axis = 0)[-k:, :].sort(axis = 0)<pre name="code" class="python">    return T.concatenate([x_conv_hidden[:, i].reshape([hid_dim, ], ndim = 1)[sorted_indices[:, i]].reshape([k, 1], ndim = 2) for i in xrange(map_count)], axis = 1)


代碼解釋:

sorted_indices = x_conv_hidden.argsort(axis = 0)[-k:, :].sort(axis = 0)
  index操作:首先用 .argsort(axis = 0) 對每一列進行降序排列得到並獲取排序後的feature map在源feature map中對應的位置;其次,[-k:, :] .sort(axis = 0)取出所有feature map的top k個數(順序與各元素在源feature map中的相對位置一致);

for i in xrange(map_count)
   對於每一個feature map 執行如下操作:

x_conv_hidden[:, i].reshape([hid_dim, ], ndim = 1)[sorted_indices[:, i]].reshape([k, 1], ndim = 2)
   將每個feature map扁平化成向量,並且取出對應的top k個數後,將其轉化爲原來的feature map格式(column)

return T.concatenate([], axis = 1)
   最後對所有feature maps重新組合,返回得到k-max poling結果。


就這麼兩行代碼就解決問題,這個是對於feature map是vector的情況,至於對於feature map 是matrix的情況需要運行兩次,將第一次運行得到的結果作爲第二次 運行的輸入,並且對於feature map是row的情況,將行列互換即可(可以根據自己的實際需要進行靈活轉換)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章