欢迎光临散文网 会员登陆 & 注册

PyTorch Tutorial 02 - Tensor Basics

2023-02-14 19:41 作者:Mr-南乔  | 我要投稿

教程Python代码如下:


import torch

import numpy as np


"""张量"""

#empty,空张量,值未初始化

x = torch.empty(1)

print(x)


x = torch.empty(3)

print(x)


x = torch.empty(2,3)

print(x)


x = torch.empty(2,2,3)

print(x)


#rand随机值张量

x = torch.rand(2,2)

print(x)


#zeros,0张量,这里x类型为float

x = torch.zeros(2,2)

print(x)


#ones,1张量

x = torch.ones(2,2)

print(x)

print(x.dtype)#这里x类型为float


#dtype,类型

x = torch.ones(2,2,dtype=torch.int)

print(x)

print(x.dtype)#这里x类型为int


x = torch.ones(2,2,dtype=torch.double)

print(x)

print(x.dtype)#这里x类型为double


#size(),大小

x = torch.ones(2,2,dtype=torch.double)

print(x.size())#torch.Size([2, 2])


#tensor

x = torch.tensor([2.5,0.1])

print(x)



"""加、减、乘运算"""

#加

x = torch.rand(2,2)

y = torch.rand(2,2)

print(x)

print(y)


z = x + y

print(z)


z = torch.add(x,y) #与z = x + y同

print(z)

print("z")


y.add_(x)

print(y)

print("y = y + x")


#减

x = torch.rand(2,2)

y = torch.rand(2,2)

print(x)

print(y)


z = x - y

z = torch.sub(x,y)

print(z)

print("z = x - y")

y.sub_(x)

print(y)

print("y = y - x")


#乘

x = torch.rand(2,2)

y = torch.rand(2,2)

print(x)

print(y)


z = x * y

z = torch.mul(x,y)

print(z)

print("z = x * y")

y.mul_(x)

print(y)

print("y = y * x")


#除

x = torch.rand(2,2)

y = torch.rand(2,2)

print(x)

print(y)


z = x / y

z = torch.div(x,y)

print(z)

print("z = x / y")


y.div_(x)

print(y)

print("y = y / x")


"""切片"""

x = torch.rand(5,3)

print(x)

print(x[0,:])#第一行

print(x[:,0])#第一列

print(x[0,0])#取某下标对应的元素

print(x[0,0].item())#item()的作用是从包含单个元素的张量中取出该元素的值,并保持元素类型不变,只有张量中只有一个元素时才能用item()方法


"""重塑"""

x = torch.rand(4,4)

print(x)


y = x.view(16)

print(y)


y = x.view(-1,8) #y = x.view(2,8),-1自动补齐

print(y)

print(y.size())


"""torch和numpy的转换"""

#torch转numpy

a = torch.ones(5)

print(a) #tensor([1., 1., 1., 1., 1.])

b = a.numpy()

print(b) #[1. 1. 1. 1. 1.]

print(type(b)) #<class 'numpy.ndarray'>


#a,b两个张量如果在CPU而不是GPU那么ab共享同一个位置,一个值改变另一个也会变,因为ab指向相同的内存位置

a.add_(1)

print(a) #tensor([2., 2., 2., 2., 2.])

print(b) #[2. 2. 2. 2. 2.]


#numpy转torch

a = np.ones(5)

print(a)

b = torch.from_numpy(a)

print(b)


a += 1

print(a)

print(b)


"""程序迁移至GPU"""

print("\n" + "程序迁移至GPU")

if torch.cuda.is_available():

device = torch.device("cuda")

#创建一个张量,并将其放在GPU上

x = torch.ones(5,device=device)

#先创建一个张量,再将其迁移到GPU上

y = torch.ones(5)

y = y.to(device)


z = x + y #这将会在GPU上执行,而且可能会快很多

print(z)

print("GPU z")

"""z.numpy()会报错,因为numpy()只能处理CPU张量,而不能处理GPU张量,所以不能把GPU张量转换回numpy,所以我们必须把其迁移回CPU"""

#将张量迁移回CPU

z = z.to("cpu")

print(z)

print("CPU z")

PyTorch Tutorial 02 - Tensor Basics的评论 (共 条)

分享到微博请遵守国家法律