繁体   English   中英

如何修复此错误:列表索引必须是整数或切片,而不是元组

[英]How to fix this error: list indices must be integers or slices, not tuple

假设我有一个称为outputs的张量列表

>> outputs[2][0][0,:,:]
Out[20]: 
tensor([[ 14.0448,  -5.1494,  -0.1780,  ...,  10.1937,  -8.9158,  -5.3964],
        [ 32.0382,  -0.5201,  29.9942,  ..., -18.8268, -23.1068,  23.9745],
        [-24.5911,  14.7233,  -6.3053,  ...,  -5.8131,  -3.3088,   0.5685],
        [  0.8842, -14.8318,   6.7204,  ...,  17.7127,   7.3332,   3.7249],
        [  2.0654, -16.5236,  38.3582,  ..., -23.1663,  -5.1202,  13.6506]],
       grad_fn=<SliceBackward>)


>> outputs[2][1][0,:,:]
Out[24]: 
tensor([[-0.1260,  0.0463, -0.3362,  ...,  0.1089, -0.2454,  0.0140],
        [ 0.5050, -0.0750, -0.1639,  ..., -0.0020, -0.0521, -0.3224],
        [-0.5311,  0.4526,  0.0079,  ..., -0.0654, -0.1255, -0.0012],
        [ 0.0728, -0.1219,  0.0905,  ...,  0.1354,  0.2730, -0.1186],
        [-0.0680, -0.5570,  0.0295,  ..., -0.2411, -0.1690,  0.0331]],
       grad_fn=<SliceBackward>)

当我尝试这样做时:

>> outputs[2][0:1][0,:,:]

python 生成错误,错误信息为

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

我该如何解决这个错误?

谢谢,

output outputs[2][0]outputs[2][1]都返回一个 object (我想是张量)。
outputs[2][0:1]返回这些对象的列表。
我认为您正在寻找的是类似outputs[2][0:1][:,0,:,:][a[0,:,:] for a in outputs[2][0:1]]

正如您要求的代码示例,这里是 go:

import torch

# using small shape to make it printable
outputs_2 = [torch.rand((3,2,1)) for _ in range(2)]

print(outputs_2[0][0,:,:])
# tensor([[0.3294],
#         [0.0031]])

print(outputs_2[1][0,:,:])
# tensor([[0.1910],
#         [0.1547]])

# this is the source of your problem
type(outputs_2[0:1])
# <class 'list'>

我不知道你期望的结果是什么。 这就是我的想法(我将使用[0:2]示例更清楚):

torch.stack(outputs_2[0:2])[:, 0, :, :]
# tensor([[[0.3294],
#          [0.0031]],
# 
#         [[0.1910],
#          [0.1547]]])

torch.stack(outputs_2[0:2]).shape
# torch.Size([2, 3, 2, 1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM