PyTorch | (3)Tensor及其基本操作

举报
DrugAI 发表于 2021/07/15 04:10:40 2021/07/15
【摘要】 PyTorch | (1)初识PyTorch PyTorch | (2)PyTorch 入门-张量 PyTorch | (3)Tensor及其基本操作 Tensor attributes: 在tensor attributes中有三个类,分别为torch.dtype, torch.device, 和 torch.layout 其中, torch.dtype 是展示...

PyTorch | (1)初识PyTorch

PyTorch | (2)PyTorch 入门-张量

PyTorch | (3)Tensor及其基本操作


Tensor attributes:

在tensor attributes中有三个类,分别为torch.dtype, torch.device, 和 torch.layout

其中, torch.dtype 是展示 torch.Tensor 数据类型的类,pytorch 有八个不同的数据类型,下表是完整的 dtype 列表.

 


Torch.device 是表现 torch.Tensor被分配的设备类型的类,其中分为’cpu’ 和 ‘cuda’两种,如果设备序号没有显示则表示此 tensor 被分配到当前设备, 比如: 'cuda' 等同于 'cuda': X , X 为torch.cuda.current _device() 返回值

我们可以通过 tensor.device 来获取其属性,同时可以利用字符或字符+序号的方式来分配设备

通过字符串

torch.device('cuda:0')

 

运行结果:

device(type='cuda', index=0)

 

torch.device('cpu')
 

运行结果:
device(type='cpu')
 

torch.device('cuda') # 当前设备
 

运行结果:
device(type='cuda')

通过字符串和设备序号

torch.device('cuda', 0)
 

运行结果:

device(type='cuda', index=0)
 

torch.device('cpu', 0)
 

运行结果:
device(type='cpu', index=0)


此外,cpu 和 cuda 设备的转换使用 'to' 来实现:


      device_cpu = torch.device("cuda")  #声明cuda设备
      device_cuda = torch.device('cuda')  #设备cpu设备
      data = torch.Tensor([1])
      data.to(device_cpu)  #将数据转为cpu格式
      data.to(device_cuda)   #将数据转为cuda格式
  
 

torch.layout 是表现 torch.Tensor 内存分布的类,目前只支持 torch.strided


创建tensor

  • 直接创建

torch.tensor(data, dtype=None, device=None,requires_grad=False)

data - 可以是list, tuple, numpy array, scalar或其他类型

dtype - 可以返回想要的tensor类型

device - 可以指定返回的设备

requires_grad - 可以指定是否进行记录图的操作,默认为False

需要注意的是,torch.tensor 总是会复制 data, 如果你想避免复制,可以使 torch.Tensor. detach(),如果是从 numpy 中获得数据,那么你可以用 torch.from_numpy(), 注from_numpy() 是共享内存的

torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
 

运行结果:


      tensor([[ 0.1000,  1.2000],
       [ 2.2000,  3.1000],
       [ 4.9000,  5.2000]])
  
 

 

torch.tensor([0, 1])  # Type inference on data 
 

运行结果:

tensor([ 0,  1])
 

 


      torch.tensor([[0.11111, 0.222222, 0.3333333]],
       dtype=torch.float64,
       device=torch.device('cuda:0'))  # creates a torch.cuda.DoubleTensor
  
 

运行结果:

tensor([[ 0.1111,  0.2222,  0.3333]], dtype=torch.float64, device='cuda:0')
 
torch.tensor(3.14159)  # Create a scalar (zero-dimensional tensor)
 

运行结果:

tensor(3.1416)
 
torch.tensor([])  # Create an empty tensor (of size (0,))
 

运行结果:

tensor([])
 

 

  • 从numpy中获得数据

torch.from_numpy(ndarry)

注:生成返回的tensor会和ndarry共享数据,任何对tensor的操作都会影响到ndarry,
反之亦然


      >>> a = numpy.array([1, 2, 3])
      >>> t = torch.from_numpy(a)
      >>> t
      tensor([ 1,  2,  3])
      >>> t[0] = -1
      >>> a
      array([-1,  2,  3])
  
 

 

  • 创建特定的tensor

根据数值要求:


      torch.zeros(*sizes, out=None, ..)# 返回大小为sizes的零矩阵 
      torch.zeros_like(input, ..) # 返回与input相同size的零矩阵
      torch.ones(*sizes, out=None, ..) #f返回大小为sizes的单位矩阵
      torch.ones_like(input, ..) #返回与input相同size的单位矩阵
      torch.full(size, fill_value,) #返回大小为sizes,单位值为fill_value的矩阵
      torch.full_like(input, fill_value,) 返回与input相同size,单位值为fill_value的矩阵
      torch.arange(start=0, end, step=1,) #返回从start到end, 单位步长为step的1-d tensor.
      torch.linspace(start, end, steps=100,)  #返回从start到end, 间隔中的插值数目为steps的1-d tensor
      torch.logspace(start, end, steps=100,) #返回1-d tensor ,从10^start到10^end的steps个对数间隔
  
 

