【发布时间】:2017-07-29 03:22:02
【问题描述】:
我有一个形状为 (None, 56, 300, 1) 的张量 X,还有一个形状为 y 的张量 strong>(None, 15),这些张量的第一个维度是batch_size,我想用y作为索引得到一个张量z,z的形状是(None, 15, 300, 1) 。有什么体面的方法可以做到这一点吗?
我写了一个简单的代码来测试,因为我发现这对我来说很难,因为实际上我不知道batch_size(这些张量的第一维是None),
这是我的测试代码:
import numpy as np
import tensorflow as tf
# In this test code , batch_size is 4.
# params' shape is (4, 3, 2 ,1), in practice is (None, 56, 300, 1),
params = [
[[['a0'], ['b0']], [['d0'], ['e0']], [['f0'], ['g0']]],
[[['a1'], ['b1']], [['d1'], ['e1']], [['f1'], ['g1']]],
[[['a2'], ['b2']], [['d2'], ['e2']], [['f2'], ['g2']]],
[[['a3'], ['b3']], [['d3'], ['e3']], [['f3'], ['g3']]],
]
# ind's shape is (4, 2) (In practice is (None, 15)),
# so I wanna get output whose's shape is (4, 2, 2, 1), (In practice is (None, 15, 300, 1))
ind = [[1, 0], [0, 2], [2, 0], [2, 1]]
#ouput = [
# [[['d0'], ['e0']], [['a0'], ['b0']]],
# [[['a1'], ['b1']], [['f1'], ['g1']]],
# [[['f2'], ['g2']], [['a2'], ['b2']]],
# [[['f3'], ['g3']], [['d3'], ['e3']]]
#]
with tf.variable_scope('gather') as scope:
tf_par = tf.constant(params)
tf_ind = tf.constant(ind)
res = tf.gather_nd(tf_par, tf_ind)
with tf.Session() as sess:
init = tf.global_variables_initializer()
print sess.run(res)
print res
【问题讨论】:
-
能否添加您对示例代码的期望结果
-
混淆了,我的理解
[1, 0]应该是[['a1'], ['b1']],但你的期望是[['d0'], ['e0']] -
@YuwenYan [[['a0'], ['b0']], [['d0'], ['e0']], [['f0'], ['g0' ]]] 是第一个样本。 [1, 0] 响应第一个样本,所以答案应该是 [['d0'], ['e0']], [['a0'], ['b0']]。注意ind的长度为4,每个元素对params中每个样本的响应
标签: python tensorflow