PyTorch教程-1:PyTorch中的Tensor基础

笔者PyTorch的全部简单教程请访问:https://www.jianshu.com/nb/48831659

PyTorch教程-1:PyTorch中的Tensor基础

首先,引入PyTorch的模块:

import torch

设置运算资源

使用 torch.cuda.is_available() 来判断设备上的GPU是否可用,如果可用则返回True,使用 torch.device() 则可以参数指定计算资源:

  • 参数为"cpu"表示使用CPU计算

  • 参数为"cuda"表示使用GPU计算,默认会使用第一块GPU,即"cuda:0"

  • 对于多GPU的设备,可以通过设置"cuda:N"来指定使用第几块GPU,第一块GPU是"cuda:0"

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    print(device)
    

    cuda
    

创建张量(tensors)

Pytorch中的基本数据类型是tensors(张量),和numpy中的ndarrays是非常相似的,而且可以互相转换,只是numpy中的多维数组只能在CPU上进行运算,而tensor则是PyTorch中设计的一种可以用于GPU高速运算的数据类型。

和numpy相似,PyTorch中也有很多方法来创建张量,这些方法的统一的几个常用参数为:

  • 前N个参数依次传入整数:张量的维度
  • dtype:数据类型,默认为torch.float32
    参数 数据类型
    torch.int 32位整数(等同于torch.int32)
    torch.int8, torch.int16, torch.int32, torch.int64 8位、16位、32位、64位整数
    torch.float 32位浮点数(等同于torch.float32)
    torch.float16, torch.float32, torch.float64 16位、32位、64位浮点数
    torch.double 64位浮点数(等同于torch.float64)
  • device:张量的目标存储设备,默认为CPU

创建张量的常用方法有:

  • torch.tensor:直接从数据创建,比如可以传入(多维)list

  • torch.empty:创建一个空的tensor

  • torch.rand:创建一个0-1之间随机数的tensor

  • torch.ones:创建全1的tensor

  • torch.zeros:创建全0的tensor

    一些例子:

    x = torch.tensor([1,2,3])
    y = torch.rand(2,2,dtype=torch.float)
    z = torch.ones(2,2,dtype=torch.int,device=device)
    print(x)
    print(y)
    print(z)
    

    tensor([1, 2, 3])
    tensor([[0.4366, 0.6651],
            [0.9753, 0.7331]])
    tensor([[1, 1],
            [1, 1]], device='cuda:0', dtype=torch.int32)
    
  • torch.full:这个方法和上述方法拥有不同的参数设置,其将前N个用于指定维数的参数换成:第一个参数为tuple指定维数,第二个参数为指定的值,创建一个该维度大小的全是指定值的tensor,但是同样有dtypedevice等参数

    x=torch.full((2,3),1.2,dtype=torch.float)
    print(x)
    

    tensor([[1.2000, 1.2000, 1.2000],
            [1.2000, 1.2000, 1.2000]])
    

基于已有的张量创建新的张量,可以使用new_系列的方法,和上面的方法类似,new_系列的方法在原有的方法前加上new_,是一个tensor实例的成员方法,传入的参数和上述一致,如果没有指定的参数(指dtypedevice等参数)则继承原来的张量,但是维度信息必须传入

```python
x = torch.rand(4,3,dtype=torch.float16,device=device)
y = x.new_ones(x.size(),dtype=torch.int16)
print(x)
print(y)
```

------

```
tensor([[0.5366, 0.9004, 0.8706],
        [0.9712, 0.2258, 0.4180],
        [0.7842, 0.9976, 0.4412],
        [0.5376, 0.7261, 0.4844]], device='cuda:0', dtype=torch.float16)
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]], device='cuda:0', dtype=torch.int16)
```

new_系列的方法有:

  • torch.new_tensor
  • torch.new_empty
  • torch.new_ones
  • torch.new_zeros
  • torch.new_full

张量的运算

基本运算的几种方式

张量之间的基本运算有几种不同的表达方式,这里以加法运算为例,列举一下几种不同方式,比如两个张量xy

  • 使用运算符运算:x+y

  • 使用torch的方法:torch.add(x,y)

  • 使用torch的方法时,传入out参数来设置结果的赋值对象:torch.add(x,y,out=z)

  • 使用_结尾的方法,完成类似于+=的操作:y.add_(x)

    x = torch.rand(3,2)
    y = torch.rand(3,2)
    
    z = x+y # method 1
    z = torch.add(x,y)  # method 2
    torch.add(x,y,out=z)    # method 3
    y.add_(x)   # method 4
    

常用的一些操作

