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

相关文章

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

在java中如何将inputStream对象转换为File对象(不生成本地文件)

《在java中如何将inputStream对象转换为File对象(不生成本地文件)》:本文主要介绍在java中如何将inputStream对象转换为File对象(不生成本地文件),具有很好的参考价... 目录需求说明问题解决总结需求说明在后端中通过POI生成Excel文件流,将输出流(outputStre

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark

C语言中的数据类型强制转换

《C语言中的数据类型强制转换》:本文主要介绍C语言中的数据类型强制转换方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C语言数据类型强制转换自动转换强制转换类型总结C语言数据类型强制转换强制类型转换:是通过类型转换运算来实现的,主要的数据类型转换分为自动转换

java streamfilter list 过滤的实现

《javastreamfilterlist过滤的实现》JavaStreamAPI中的filter方法是过滤List集合中元素的一个强大工具,可以轻松地根据自定义条件筛选出符合要求的元素,本文就来... 目录1. 创建一个示例List2. 使用Stream的filter方法进行过滤3. 自定义过滤条件1. 定

使用PyTorch实现手写数字识别功能

《使用PyTorch实现手写数字识别功能》在人工智能的世界里,计算机视觉是最具魅力的领域之一,通过PyTorch这一强大的深度学习框架,我们将在经典的MNIST数据集上,见证一个神经网络从零开始学会识... 目录当计算机学会“看”数字搭建开发环境MNIST数据集解析1. 认识手写数字数据库2. 数据预处理的

Redis中的常用的五种数据类型详解

《Redis中的常用的五种数据类型详解》:本文主要介绍Redis中的常用的五种数据类型详解,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Redis常用的五种数据类型一、字符串(String)简介常用命令应用场景二、哈希(Hash)简介常用命令应用场景三、列表(L