用索引将Tensorflow合并三个图像

时间:2018-06-23 04:04:56

标签: numpy tensorflow keras deep-learning max-pooling

我在使用Tensorflow时遇到问题。我有四个图像及其相应的索引。我想从他们那里做一个形象。我尝试了循环,tf.gather,tf.assign等,但是都显示错误。如果有人帮助我,将不胜感激。我用一个小例子解释我的问题: 我们有4个张量及其来自张量tf.ktop函数的索引:(为简单起见,我像MATLAB一样写)

a = [1, 2; 5, 6] a_idx = [0, 1; 2, 3] b = [3, 4; 7, 8] b_idx = [0, 1; 2, 3] c = [9, 10; 13, 14] c_idx = [0, 1; 2, 3] d = [11, 12; 15, 16] d_idx = [0, 1; 2, 3]

我正在从a,b,c和d以及它们的索引中寻找大图像:

image = [a b; c d] image = [1, 2, 3, 4; 5, 6, 7, 8;9 10, 11, 12;13, 14, 15, 16]

在python中,我有类似的东西:

a, a_idx, b, b_idx, c, c_idx, d, d_idx

n_x = tf.Variable(tf.zeros([1, 4, 4, 1]))

n_patches = tf.extract_image_patches(
    n_x,
    [1, 2, 2, 1],
    [1, 2, 2, 1],
    [1, 1, 1, 1],
    "SAME"
)

因此,n_patches是4个张量,我需要将a到d的值放到与a_idx到d_idx对应的每个补丁中。在MATLAB或Numpy中使用for循环对我来说真的很容易,但是在tensorflow中我不能

1 个答案:

答案 0 :(得分:0)

在您的评论中,我怀疑您在所需的输出image中犯了一个小错误。

我解释你想要的被给予

values = np.array([[2, 5],\
                   [4, 6]])
indices = np.array([[0, 3],\
                    [2, 1]])

您的结果将是

[[2. 0. 0. 0.]
 [0. 0. 0. 5.]
 [0. 0. 4. 0.]
 [0. 6. 0. 0.]]

因此,您想获得一种热编码矩阵,但其值与给定索引相对应。可以这样获得:

import numpy as np
values = np.array([[2, 5],\
                   [4, 6]])
indices = np.array([[0, 3],\
                    [2, 1]])

# Make a matrix with only zeros
n_hots = np.zeros_like((indices))
# Now row 0,1,2 and 3 should have values corresponding to the
# indices. That is we should first "unpack" the values and indices:
indices=indices.ravel()
values=values.ravel()
# values are now: [2,5,4,6]
# indices are now: [0,3,2,1]
# values:
# n_hots[row,indices[row]]=values[indices[row]]
# e.g.
# n_hots[0,0]=2
# n_hots[1,3]=5
# n_hots[2,2]=4
# n_hots[3,1]=6
# Notice how the first slices are a ascending range of values:
# [0,1,2,3], and the second slice are the raveled indices, and the
# right hand side of the equal sign are the ravele values!
# That means we can just do the following:
n_hots[np.arange(4),indices]=values
print(n_hots)

在tensorflow中会有所不同。首先生成一个one_hot张量,该张量的第二个轴值是:在索引处,然后将其与相应的索引相乘:

import numpy as np
import tensorflow as tf

indices=tf.placeholder(shape=(None),dtype=tf.int32)
values=tf.placeholder(shape=(None),dtype=tf.float32)
one_hots=tf.one_hot(indices, tf.shape(indices)[0])
n_hots=one_hots*tf.gather(values, indices)

with tf.Session() as sess:
    _values = np.array([[2, 5],\
                       [4, 6]])
    _indices = np.array([[0, 3],\
                        [2, 1]])
    n_h=sess.run(n_hots, {indices: _indices.ravel(), values:_values.ravel()})
    print(n_h)