Tensor基本操作

Tensor(张量)

1、Tensor,又名张量,从工程角度来说,可简单地认为它就是一个数组,且支持高效的科学计算。它可以是一个数(标量)、一维数组(向量)、二维数组(矩阵)或更高维的数组(高阶数组),torch里的Tensor支持GPU加速。

基本操作

1、从接口的角度讲,对tensor的操作可分为两类:
    (1)torch.function,如torch.save等
    (2)tensor.function,如tensor.view等
2、从存储的角度讲,对tensor的操作又可分为两类:
    (1)不会修改自身的数据,如a.add(b),加法的结果会返回一个新的tensor
    (2)会修改自身的数据,如a.add_(b),加法的结果仍存储在a中,a被修改了
函数名以_结尾的都是inplace方式,即会修改调用者自己的数据,在实际应用中需要加以区分。
 
  1. #_Author_:Monkey  
  2. #!/usr/bin/env python  
  3. #-*- coding:utf-8 -*-  
  4. import torch as t  
  5. # from __future__ import print_function  
  6.   
  7. a = t.Tensor(2,3)       #指定Tensor的形状,a的数值取决于内存空间的状态  
  8. print(a)  
  9. '''''tensor([[2.1469e+33, 5.9555e-43, 2.1479e+33], 
  10.         [5.9555e-43, 6.3273e+30, 5.9555e-43]])'''  
  11. b = t.Tensor([ [1,2,3],[4,5,6] ])       #用list的数据创建Tensor  
  12. print(b)  
  13. '''''tensor([[1., 2., 3.], 
  14.         [4., 5., 6.]])'''  
  15. c = b.tolist()      #Tensor转list  
  16. print(c)  
  17. '''''[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'''  
  18. #torch.size()返回torch.Size的子类,但其使用方式与tuple稍有区别  
  19. b_size = b.size()  
  20. print(b_size)  
  21. '''''torch.Size([2, 3])'''  
  22. d = b.numel()  
  23. print(d)  
  24. '''''6'''  
  25. #创建一个和b形状一样的tensor  
  26. e = t.Tensor(b_size)  
  27. f = t.Tensor((2,3))  
  28. print(e)  
  29. print(f)  
  30. '''''tensor([[2.6492e+21, 4.5908e-41, 0.0000e+00], 
  31.         [0.0000e+00, 1.4013e-45, 2.9775e-41]]) 
  32. tensor([2., 3.])'''  
  33. print(e.shape)  
  34. '''''torch.Size([2, 3])'''  
  35. print(t.ones(2,3))  
  36. '''''tensor([[1., 1., 1.], 
  37.         [1., 1., 1.]])'''  
  38. print(t.zeros(2,3))  
  39. '''''tensor([[0., 0., 0.], 
  40.         [0., 0., 0.]])'''  
  41. print(t.arange(1,6,2))  
  42. '''''tensor([1, 3, 5])'''  
  43. print(t.linspace(1,10,3))  
  44. '''''tensor([ 1.0000,  5.5000, 10.0000])'''  
  45. print(t.randn(2,3))  
  46. '''''tensor([[-0.3437, -0.3981, -0.3250], 
  47.         [ 2.6717, -0.7511, -0.5858]])'''  
  48. print(t.randperm(5))        #长度为5的随机排序  
  49. '''''tensor([4, 0, 3, 2, 1])'''  
  50. print(t.eye(2,3))           #对角线为1,不要求行列数一致  
  51. '''''tensor([[1., 0., 0.], 
  52.         [0., 1., 0.]])'''  

Monkey
原文地址:https://www.cnblogs.com/monkeyT/p/9768932.html