简体   繁体   English

如何将火炬张量转换为 Pytorch 中的 numpy arrays 列表?

[英]How can I turn a torch tensor into a list of numpy arrays in Pytorch?

I have a torch tensor that looks like torch.Size([32, 3, 64, 64]).我有一个看起来像 torch.Size([32, 3, 64, 64]) 的火炬张量。

I'm trying convert the tensor into something that can pass these assertions:我正在尝试将张量转换为可以传递这些断言的东西:

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)

I'm currently doing this to convert the tensor:我目前正在这样做以转换张量:

# 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 )

and I get this error:我得到这个错误:

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

How can I convert the tensor correctly so that type(images) is a list and type(images[0] is a np.ndarray)?如何正确转换张量,使 type(images) 是一个列表,而 type(images[0] 是一个 np.ndarray)? Any help would be greatly appreciated.任何帮助将不胜感激。 Thank you in advance.先感谢您。

Convert Pytorch tensor to numpy array first using tensor.numpy() and then convert it into a list using the built-in list() method.首先使用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]))

<class 'torch.Tensor'> <class 'torch.Tensor'>

<class 'numpy.ndarray'> <类'numpy.ndarray'>

<class 'list'> <类'列表'>

<class 'numpy.ndarray'> <类'numpy.ndarray'>

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

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