2、tensor数据的运算、numpy与Tensor互转、Tensor转cuda

原位操作(in-place),带“_”尾巴的都是原位操作,如x.add_(y) ,x被改变。

1、加法

import torch as t
x=t.Tensor([[10,11],[20,21]]) #Tensor得到的是浮点型
#x=t.tensor([[10,11],[20,21]],dtype=float) #必须指定为浮点型,否则与元素同类型
y=t.rand_like(x) #若x不是浮点型,报错
y
#加法
x+y #方式一
t.add(x,y) #方式二
x.add(y) #方式三
z=t.empty(2,2) t.add(x,y,out=z) #方式四,先分配z的空间再赋值 z

numpy与Tensor互转,共享内存,其一改变,都变。

import torch as t
a=t.ones(2) #默认浮点型
b=a.numpy() #Tensor→numpy
b
a.add_(1) #a、b的元素都变为2.
b
import numpy as nu
a=nu.ones(2) #默认浮点型
b=t.from_numpy(a) #numpy→Tensor
b

Tensor转cuda(GPU运算)

import torch as t
x=t.Tensor([[10,11],[20,21]]) #Tensor得到的是浮点型
y=t.Tensor([[10,11],[20,21]]) #Tensor得到的是浮点型
if t.cuda.is_available(): #gpu上运算,如果不支持,代码块不执行
    x=x.cuda() #转cuda
    y=y.cuda()
    z=x+y
    print(z) #还在GPU里
    print(z.to("cpu")) #转到cpu展示

原文地址:https://www.cnblogs.com/xixixing/p/12626267.html