无法将列表转换为数组:ValueError:只能将一个元素张量转换为Python标量

时间:2018-08-29 09:33:50

标签: python numpy pytorch numpy-ndarray

我目前正在使用PyTorch框架并试图了解外部代码。我遇到了索引问题,想打印列表的形状。
这样做的唯一方法(据Google告诉我)是将列表转换为numpy数组,然后使用numpy.ndarray.shape()获得形状。

但是尝试将列表转换成数组,却得到了ValueError: only one element tensors can be converted to Python scalars

“我的列表”是经过转换的PyTorch张量(list(pytorchTensor)),看起来像这样:

  

[张量([[-0.2781,-0.2567,-0.2353,...,-0.9640,-0.9855,-1.0069],
          [-0.2781,-0.2567,-0.2353,...,-1.0069,-1.0283,-1.0927],
          [-0.2567,-0.2567,-0.2138,...,-1.0712,-1.1141,-1.1784],
          ...,
          [-0.6640,-0.6425,-0.6211,...,-1.0712,-1.1141,-1.0927],
          [-0.6640,-0.6425,-0.5997,...,-0.9426,-0.9640,-0.9640],
          [-0.6640,-0.6425,-0.5997,...,-0.9640,-0.9426,-0.9426]]),张量([[--0.0769,-0.0980,-0.076 9,...,-0.9388,-0.9598, -0.9808],
          [-0.0559,-0.0769,-0.0980,...,-0.9598,-1.0018,-1.0228],
          [-0.0559,-0.0769,-0.0769,...,-1.0228,-1.0439,-1.0859],
          ...,
          [-0.4973,-0.4973,-0.4973,...,-1.0018,-1.0439,-1.0228],
          [-0.4973,-0.4973,-0.4973,...,-0.8757,-0.9177,-0.9177],
          [-0.4973,-0.4973,-0.4973,...,-0.9177,-0.8967,-0.8967]]),张量([[--0.1313,-0.1313,-0.110 0,...,-0.8115,-0.8328, -0.8753],
          [-0.1313,-0.1525,-0.1313,...,-0.8541,-0.8966,-0.9391],
          [-0.1100,-0.1313,-0.1100,...,-0.9391,-0.9816,-1.0666],
          ...,
          [-0.4502,-0.4714,-0.4502,...,-0.8966,-0.8966,-0.8966],
          [-0.4502,-0.4714,-0.4502,...,-0.8115,-0.8115,-0.7903],
          [-0.4502,-0.4714,-0.4502,...,-0.8115,-0.7690,-0.7690]])]

有没有一种方法可以获取列表的形状而不将其转换为numpy数组?

3 个答案:

答案 0 :(得分:4)

似乎您有张量列表。对于每个张量,您都可以看到其size()(无需转换为list / numpy)。如果坚持的话,可以使用numpy()将张量转换为numpy数组:

返回张量形状列表:

>> [t.size() for t in my_list_of_tensors]

返回numpy数组的列表:

>> [t.numpy() for t in my_list_of_tensors]

就性能而言,始终最好避免将张量转换为numpy数组,因为它可能导致设备/主机内存同步。如果只需要检查张量的shape,请使用size()函数。

答案 1 :(得分:1)

将pytorch张量转换为numpy数组的最简单方法是:

nparray = tensor.numpy()

此外,对于尺寸和形状:

tensor_size = tensor.size()
tensor_shape = tensor.shape()
tensor_size
>>> (1080)
tensor_shape
>>> (32, 3, 128, 128)

答案 2 :(得分:0)

一个真实的例子,需要处理 torch no grad issue

with torch.no_grad():
    probs = [t.numpy() for t in my_tensors]

probs = [t.detach().numpy() for t in my_tensors]