简体   繁体   English

我如何迭代 pytorch 2d 张量?

[英]How do i iterate over pytorch 2d tensors?

X = np.array([
    [-2,4,-1],
    [4,1,-1],
    [1, 6, -1],
    [2, 4, -1],
    [6, 2, -1],
    ])

for epoch in range(1,epochs):
    for i, x in enumerate(X):

X = torch.tensor([
    [-2,4,-1],
    [4,1,-1],
    [1, 6, -1],
    [2, 4, -1],
    [6, 2, -1],
    ])

The looping was fine when it was an numpy array.当它是 numpy 阵列时,循环很好。 But i want to work with pytorch tensors so what's alternative to enumerate or How can i loop through the above tensor in the 2nd line?但是我想使用 pytorch 张量,那么有什么可以替代枚举或如何在第二行遍历上述张量?

enumerate expects an iterable, so it works just fine with pytorch tensors too: enumerate需要一个可迭代的,因此它也适用于 pytorch 张量:

X = torch.tensor([
    [-2,4,-1],
    [4,1,-1],
    [1, 6, -1],
    [2, 4, -1],
    [6, 2, -1],
    ])

for i, x in enumerate(X):
    print(x)
    tensor([-2,  4, -1])
    tensor([ 4,  1, -1])
    tensor([ 1,  6, -1])
    tensor([ 2,  4, -1])
    tensor([ 6,  2, -1])

If you want to iterate over the underlying arrays:如果要遍历底层 arrays:

for i, x in enumerate(X.numpy()):
    print(x)
    [-2  4 -1]
    [ 4  1 -1]
    [ 1  6 -1]
    [ 2  4 -1]
    [ 6  2 -1]

Do note however that pytorch's underlying data structure are numpy arrays, so you probably want to avoid looping over the tensor as you're doing, and should be looking at vectorising any operations either via pytorch or numpy. Do note however that pytorch's underlying data structure are numpy arrays, so you probably want to avoid looping over the tensor as you're doing, and should be looking at vectorising any operations either via pytorch or numpy.

x = torch.tensor([ 
                 [-2,4,-1],
                 [4,1,-1],
                 [1, 6, -1],
                 [2, 4, -1],
                 [6, 2, -1],
                          ])

for i in x:
    print(i)

output: output:

tensor([-2,  4, -1])
tensor([ 4,  1, -1])
tensor([ 1,  6, -1])
tensor([ 2,  4, -1])
tensor([ 6,  2, -1])

Iterating pytorch tensor or a numpy array is significantly slower than iterating a list.迭代 pytorch 张量或 numpy 数组比迭代列表慢得多。

Convert your tensor to a list and iterate over it:将您的张量转换为列表并对其进行迭代:

l = tens.tolist()

detach() is needed if you need to detach your tensor from a computation graph:如果需要从计算图中分离张量,则需要detach()

l = tens.detach().tolist()

Alternatively, you might use numpy array and use some of its fast functions on each row in your 2d array in order to get the values that you need from that row.或者,您可以使用 numpy 数组,并在二维数组的每一行上使用它的一些快速函数,以便从该行获取您需要的值。

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

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