当前位置:网站首页>PyTorch中的一些常见数据类型转换方法,与list和np.ndarray的转换方法
PyTorch中的一些常见数据类型转换方法,与list和np.ndarray的转换方法
2022-04-23 06:11:00 【小风_】
目录
0.导包
import torch
import numpy as np
import PIL
1.tensor类型转换
# 设置Torch默认类型
torch.set_default_tensor_type(torch.FloatTensor)
# CPU GPU # 数据类型
# torch.FloatTensor torch.cuda.FloatTensor # 32位浮点数
# torch.DoubleTensor torch.cuda.DoubleTensor # 64位浮点数
# torch.cuda.HalfTensor # 16位浮点数
# 类型转换
tensor = torch.rand(1,3,224,224)
tensor = tensor.float() # 转为float类型,其他:half() int() double() char() byte() short() long()
tensor = tensor.cuda() # 转为GPU对象
tensor = tensor.cpu() # 转为CPU对象
# type_as()方法
tensor1 = torch.rand(2,3)
tensor2 = torch.IntTensor(2,3)
tensor3 = tensor1.type_as(tensor2) # 将tensor1转为tensor2的类型
# print(tensor1,tensor2,tensor3)
2.tensor和list转换
'''tensor和list转换'''
tensor1 = torch.ones([1,5]) # 创建一个1x5的单位张量
list1 = tensor1.tolist() # tensor -> list
tensor1 = torch.tensor(list1) # list -> tensor
3.tensor和np.ndarray转换
'''tensor和np.ndarray转换'''
ndarray = tensor.numpy() # 注意GPU对象要先转为CPU对象
tensor = torch.from_numpy(ndarray) # 注意一般转为浮点数对象
4.图像tensor和图像ndarray转换,tensor -> cv2
'''图像tensor和图像ndarray转换,tensor -> cv2'''
# tensor的图像是维度信息是[N, C, H, W]
ndarray = np.random.random((3,224,224))
tensor = torch.tensor(ndarray).permute(2,0,1) #ndarray转tensor图像要注意维度是HWC->CHW
img = tensor.permute(1,2,0).cpu().numpy() #反之同理
5.cv2(ndarray)与PIL之间的转换
'''PIL.Image和np.ndarray转换,也可是cv2与PIL之间的转换'''
path = '1.jpg' #这里传入自己的图像地址
ndarray = np.asarray(PIL.Image.open(path)) #Image转ndarray
img = PIL.Image.fromarray(ndarray.astype(np.uint8)) #ndarray转Image
版权声明
本文为[小风_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_33952811/article/details/124293373
边栏推荐
- Itop4412 HDMI display (4.0.3_r1)
- [Andorid] 通过JNI实现kernel与app进行spi通讯
- Thanos.sh灭霸脚本,轻松随机删除系统一半的文件
- Apprentissage par composantes
- 素数求解的n种境界
- npm ERR code 500解决
- Cause: dx. jar is missing
- BottomSheetDialogFragment 与 ListView RecyclerView ScrollView 滑动冲突问题
- [exynos4412] [itop4412] [android-k] add product options
- 【2021年新书推荐】Red Hat Certified Engineer (RHCE) Study Guide
猜你喜欢
随机推荐
組件化學習
GEE配置本地开发环境
MySQL笔记5_操作数据
AVD Pixel_2_API_24 is already running.If that is not the case, delete the files at C:\Users\admi
oracle视图相关
oracle表的约束详解
Oracle Job定时任务的使用详解
记录webView显示空白的又一坑
Itop4412 HDMI display (4.0.3_r1)
机器学习笔记 一:学习思路
sys.dbms_scheduler.create_job创建定时任务(功能更强大丰富)
发布自定义插件到本地服务器
【2021年新书推荐】Learn WinUI 3.0
WebView displays a blank due to a certificate problem
webView因证书问题显示一片空白
JVM basics you should know
[2021 book recommendation] kubernetes in production best practices
adb shell 常用命令
oracle给对象重命名
MySQL笔记3_约束_主键约束


![[2021 book recommendation] artistic intelligence for IOT Cookbook](/img/8a/3ff45a911becb895e6dd9e061ac252.png)





