栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch中的数据类型和相互转换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

torch中的数据类型和相互转换

文章目录
      • 1 torch.Tensor
      • 2 Data types
      • 3 Initializing and basic operations
        • 1)使用torch.tensor() 创建
        • 2)使用python list创建
        • 3)使用zeros ones函数创建
        • 4)通过torch.dtype指定类型, torch.device指定构造器
        • 5)零维张量
        • 6)torch.Tensor.item()从包含单个值的张量中获取Python数字
      • 4 type changes
        • 1)tensor间类型转换
        • 2)数据存储位置转换
        • 3)与Python数据类型转换
        • 4)剥离出一个tensor参与计算,但不参与求导

官网链接

1 torch.Tensor

A torch.Tensoris a multi-dimensional matrix containing elements of a single data type.
torch.Tensor 是包含单一数据类型的多维矩阵

2 Data types

Torch定义了10种不同CPU和GPU的张量类型,下面摘录常用的几种

Data typedtypeCPU tensorGPU tensor
32-bit floating pointtorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64-bit floating pointtorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
32-bit integer (signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64-bit integer (signed)torch.int64 or torch.longtorch.LongTensortorch.cuda.LongTensor
Booleantorch.booltorch.BoolTensortorch.cuda.BoolTensor

torch.Tensor is an alias for the default tensor type (torch.FloatTensor).
torch.Tensor 是默认张量类型(torch.FloatTensor)的别名

CPU张量在torch中,GPU张量在torch.cuda包中

从CPU转换到GPU,有一个to(device)的张量方法,可以创建张量的副本到指定设备(可以是CPU或GPU)

  • GPU设备可以在冒号之后指定一个可选设备的索引。例如,系统中的第二个GPU可以用“cuda:1”寻址(索引从零开始)
  • 另一种更为有效的方法是使用torch.device类,该类接受设备名称和可选索引。它有device属性,所以可以访问张量当前所在的设备。

从GPU转换到CPU,使用.cpu()方法

3 Initializing and basic operations 1)使用torch.tensor() 创建

2)使用python list创建

3)使用zeros ones函数创建

4)通过torch.dtype指定类型, torch.device指定构造器

5)零维张量

就是数字,比如说是某些操作的求和结果
可以使用torch.tensor()函数创建

6)torch.Tensor.item()从包含单个值的张量中获取Python数字

必须是单个值才行!!!!

4 type changes

参考

1)tensor间类型转换
  • 在Tensor后加.long(), .int(), .float(), .double()等
  • 也可以用.to()函数进行转换
2)数据存储位置转换

CPU张量 ----> GPU张量,使用data.cuda() 或者 data.to()
GPU张量 ----> CPU张量,使用data.cpu()

3)与Python数据类型转换

1 torch.Tensor ----> 单个Python数据,使用data.item(),data为Tensor变量且只能为包含单个数据

2 torch.Tensor ----> Python list,使用data.tolist(),data为Tensor变量,返回shape相同的可嵌套的list

3 torch.Tensor ----> numpy,使用data.numpy(),data为Tensor变量

4 numpy ----> torch.Tensor,tensor = torch.from_numpy(ndarray)

5 list ----> numpy ,使用np.array(list)
6 numpy----> list ,使用.tolist()

参考

4)剥离出一个tensor参与计算,但不参与求导

Tensor后加 .detach()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号