根据矩阵要求:


      torch.eye(n, m=None, out=None,) #返回2-D 的单位对角矩阵
      torch.empty(*sizes, out=None,) #返回被未初始化的数值填充,大小为sizes的tensor
      torch.empty_like(input,) # 返回与input相同size,并被未初始化的数值填充的tensor
  
 

 

  • 随机采用生成:


      torch.normal(mean, std, out=None)
      torch.rand(*size, out=None, dtype=None,) #返回[0,1]之间均匀分布的随机数值
      torch.rand_like(input, dtype=None,) #返回与input相同size的tensor, 填充均匀分布的随机数值
      torch.randint(low=0, high, size,) #返回均匀分布的[low,high]之间的整数随机值
      torch.randint_like(input, low=0, high, dtype=None,) #
      torch.randn(*sizes, out=None,) #返回大小为size,由均值为0,方差为1的正态分布的随机数值
      torch.randn_like(input, dtype=None,)
      torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的数列的随机排列
  
 

 


张量的操作

  索引: 支持numpy的常用索引和切片操作

  加法:和numpy类似的广播原则


      #索引操作
      y = torch.rand(5,3)
      y[1:, 2]  #切片和索引
      y[y>0.5] #花式索引
      #加法操作(和numpy一样的广播原则)
      result = x+y
      reslut = torch.add(x, y)
      y.add_(x)  #直接对y的值进行修改, 
      (以_结尾的方法会直接在原地修改变量, 如x.copy_(y), x.t_()会修改x.)
      result = torch.empty(5,3)
      torch.add(x, y, out=result)  #这里的result必须先定义
      #对于一个元素的张量,可以直接通过x.item()拿到元素值
      x = torch.ones(3,4)
      y = torch.sum(x)
      print(y.item(0)) #得到整数12.0
  
 

 

cuda Tensor: pytorch 支持Gpu操作,可以在Gpu上创建tensor,通过to()方法可以在cpu和Gpu上间转换tensor


      if torch.cuda.is_available():
       device = torch.device("cuda")
       y = torch.ones_like(x, device=device)   #直接在Gpu上创建tensor
       x = x.to(device)  #从cpu上转移到gpu
       z = x+y
       print(z.to("cpu", torch.double))  #转回到cpu,并改变数据类型
  
 

 

  • 点对点操作

三角函数:


      torch.abs(input, out=None)
      torch.acos(input, out=None)
      torch.asin(input, out=None)
      torch.atan(input, out=None)
      torch.atan2(input, inpu2, out=None)
      torch.cos(input, out=None)
      torch.cosh(input, out=None)
      torch.sin(input, out=None)
      torch.sinh(input, out=None)
      torch.tan(input, out=None)
      torch.tanh(input, out=None)
  
 

 

基本运算,加减乘除


      Torch.add(input, value, out=None)
       .add(input, value=1, other, out=None)
       .addcdiv(tensor, value=1, tensor1, tensor2, out=None)
       .addcmul(tensor, value=1, tensor1, tensor2, out=None)
      torch.div(input, value, out=None)
       .div(input, other, out=None)
      torch.mul(input, value, out=None)
       .mul(input, other, out=None)
  
 

 

对数运算:


      torch.log(input, out=None)  # y_i=log_e(x_i)
      torch.log1p(input, out=None)  #y_i=log_e(x_i+1)
      torch.log2(input, out=None)   #y_i=log_2(x_i)
      torch.log10(input,out=None)  #y_i=log_10(x_i)
  
 

 

幂函数:

torch.pow(input, exponent, out=None)  # y_i=input^(exponent)
 

 

指数运算


      torch.exp(tensor, out=None) #y_i=e^(x_i)
      torch.expm1(tensor, out=None)   #y_i=e^(x_i) -1
  
 

 

截断函数


      torch.ceil(input, out=None)   #返回向正方向取得最小整数
      torch.floor(input, out=None)  #返回向负方向取得最大整数
      torch.round(input, out=None)  #返回相邻最近的整数,四舍五入
      torch.trunc(input, out=None)  #返回整数部分数值
      torch.frac(tensor, out=None)  #返回小数部分数值
      torch.fmod(input, divisor, out=None)  #返回input/divisor的余数
      torch.remainder(input, divisor, out=None)  #同上
  
 

 

