Tensorflow 用张量计算元素的邻域
假设我有下列张量Tensorflow 用张量计算元素的邻域,tensorflow,tensor,Tensorflow,Tensor,假设我有下列张量 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
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'中的每个元素,我想得到距离'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]
提前谢谢 我认为您只需要一个矩阵来充当
邻居遮罩
(请参见下面的代码)。实际上,这个想法与二维图像的工作原理非常相似
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
为中心的基本切片,并将其与掩码相乘
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.]]