Pytorch to(device)用法
如下所示:
device=torch.device("cuda:0"iftorch.cuda.is_available()else"cpu") model.to(device)
这两行代码放在读取数据之前。
mytensor=my_tensor.to(device)
这行代码的意思是将所有最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行。
这句话需要写的次数等于需要保存GPU上的tensor变量的个数;一般情况下这些tensor变量都是最开始读数据时的tensor变量,后面衍生的变量自然也都在GPU上
如果是多个GPU
在代码中的使用方法为:
device=torch.device("cuda:0"iftorch.cuda.is_available()else"cpu") model=Model() iftorch.cuda.device_count()>1: model=nn.DataParallel(model,device_ids=[0,1,2]) model.to(device)
Tensor总结
(1)Tensor和Numpy都是矩阵,区别是前者可以在GPU上运行,后者只能在CPU上;
(2)Tensor和Numpy互相转化很方便,类型也比较兼容
(3)Tensor可以直接通过print显示数据类型,而Numpy不可以
把Tensor放到GPU上运行
iftorch.cuda.is_available(): h=g.cuda() print(h)
torch.nn.functional Convolution函数 torch.nn.functional.vonv1d(input,weight,bias=None,stride=1,padding=0,dilation=1,groups=1) torch.nn.functional.conv2d(input,weight,bias=None,stride=1,padding=0,dilation=1,group=1) parameter: input--输入张量(minibatch*in_channels*iH*iW)-weights-–过滤器张量(out_channels,in_channels/groups,kH,kW)-bias–可选偏置张量(out_channels)-stride–卷积核的步长,可以是单个数字或一个元组(shxsw)。默认为1-padding–输入上隐含零填充。可以是单个数字或元组。默认值:0-groups–将输入分成组,in_channels应该被组数除尽 >>>#Withsquarekernelsandequalstride >>>filters=autograd.Variable(torch.randn(8,4,3,3)) >>>inputs=autograd.Variable(torch.randn(1,4,5,5)) >>>F.conv2d(inputs,filters,padding=1)
Pytorch中使用指定的GPU
(1)直接终端中设定
CUDA_VISIBLE_DEVICES=1
(2)python代码中设定:
importos os.environ['CUDA_VISIBLE_DEVICE']='1'
(3)使用函数set_device
importtorch torch.cuda.set_device(id) Pytoch中的in-place
in-placeoperation在pytorch中是指改变一个tensor的值的时候,不经过复制操作,而是在运来的内存上改变它的值。可以把它称为原地操作符。
在pytorch中经常加后缀“_”来代表原地in-placeoperation,比如.add_()或者.scatter()
python中里面的+=*=也是in-placeoperation。
下面是正常的加操作,执行结束加操作之后x的值没有发生变化:
importtorch x=torch.rand(2)#tensor([0.8284,0.5539]) print(x) y=torch.rand(2) print(x+y)#tensor([1.0250,0.7891]) print(x)#tensor([0.8284,0.5539])
下面是原地操作,执行之后改变了原来变量的值:
importtorch x=torch.rand(2)#tensor([0.8284,0.5539]) print(x) y=torch.rand(2) x.add_(y) print(x)#tensor([1.1610,1.3789])
以上这篇Pytorchto(device)用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。