脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Pytorch to(device)用法

Pytorch to(device)用法

2020-05-04 11:57shaopeng568 Python

今天小编就为大家分享一篇Pytorch to(device)用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

?
1
2
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)

这两行代码放在读取数据之前。

?
1
mytensor = my_tensor.to(device)

这行代码的意思是将所有最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行。

这句话需要写的次数等于需要保存GPU上的tensor变量的个数;一般情况下这些tensor变量都是最开始读数据时的tensor变量,后面衍生的变量自然也都在GPU上

如果是多个GPU

在代码中的使用方法为:

?
1
2
3
4
5
6
7
8
9
10
11
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
model = Model()
 
if torch.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上运行

?
1
2
3
if torch.cuda.is_available():
 h = g.cuda()
 print(h)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 – 卷积核的步长,可以是单个数字或一个元组 (sh x sw)。默认为1 - padding – 输入上隐含零填充。可以是单个数字或元组。 默认值:0 - groups – 将输入分成组,in_channels应该被组数除尽
 
 
>>> # With square kernels and equal stride
>>> 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)直接终端中设定

?
1
CUDA_VISIBLE_DEVICES=1

(2)python代码中设定:

?
1
2
3
import os
 
os.environ['CUDA_VISIBLE_DEVICE']='1'

(3)使用函数set_device

?
1
2
3
4
5
import torch
 
torch.cuda.set_device(id)
 
Pytoch中的in-place

in-place operation 在 pytorch中是指改变一个tensor的值的时候,不经过复制操作,而是在运来的内存上改变它的值。可以把它称为原地操作符。

在pytorch中经常加后缀 “_” 来代表原地in-place operation, 比如 .add_() 或者.scatter()

python 中里面的 += *= 也是in-place operation。

下面是正常的加操作,执行结束加操作之后x的值没有发生变化:

?
1
2
3
4
5
6
import torch
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])

下面是原地操作,执行之后改变了原来变量的值:

?
1
2
3
4
5
6
import torch
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])

以上这篇Pytorch to(device)用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/shaopeng568/article/details/95205345

延伸 · 阅读

精彩推荐