2017-10-19 144 views
-1

考虑我我thave以下张量计算张量元素的邻居

r = 8 
c = 12 
n = 2 
a = np.arange(0, 96) 
o = tf.ones([(n*2)+1, (n*2)+1], tf.int32) 
m = tf.constant(a, tf.int32, [r,c]) 

[[ 0 1 2 3 4 5 6 7 8 9 10 11] 
[12 13 14 15 16 17 18 19 20 21 22 23] 
[24 25 26 27 28 29 30 31 32 33 34 35] 
[36 37 38 39 40 41 42 43 44 45 46 47] 
[48 49 50 51 52 53 54 55 56 57 58 59] 
[60 61 62 63 64 65 66 67 68 69 70 71] 
[72 73 74 75 76 77 78 79 80 81 82 83] 
[84 85 86 87 88 89 90 91 92 93 94 95]] 

k = tf.slice(m, [n ,n], [r - n*2, c - n*2]) 

[[26 27 28 29 30 31 32 33] 
[38 39 40 41 42 43 44 45] 
[50 51 52 53 54 55 56 57] 
[62 63 64 65 66 67 68 69]] 

为“K”我想要得到的邻居是“N每一个元素'远处。

例如

为 '26' 我想下面的张量

[[ 0 1 2 3 4 ] 
[12 00 00 00 16 ] 
[24 00 00 00 28 ] 
[36 00 00 00 40 ] 
[48 49 50 51 52]] 

在1D这将是

[0,1,2,3,4,12, 16,24,28,36,40,48,49,50,51,52]

在此先感谢!

回答

0

我想你只需要一个矩阵作为neighbor_mask(见下面的代码)。实际上这个想法与2D图像中convolution的工作方式非常相似。

import tensorflow as tf 
import numpy as np 
k = tf.cast(tf.constant(np.reshape(np.arange(96), [-1, 12])), 
      tf.float32) 
slice_centered_at_m = tf.slice(k, [0, 0], [5, 5]) 
neighbor_mask = tf.constant([[1, 1, 1, 1, 1], 
          [1, 0, 0, 0, 1], 
          [1, 0, 0, 0, 1], 
          [1, 0, 0, 0, 1], 
          [1, 1, 1, 1, 1]], 
       tf.float32) 
with tf.Session() as sess: 
    print sess.run(slice_centered_at_m * neighbor_mask) 

>> [[ 0. 1. 2. 3. 4.] 
    [ 12. 0. 0. 0. 16.] 
    [ 24. 0. 0. 0. 28.] 
    [ 36. 0. 0. 0. 40.] 
    [ 48. 49. 50. 51. 52.]] 

为了得到邻居的任意元素m,只需使用一个方法来获得在m为中心的基本切片,并用口罩相乘。