【问题标题】:How can I turn a torch tensor into a list of numpy arrays in Pytorch?如何将 Torch 张量转换为 Pytorch 中的 numpy 数组列表?
【发布时间】:2020-03-16 22:07:45
【问题描述】:

我有一个 Torch 张量,看起来像 torch.Size([32, 3, 64, 64])。

我正在尝试将张量转换为可以传递这些断言的东西:

assert(type(images) == list)
assert(type(images[0]) == np.ndarray)
assert(len(images[0].shape) == 3)
assert(np.max(images[0]) > 10)
assert(np.min(images[0]) >= 0.0)

我目前正在这样做以转换张量:

# turn tensor into list of lists
imgs = imgs.tolist()

# iterate over list and turn each image into a numpy array with normalized values
for idx, img in enumerate(imgs):
  img = cv2.normalize(np.array(img), None,
  alpha = 0, beta = 255, norm_type = cv2.NORM_MINMAX )

我得到这个错误:

File "scripts/run_model.py", line 158, in get_inception_score
assert(type(images[0]) == np.ndarray)
AssertionError

如何正确转换张量,使 type(images) 是一个列表,而 type(images[0] 是一个 np.ndarray)? 任何帮助将不胜感激。 提前谢谢你。

【问题讨论】:

    标签: python arrays numpy pytorch torchvision


    【解决方案1】:

    首先使用 tensor.numpy() 将 Pytorch 张量转换为 numpy 数组,然后使用内置的 list() 方法将其转换为列表。

    images = torch.randn(32,3,64,64)
    numpy_imgs = images.numpy()
    list_imgs = list(numpy_imgs)
    print(type(images))
    print(type(numpy_imgs))
    print(type(list_imgs))
    print(type(list_imgs[0]))
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 2019-06-13
      • 2019-10-23
      • 2020-12-12
      • 2020-06-27
      • 2019-07-29
      • 2021-02-24
      • 2019-04-27
      相关资源
      最近更新 更多