Pytorch to(device)用法

yipeiwu_com6年前Python基础

如下所示:

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)直接终端中设定

CUDA_VISIBLE_DEVICES=1

(2)python代码中设定:

import os

os.environ['CUDA_VISIBLE_DEVICE']='1'

(3)使用函数set_device

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的值没有发生变化:

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])

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

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)用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

用Python的Django框架来制作一个RSS阅读器

用Python的Django框架来制作一个RSS阅读器

Django带来了一个高级的聚合生成框架,它使得创建RSS和Atom feeds变得非常容易。 什么是RSS? 什么是Atom? RSS和Atom都是基于XML的格式,你可以用它来提供有...

Python实现的矩阵类实例

本文实例讲述了Python实现的矩阵类。分享给大家供大家参考,具体如下: 科学计算离不开矩阵的运算。当然,python已经有非常好的现成的库:numpy(numpy的简单安装与使用可参考...

Python中循环引用(import)失败的解决方法

前言 最近在开发智能家居项目hestia-rpi项目中,由于代码结构层级划分不合理,导致了循环引用(import)module失败的问题,错误如下: Traceback (most r...

python实战串口助手_解决8串口多个发送的问题

今晚终于解决了串口发送的问题,更改代码如下: def write(self, data): if self.alive: if self.serSer.isOpe...

python读出当前时间精度到秒的代码

导入time这个包就可以通过它获取是时间 # -*- coding: UTF-8 -*- import time print(time.time()) # 输出:1562...