PyTorch之list、ndarray、tensor数据类型相互转换

2024-05-16 02:12

本文主要是介绍PyTorch之list、ndarray、tensor数据类型相互转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

温故而知新,可以为师矣!

一、参考资料

python中list、numpy、torch.tensor之间的相互转换

二、常用操作

list 转 numpy

ndarray = np.array(list)

import numpy as npa_list = [[j for j in range(5)] for i in range(3)]
a_ndarray = np.array(a_list)print(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'a_ndarray = {a_ndarray}, type of a_ndarray: {type(a_ndarray)}')

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
a_ndarray = [[0 1 2 3 4][0 1 2 3 4][0 1 2 3 4]], type of a_ndarray: <class 'numpy.ndarray'>

list 转 torch.Tensor

如何将装有tensor的多维list转化为torch.Tensor类型

普通 list 转 torch.Tensor

tensor=torch.Tensor(list)

# 普通list转tensor
a_list = [[j for j in range(5)] for i in range(3)]
A_tensor = torch.Tensor(a_list)print(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'A_tensor = {A_tensor}, type of A_tensor: {type(A_tensor)}')

注意:将list中元素类型为int,转换为tensor后,类型转换为float,如果希望转换为int,则需要加上类型。

A_tensor = torch.Tensor(a_list)  # 默认为float
A_tensor = torch.IntTensor(a_list)  # 转为int

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
A_tensor = tensor([[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.]]), type of A_tensor: <class 'torch.Tensor'>

list包含多维tensor

# list包含tensor,使用torch.Tensor会报错
a = torch.rand((2, 3))
a_list = [a for _ in range(3)]
A_tensor = torch.Tensor(a_list)

输出结果

raceback (most recent call last):File "/PATH/TO/demo.py", line 13, in <module>A = torch.Tensor(a_list)
ValueError: only one element tensors can be converted to Python scalars

解决办法

如果该方法无法解决该问题,请参考下文的FAQ。

# 在cpu上
A_tensor= torch.tensor([item.detach().numpy() for item in a_list])# 在gpu上
A_tensor= torch.tensor([item.cpu().detach().numpy() for item in a_list]).cuda() 

注意:因为 gpu上的 tensor 不能直接转为 numpy,需要先在 cpu 上完成操作,再回到 gpu 上。

numpy 转 list

list = ndarray.tolist()

import numpy as npa_list = [[j for j in range(5)] for i in range(3)]
a_ndarray = np.array(a_list)  # ndarray 转为 ndarray
A_list = a_ndarray.tolist()  # ndarray 转为 listprint(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'a_ndarray = {a_ndarray}, type of a_ndarray: {type(a_ndarray)}')
print(f'A_list = {A_list}, type of A_list: {type(A_list)}')

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
a_ndarray = [[0 1 2 3 4][0 1 2 3 4][0 1 2 3 4]], type of a_ndarray: <class 'numpy.ndarray'>
A_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of A_list: <class 'list'>

numpy 转 torch.Tensor

tensor = torch.from_numpy(ndarray)

import torch
import numpy as npa_list = [[j for j in range(5)] for i in range(3)]
a_ndarray = np.array(a_list)
a_tensor = torch.from_numpy(a_ndarray)print(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'a_ndarray = {a_ndarray}, type of a_ndarray: {type(a_ndarray)}')
print(f'a_tensor = {a_tensor}, type of a_tensor: {type(a_tensor)}')

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
a_ndarray = [[0 1 2 3 4][0 1 2 3 4][0 1 2 3 4]], type of a_ndarray: <class 'numpy.ndarray'>
a_tensor = tensor([[0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4]]), type of a_tensor: <class 'torch.Tensor'>

torch.Tensor 转 numpy

# CPU
ndarray = tensor.numpy()# GPU
ndarray = tensor.cpu().numpy()

注意:gpu上的tensor不能直接转为numpy,须要先在 cpu 上完成操做,再回到 gpu 上。

import torcha_list = [[j for j in range(5)] for i in range(3)]
# list转tensor
A_tensor = torch.Tensor(a_list)# CPU
A_ndarray = A_tensor.numpy()print(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'A_tensor = {A_tensor}, type of A_tensor: {type(A_tensor)}')
print(f'A_ndarray = {A_ndarray}, type of A_ndarray: {type(A_ndarray)}')

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
A_tensor = tensor([[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.]]), type of A_tensor: <class 'torch.Tensor'>
A_ndarray = [[0. 1. 2. 3. 4.][0. 1. 2. 3. 4.][0. 1. 2. 3. 4.]], type of A_ndarray: <class 'numpy.ndarray'>

torch.Tensor 转 list

tensor先转numpy,后转list。

list = tensor.numpy().tolist()

import torcha_list = [[j for j in range(5)] for i in range(3)]
# list转tensor
A_tensor = torch.Tensor(a_list)
# tensor先转numpy,再转list
A_list = A_tensor.numpy().tolist()print(f'a_list = {a_list}, type of a_list: {type(a_list)}')
print(f'A_tensor = {A_tensor}, type of A_tensor: {type(A_tensor)}')
print(f'A_list = {A_list}, type of A_list: {type(A_list)}')

输出结果

a_list = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], type of a_list: <class 'list'>
A_tensor = tensor([[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.],[0., 1., 2., 3., 4.]]), type of A_tensor: <class 'torch.Tensor'>
A_list = [[0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0]], type of A_list: <class 'list'>