其他运算


      torch.erf(tensor, out=None)
      torch.erfinv(tensor, out=None)
      torch.sigmoid(input, out=None)
      torch.clamp(input, min, max out=None)  #返回 input<min,则返回min, input>max,则返回max,其余返回input
      torch.neg(input, out=None) #out_i=-1*(input)
      torch.reciprocal(input, out=None)  # out_i= 1/input_i
      torch.sqrt(input, out=None)  # out_i=sqrt(input_i)
      torch.rsqrt(input, out=None) #out_i=1/(sqrt(input_i))
      torch.sign(input, out=None)  #out_i=sin(input_i) 大于0为1,小于0为-1
      torch.lerp(start, end, weight, out=None)
  
 

 

  • 降维操作


      torch.argmax(input, dim=None, keepdim=False) #返回最大值排序的索引值
      torch.argmin(input, dim=None, keepdim=False)  #返回最小值排序的索引值
      torch.cumprod(input, dim, out=None)  #y_i=x_1 * x_2 * x_3 *…* x_i
      torch.cumsum(input, dim, out=None)  #y_i=x_1 + x_2 + … + x_i
      torch.dist(input, out, p=2) #返回input和out的p式距离
      torch.mean() #返回平均值
      torch.sum() #返回总和
      torch.median(input) #返回中间值
      torch.mode(input) #返回众数值
      torch.unique(input, sorted=False) #返回1-D的唯一的tensor,每个数值返回一次.
      >>> output = torch.unique(torch.tensor([1, 3, 2, 3], dtype=torch.long))
      >>> output
      tensor([ 2,  3,  1])
      torch.std(  #返回标准差)
      torch.var() #返回方差
      torch.norm(input, p=2) #返回p-norm的范式
      torch.prod(input, dim, keepdim=False) #返回指定维度每一行的乘积
  
 

 

  • 对比操作:


      torch.eq(input, other, out=None)  #按成员进行等式操作,相同返回1
      torch.equal(tensor1, tensor2) #如果tensor1和tensor2有相同的size和elements,则为true
      >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
      tensor([[ 1,  0],
       [ 0,  1]], dtype=torch.uint8)
      >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
      tensor([[ 1,  0],
       [ 0,  1]], dtype=torch.uint8)
      torch.ge(input, other, out=None)   # input>= other
      torch.gt(input, other, out=None)   # input>other
      torch.le(input, other, out=None) # input=<other
      torch.lt(input, other, out=None) # input<other
      torch.ne(input, other, out=None)  # input != other 不等于
      torch.max() # 返回最大值
      torch.min() # 返回最小值
      torch.isnan(tensor) #判断是否为’nan’
      torch.sort(input, dim=None, descending=False, out=None) #对目标input进行排序
      torch.topk(input, k, dim=None, largest=True, sorted=True, out=None)  #沿着指定维度返回最大k个数值及其索引值
      torch.kthvalue(input, k, dim=None, deepdim=False, out=None) #沿着指定维度返回最小k个数值及其索引值
  
 

 

  • 频谱操作


      torch.fft(input, signal_ndim, normalized=False)
      torch.ifft(input, signal_ndim, normalized=False)
      torch.rfft(input, signal_ndim, normalized=False, onesided=True)
      torch.irfft(input, signal_ndim, normalized=False, onesided=True)
      torch.stft(signa, frame_length, hop,)
  
 

 

  • 其他操作:


      torch.cross(input, other, dim=-1, out=None)  #叉乘(外积)
      torch.dot(tensor1, tensor2)  #返回tensor1和tensor2的点乘
      torch.mm(mat1, mat2, out=None) #返回矩阵mat1和mat2的乘积
      torch.eig(a, eigenvectors=False, out=None) #返回矩阵a的特征值/特征向量 
      torch.det(A)  #返回矩阵A的行列式
      torch.trace(input) #返回2-d 矩阵的迹(对对角元素求和)
      torch.diag(input, diagonal=0, out=None) #
      torch.histc(input, bins=100, min=0, max=0, out=None) #计算input的直方图
      torch.tril(input, diagonal=0, out=None)  #返回矩阵的下三角矩阵,其他为0
      torch.triu(input, diagonal=0, out=None) #返回矩阵的上三角矩阵,其他为0
  
 

 


参考资料

1. https://zhuanlan.zhihu.com/p/36233589

2. https://www.cnblogs.com/silence-cho/p/11404817.html

 

文章来源: drugai.blog.csdn.net,作者:DrugAI,版权归原作者所有,如需转载,请联系作者。

原文链接:drugai.blog.csdn.net/article/details/104381077

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。