How to use tf.gather similar to the numpy slicing(如何使用类似于麻木切片的tf.ather)
本文介绍了如何使用类似于麻木切片的tf.ather的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个索引列表,表示我要访问的行和列。
r= np.array([0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3])
c = np.array([0, 0, 1, 1, 4, 4, 1, 1, 3, 3, 5, 5])
当我将它们用作[r,c]时,我能够获取numpy数组中的相应元素。
arr = np.array([[517.0, 1876.0, 4716.0, 2725.0, 2138.0, 2213.0],
[517.0, 1876.0, 4716.0, 2725.0, 2138.0, 2213.0],
[3745.0, 3103.0, 885.0, 3482.0, 4196.0, 1802.0],
[3745.0, 3103.0, 885.0, 3482.0, 4196.0, 1802.0],
[1548.0, 610.0, 3936.0, 905.0, 3791.0, 3657.0],
[1548.0, 610.0, 3936.0, 905.0, 3791.0, 3657.0],
[971.0, 573.0, 4756.0, 2137.0, 1407.0, 4388.0],
[971.0, 573.0, 4756.0, 2137.0, 1407.0, 4388.0],
[2786.0, 4769.0, 3391.0, 940.0, 2188.0, 1823.0],
[2786.0, 4769.0, 3391.0, 940.0, 2188.0, 1823.0],
[3225.0, 3262.0, 3444.0, 783.0, 3931.0, 1546.0],
[3225.0, 3262.0, 3444.0, 783.0, 3931.0, 1546.0]])
print(mst_array[r, c])
[ 517. 517. 1876. 1876. 2138. 2138. 3103. 3103. 3482. 3482. 1802. 1802.]
我想在tf中执行相同的操作,并且正在使用tf.gather。
https://www.tensorflow.org/api_docs/python/tf/gather
t_r = tf.convert_to_tensor(r, dtype= tf.int32)
t_c = tf.convert_to_tensor(c, dtype= tf.int32)
t_arr = tf.convert_to_tensor(arr, dtype= tf.int32)
print(t_r, "
", t_c, "
")
tf.Tensor([0 1 0 1 0 1 2 3 2 3 2 3], shape=(12,), dtype=int32)
tf.Tensor([0 0 1 1 4 4 1 1 3 3 5 5], shape=(12,), dtype=int32)
我尝试了不同的命令,但未能获得与numpy中相同的结果。
tf.gather(t_arr, [t_r, t_c], axis=-1)
tf.gather(t_arr, [t_r, t_c], axis=-1).shape_as_list()
推荐答案
尝试tf.stack使用tf.gather_nd:
z = tf.gather_nd(t_arr, tf.stack([t_r, t_c], axis=1))
tf.Tensor([ 517 517 1876 1876 2138 2138 3103 3103 3482 3482 1802 1802], shape=(12,), dtype=int32)
这篇关于如何使用类似于麻木切片的tf.ather的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:如何使用类似于麻木切片的tf.ather
基础教程推荐
猜你喜欢
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