三、FAQ

Q:ValueError: only one element tensors can be converted to Python scalars

Pytorch: list, numpy. Tensor 格式转化 (附 only one element tensors can be converted to Python scalars 解决)

ValueError:only one element tensors can be converted to Python scalars解决办法

错误原因:list包含多维tensor,导致类型转换错误。有以下两种解决方法。

方法一:torch.stack

通过torch.stack将包含tensor的多维list转换成tensor。
torch.stack要求两个输入的shape完全相同

b_tensor = torch.rand((2, 3))
b_list = [b_tensor for _ in range(3)]
B_tensor = torch.stack(b_list)print(f'b_tensor = {b_tensor}, type of b: {type(b_tensor)}')
print(f'b_list = {b_list}, type of b_list: {type(b_list)}')
print(f'B_tensor = {B_tensor}, type of B_tensor: {type(B_tensor)}, shape of B_tensor: {B_tensor.shape}')
b_tensor = tensor([[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]]), type of b: <class 'torch.Tensor'>
b_list = [tensor([[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]]), tensor([[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]]), tensor([[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]])], type of b_list: <class 'list'>
B_tensor = tensor([[[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]],[[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]],[[0.7443, 0.3041, 0.9545],[0.3092, 0.2747, 0.6717]]]), type of B_tensor: <class 'torch.Tensor'>, shape of B_tensor: torch.Size([3, 2, 3])

方法二:torch.cat

通过torch.cat将包含tensor的多维list转换成tensor。

b_tensor = torch.rand((2, 3))
b_list = [b_tensor for _ in range(3)]
B_tensor = torch.cat(b_list, 0)print(f'b_tensor = {b_tensor}, type of b: {type(b_tensor)}')
print(f'b_list = {b_list}, type of b_list: {type(b_list)}')
print(f'B_tensor = {B_tensor}, type of B_tensor: {type(B_tensor)}, shape of B_tensor: {B_tensor.shape}')
b_tensor = tensor([[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780]]), type of b: <class 'torch.Tensor'>
b_list = [tensor([[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780]]), tensor([[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780]]), tensor([[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780]])], type of b_list: <class 'list'>
B_tensor = tensor([[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780],[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780],[0.4237, 0.4743, 0.5213],[0.0815, 0.6654, 0.8780]]), type of B_tensor: <class 'torch.Tensor'>, shape of B_tensor: torch.Size([6, 3])

这篇关于PyTorch之list、ndarray、tensor数据类型相互转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/993577

相关文章

PyTorch高级特性与性能优化方式

《PyTorch高级特性与性能优化方式》:本文主要介绍PyTorch高级特性与性能优化方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、自动化机制1.自动微分机制2.动态计算图二、性能优化1.内存管理2.GPU加速3.多GPU训练三、分布式训练1.分布式数据

C语言中的常见进制转换详解(从二进制到十六进制)

《C语言中的常见进制转换详解(从二进制到十六进制)》进制转换是计算机编程中的一个常见任务,特别是在处理低级别的数据操作时,C语言作为一门底层编程语言,在进制转换方面提供了灵活的操作方式,今天,我们将深... 目录1、进制基础2、C语言中的进制转换2.1 从十进制转换为其他进制十进制转二进制十进制转八进制十进

Pandas进行周期与时间戳转换的方法

《Pandas进行周期与时间戳转换的方法》本教程将深入讲解如何在pandas中使用to_period()和to_timestamp()方法,完成时间戳与周期之间的转换,并结合实际应用场景展示这些方法的... 目录to_period() 时间戳转周期基本操作应用示例to_timestamp() 周期转时间戳基

通过C#获取Excel单元格的数据类型的方法详解

《通过C#获取Excel单元格的数据类型的方法详解》在处理Excel文件时,了解单元格的数据类型有助于我们正确地解析和处理数据,本文将详细介绍如何使用FreeSpire.XLS来获取Excel单元格的... 目录引言环境配置6种常见数据类型C# 读取单元格数据类型引言在处理 Excel 文件时,了解单元格

Java使用Stream流的Lambda语法进行List转Map的操作方式

《Java使用Stream流的Lambda语法进行List转Map的操作方式》:本文主要介绍Java使用Stream流的Lambda语法进行List转Map的操作方式,具有很好的参考价值,希望对大... 目录背景Stream流的Lambda语法应用实例1、定义要操作的UserDto2、ListChina编程转成M

使用Python开发Markdown兼容公式格式转换工具

《使用Python开发Markdown兼容公式格式转换工具》在技术写作中我们经常遇到公式格式问题,例如MathML无法显示,LaTeX格式错乱等,所以本文我们将使用Python开发Markdown兼容... 目录一、工具背景二、环境配置(Windows 10/11)1. 创建conda环境2. 获取XSLT

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

判断PyTorch是GPU版还是CPU版的方法小结

《判断PyTorch是GPU版还是CPU版的方法小结》PyTorch作为当前最流行的深度学习框架之一,支持在CPU和GPU(NVIDIACUDA)上运行,所以对于深度学习开发者来说,正确识别PyTor... 目录前言为什么需要区分GPU和CPU版本?性能差异硬件要求如何检查PyTorch版本?方法1:使用命

Java对象转换的实现方式汇总

《Java对象转换的实现方式汇总》:本文主要介绍Java对象转换的多种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java对象转换的多种实现方式1. 手动映射(Manual Mapping)2. Builder模式3. 工具类辅助映

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py