1

我在使用 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 中我不能

4

1 回答 1

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)

在张量流中它会有点不同。首先生成一个one_hot在第 2 轴值处具有 1 的张量:在索引处,然后将其与相应的索引相乘:

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)
于 2018-06-24T11:11:20.457 回答