一、Pytorch安装
安装cuda和cudnn,例如cuda10,cudnn7.5
官网下载torch:https://pytorch.org/ 选择下载相应版本的torch 和torchvision的whl文件
使用pip install whl_dir安装torch,并且同时安装torchvision
二、初步使用pytorch
#-*- coding:utf-8 -*-
__author__ = 'Leo.Z'
importtorchimporttime#查看torch版本
print(torch.__version__)#定义矩阵a和b,随机值填充
a = torch.randn(10000, 1000)
b= torch.randn(1000, 2000)#记录开始时间
t0 =time.time()#计算矩阵乘法
c =torch.matmul(a, b)#记录结束时间
t1 =time.time()#打印结果和运行时间
print(a.device, t1 - t0, c.norm(2)) #这里的c.norm(2)是计算c的L2范数
#使用GPU设备
device = torch.device('cuda')#将ab搬到GPU
a =a.to(device)
b=b.to(device)#运行,并记录运行时间
t0 =time.time()
c=torch.matmul(a, b)
t1=time.time()#打印在GPU上运行所需时间
print(a.device, t1 - t0, c.norm(2))#再次运行,确认运行时间
t0 =time.time()
c=torch.matmul(a, b)
t1=time.time()print(a.device, t1 - t0, c.norm(2))
运行结果如下:
1.1.0
cpu0.14660906791687012 tensor(141129.3906)
cuda:00.19049072265625 tensor(141533.1250, device='cuda:0')
cuda:00.006981372833251953 tensor(141533.1250, device='cuda:0')
我们发现,两次在GPU上运行的时间不同,第一次时间甚至超过CPU运行时间,这是因为第一次运行有初始化GPU运行环境的时间开销。
三、自动求导
#-*- coding:utf-8 -*-
__author__ = 'Leo.Z'
importtorch#定义a b c x的值,abc指定为需要求导requires_grad=True
x = torch.tensor(2.)
a= torch.tensor(1., requires_grad=True)
b= torch.tensor(2., requires_grad=True)
c= torch.tensor(3., requires_grad=True)#定义y函数
y = a * x ** 2 + b * x +c;#使用autograd.grad自定求导
grads =torch.autograd.grad(y, [a, b, c])#打印abc分别的导数值(带入x的值)
print('after', grads[0],grads[1],grads[2])
四、pytorch数据类型
查看数据的类型:
#-*- coding:utf-8 -*-
__author__ = 'Leo.Z'
importtorch
a= torch.randn(2, 3)print(a.type()) #打印torch.FloatTensor
print(type(a)) #打印
print(isinstance(a, torch.FloatTensor)) #打印True
print(isinstance(a, torch.cuda.FloatTensor)) #打印False#将a放到GPU中
a = a.to(torch.device('cuda'))#或这样也可以
a =a.cuda()print(isinstance(a, torch.cuda.FloatTensor)) #打印True
查看数据的维度等信息:
#-*- coding:utf-8 -*-
__author__ = 'Leo.Z'
importtorch
a= torch.randn(2, 3)#b是一个dim为0的标量(就是一个数)
b = torch.tensor(2.2)#查看shape
print(a.shape) #返回torch.Size([2,3])
print(b.shape) #返回torch.Size([])
print(len(a.shape)) #返回2
print(len(b.shape)) #返回0,表示dim为0#size()和shape是一样的,size是成员函数,shape是成员属性
print(a.size()) #返回torch.Size([2,3])
print(a.size(0)) #返回2
print(a.size(1)) #返回3
print(b.size()) #返回torch.Size([])#返回a的维度,返回2,表示2D矩阵
print(a.dim())
五、pytorch基本使用
定义数据:
#-*- coding:utf-8 -*-
__author__ = 'Leo.Z'
importtorchimportnumpy as np#建议使用torch.tensor()来直接赋值
a = torch.tensor([1., 2., 3.]) #直接赋值(建议)#不建议用FloatTensor来直接赋值,避免混淆
a_2 = torch.FloatTensor([1.,2.,3.]) #也可以用FloatTensor赋值
#建议使用FloatTensor传入shape来定义数据结构
b = torch.FloatTensor(1) #参数表示shape,这里是2个元素的向量,值未初始化,可能很大或很小
c = torch.FloatTensor(3, 2) #这里表示维度为[3,2]的矩阵,值未初始化,可能很大或很小
d= torch.ones(3, 3) #定义维度为[3,3]的全1矩阵
#同numpy来转换数据
e_np = np.ones((3, 3)) #定义numpy