python pytorch教程_PyTorch教程-1:PyTorch中的Tensor基础

2022-09-29 11:48:25

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

首先,引入PyTorch的模块:

import torch

设置运算资源

使用 torch.cuda.is_avaliable() 来判断设备上的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,但是同样有dtype和device等参数

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实例的成员方法,传入的参数和上述一致,如果没有指定的参数(指dtype、device等参数)则继承原来的张量,但是维度信息必须传入:

```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

张量的运算

基本运算的几种方式

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

使用运算符运算: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与其他数据类型的转换

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

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

Tensor 转 ndarray:使用 Tensor.numpy() 将一个tensor转换成一个numpy的ndarray对象

tensor_x = torch.rand(2,3)

print(type(tensor_x))

ndarray_y = tensor_x.numpy()

print(type(ndarray_y))

ndarray 转 Tensor:使用 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))

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

list转Tensor:使用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))

Tensor转list:只能先转换成numpy数组,再通过numpy数组的tolist方法转换成list,没有直接转换的方法

list_b = tensor_x.numpy().tolist()

print(type(list_b))

将变量分配到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!

  • 作者:此用户已诈尸
  • 原文链接:https://blog.csdn.net/weixin_34811747/article/details/112891328
    更新时间:2022-09-29 11:48:25