tensor也可以作为索引

本文探讨了在TensorFlow框架下,如何正确地使用Tensor作为索引。Tensor可以用于索引同样为Tensor类型的变量,但不能直接用于list类型的变量。通过示例展示了将list转换为Tensor后,如何进行有效的索引操作。

在TensorFlow中,tensor也可以作为索引,但只能作为同样为tensor类型变量的索引,不能作为list类型变量的索引如下面的例子:

import tensorflow as tf

index = tf.to_int32([0,1,2])  # index是一个tensor
a = [[1,2,3], [4,5,6]]
b = a[index[0]]
sess = tf.InteractiveSession()
print(b)

TypeError: list indices must be integers or slices, not Tensor

若将a变为tensor类型

import tensorflow as tf

index = tf.to_int32([0,1,2])  # index是一个tensor
a = tf.convert_to_tensor([[1,2,3], [4,5,6]])
b = a[index[0]]
sess = tf.InteractiveSession()
print(sess.run(b))  # [1 2 3]

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值