【问题标题】:Better way to access individual elements in a tensor访问张量中单个元素的更好方法
【发布时间】:2019-01-31 07:12:04
【问题描述】:

我正在尝试使用张量 b 中定义的索引访问张量 a 的元素。

a=tf.constant([[1,2,3,4],[5,6,7,8]])
b=tf.constant([0,1,1,0])

我希望输出是

out = [1 6 7 4]

我尝试过的:

out=[]
for i in range(a.shape[1]):
    out.append(a[b[i],i])

out=tf.stack(out) #[1 6 7 4]

这给出了正确的输出,但我正在寻找一种更好、更紧凑的方法。

a 的形状类似于(2,None) 时,我的逻辑也不起作用,因为我无法使用range(a.shape[1]) 进行迭代,如果答案也包括这种情况,这将对我有所帮助

谢谢

【问题讨论】:

    标签: python python-3.x tensorflow


    【解决方案1】:

    您可以使用tf.one_hot()tf.boolean_mask()

    import tensorflow as tf
    import numpy as np
    
    a_tf = tf.placeholder(shape=(2,None),dtype=tf.int32)
    b_tf = tf.placeholder(shape=(None,),dtype=tf.int32)
    
    index = tf.one_hot(b_tf,a_tf.shape[0])
    out = tf.boolean_mask(tf.transpose(a_tf),index)
    
    a=np.array([[1,2,3,4],[5,6,7,8]])
    b=np.array([0,1,1,0])
    with tf.Session() as sess:
        print(sess.run(out,feed_dict={a_tf:a,b_tf:b}))
    
    # print
    [1 6 7 4]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 2015-09-21
      • 2020-09-11
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多