【转载】Pytorch to(device)用法

device = torch.device("cuda:0" if torch.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" 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上运行

if torch.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 – 卷积核的步长,可以是单个数字或一个元组 (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])

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值