下图描述了在应用最大池化层之前,单个中间滤波层输出的情况。我希望存储箭头左侧矩阵中右下角强度为4的像素的坐标,这个像素在箭头左侧矩阵中的坐标为(4,4)(基于1的索引),在箭头右侧矩阵的右下角单元格中存储的是这个像素。现在,我想将这个坐标值(4,4)以及其他像素的坐标{(2,2)对应强度为6的像素,(2, 4)对应强度为8的像素,(3, 1)对应强度为3的像素}存储为一个列表,以便后续处理。如何在TensorFlow中实现这一点?
使用大小为2 x 2的滤波器和步长为2进行的最大池化
回答:
你可以使用 tf.nn.max_pool_with_argmax
(链接)。 注意:
argmax中的索引是平坦化的,因此位置[b, y, x, c]的最大值变为平坦化索引 ((b * height + y) * width + x) * channels + c。
我们需要进行一些处理以使其适应你的坐标。一个示例:
import tensorflow as tfimport numpy as npdef max_pool_with_argmax(net,filter_h,filter_w,stride): output, mask = tf.nn.max_pool_with_argmax( net,ksize=[1, filter_h, filter_w, 1], strides=[1, stride, stride, 1],padding='SAME') # 如果你的ksize看起来像[1, stride, stride, 1] loc_x = mask // net.shape[2] loc_y = mask % net.shape[2] loc = tf.concat([loc_x+1,loc_y+1],axis=-1) #从0开始计数,所以加1 # 如果你的ksize全部在变化,使用以下代码 # c = tf.mod(mask,net.shape[3]) # remain = tf.cast(tf.divide(tf.subtract(mask,c),net.shape[3]),tf.int64) # x = tf.mod(remain,net.shape[2]) # remain = tf.cast(tf.divide(tf.subtract(remain,x),net.shape[2]),tf.int64) # y = tf.mod(remain,net.shape[1]) # remain = tf.cast(tf.divide(tf.subtract(remain, y), net.shape[1]),tf.int64) # b = tf.mod(remain, net.shape[0]) # loc = tf.concat([y+1,x+1], axis=-1) return output,locinput = tf.Variable(np.random.rand(1, 6, 4, 1), dtype=np.float32)output, mask = max_pool_with_argmax(input,2,2,2)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) input_value,output_value,mask_value = sess.run([input,output,mask]) print(input_value[0,:,:,0]) print(output_value[0,:,:,0]) print(mask_value[0,:,:,:])#print[[0.20101677 0.09207255 0.32177696 0.34424785] [0.4116488 0.5965447 0.20575707 0.63288754] [0.3145412 0.16090539 0.59698933 0.709239 ] [0.00252096 0.18027237 0.11163216 0.40613824] [0.4027637 0.1995668 0.7462126 0.68812144] [0.8993007 0.55828506 0.5263306 0.09376772]][[0.5965447 0.63288754] [0.3145412 0.709239 ] [0.8993007 0.7462126 ]][[[2 2] [2 4]] [[3 1] [3 4]] [[6 1] [5 3]]]
你可以看到,强度为0.5965447的像素的坐标为(2,2),强度为0.63288754的像素的坐标为(2, 4),依此类推。