一些张量的重要操作列在下边:

  • 获取张量的形状:使用 Tensor.size() 或者 Tensor.shape 获取张量的形状,返回的是一个tuple

  • 获取张量的维数:使用 Tensor.dim() 获取张量的维数

  • 切片操作:tensors的切片操作和numpy完全一致。(笔者另有一篇详细介绍关于numpy和list的索引、切片操作的文章,请移步:https://www.jianshu.com/p/dd166725a2c3

  • 改变形状:使用Tensor.view方法可以改变一个张量的形状,使用参数 -1 表示该维度的大小取决于其他维度

    x = torch.rand(4,6)
    print(x.size())
    y = x.view(2,12)
    print(y.size())
    z = x.view(8,-1)
    print(z.size())
    

    torch.Size([4, 6])
    torch.Size([2, 12])
    torch.Size([8, 3])
    
  • 从单元素的张量提出该单独元素的值:对于只包含一个元素的Tensor,使用 Tensor.item() 获取该元素

    x = torch.rand(1)
    print(x)
    print(x.item())
    

    tensor([0.5759])
    0.5759033560752869
    

其他的操作

Tensor还有很多各种各样的操作、方法、属性等,参考完整的列表:
https://pytorch.org/docs/stable/torch.html

Tensor与其他数据类型的转换

PyTorch的Tensor与Numpy的ndarray之间的转换

假设 tensor_x 是一个Tensor,ndarray_y 是一个ndarray:

  • Tensorndarray:使用 Tensor.numpy() 将一个tensor转换成一个numpyndarray对象

    tensor_x = torch.rand(2,3)
    print(type(tensor_x))
    ndarray_y = tensor_x.numpy()
    print(type(ndarray_y))
    

    <class 'torch.Tensor'>
    <class 'numpy.ndarray'>
    
  • ndarrayTensor:使用 torch.from_numpy(ndarray) 将一个ndarray转换成tensor

    ndarray_y = np.ones((2,3))
    print(type(ndarray_y))
    tensor_x = torch.from_numpy(ndarray_y)
    print(type(tensor_x))
    

    <class 'numpy.ndarray'>
    <class 'torch.Tensor'>
    

PyTorch的Tensor与Python的list之间的转换

  • listTensor:使用torch.tensor或者torch.Tensor均可:

    list_a = [[1,2,3],[4,5,6]]
    tensor_x = torch.tensor(list_a)
    tensor_y = torch.Tensor(list_a)
    print(type(tensor_x))
    print(type(tensor_y))
    

    <class 'torch.Tensor'>
    <class 'torch.Tensor'>
    
  • Tensorlist:只能先转换成numpy数组,再通过numpy数组的tolist方法转换成list,没有直接转换的方法

    list_b = tensor_x.numpy().tolist()
    print(type(list_b))
    

    <class 'list'>
    

将变量分配到GPU计算资源

我们已经知道如何设置计算资源,比如使用如下代码返回一个可用的设备(即优先使用GPU),如何将一个Tensor分配到对应的计算资源呢?有两种常用的方法:

  • 在创建Tensor时设置device参数将创建的变量直接发送到对应的设备,device参数默认为"cpu"

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    x = torch.rand(4,3,device=device)
    print(x)
    

    tensor([[0.1092, 0.7485, 0.1401],
            [0.2976, 0.3415, 0.6248],
            [0.7625, 0.6632, 0.7994],
            [0.8400, 0.1557, 0.6348]], device='cuda:0')
    
  • 使用tensor.to(device)方法将该tensor发送到目标设备,to方法接收的第一个参数为一个指定目标设备的字符串,第二个参数可以设置数据类型,默认为tensor原本的数据类型

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    x = torch.rand(4,3,device=device)
    y = x.to("cpu")
    print(y)
    print(y.device)
    z = x.to("cpu",torch.double)
    print(z)
    print(z.device)
    print(z.dtype)
    

    tensor([[0.3537, 0.3610, 0.1814],
            [0.8401, 0.1496, 0.6197],
            [0.7640, 0.5794, 0.1897],
            [0.6594, 0.3619, 0.3482]])
    cpu
    tensor([[0.3537, 0.3610, 0.1814],
            [0.8401, 0.1496, 0.6197],
            [0.7640, 0.5794, 0.1897],
            [0.6594, 0.3619, 0.3482]], dtype=torch.float64)
    cpu
    torch.float64
    

需要注意的是,两个张量之间如果发生运算,必须保证两个张量在统一运算资源下,否则会报错,所以有时需要通过上述方法进行调整。比如如下的代码验证了这一点:

x = torch.rand(3,2,device="cpu")
y = torch.rand(3,2,device="cuda")
try:
    z = x + y
except RuntimeError as e:
    print("Meet error because the two tensors aren't at the same device: \n{}".format(e))

Meet error because the two tensors aren't at the same device: 
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容