翼度科技»论坛 编程开发 python 查看内容

python中的torch常用tensor处理函数示例详解

9

主题

9

帖子

27

积分

新手上路

Rank: 1

积分
27
note


一、tensor的创建


    1. torch.tensor
    复制代码
    会复制data,不想复制可以使用
    1. torch.Tensor.detach()
    复制代码

  • 如果是获得numpy数组数据,可以使用
    1. torch.from_numpy()
    复制代码
    ,共享内存
  1. # 1. tensor
  2. torch.tensor(data, dtype=None, device=None,requires_grad=False)
  3. data - 可以是list, tuple, numpy array, scalar或其他类型
  4. dtype - 可以返回想要的tensor类型
  5. device - 可以指定返回的设备
  6. requires_grad - 可以指定是否进行记录图的操作,默认为False
  7. # example 1
  8. torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
  9. tensor([[ 0.1000,  1.2000],
  10. [ 2.2000,  3.1000],
  11. [ 4.9000,  5.2000]])
  12. # example 2
  13. torch.tensor([0, 1]) # Type inference on data
  14. tensor([ 0, 1])
  15. # example 3
  16. torch.tensor([[0.11111, 0.222222, 0.3333333]],
  17. dtype=torch.float64,
  18. device=torch.device(‘cuda:0')) # creates a torch.cuda.DoubleTensor
  19. tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device=‘cuda:0')
  20. torch.tensor(3.14159) # Create a scalar (zero-dimensional tensor)
  21. tensor(3.1416)
  22. torch.tensor([]) # Create an empty tensor (of size (0,))
  23. tensor([])
  24. # 2. 从numpy中获得数据
  25. torch.from_numpy(ndarry)
  26. # 3. 创建特定数值的tensor
  27. torch.zeros(*sizes, out=None, …)# 返回大小为sizes的零矩阵
  28. 1
  29. torch.zeros_like(input, …) # 返回与input相同size的零矩阵
  30. torch.ones(*sizes, out=None, …) #f返回大小为sizes的单位矩阵
  31. torch.ones_like(input, …) #返回与input相同size的单位矩阵
  32. torch.full(size, fill_value, …) #返回大小为sizes,单位值为fill_value的矩阵
  33. torch.full_like(input, fill_value, …) 返回与input相同size,单位值为fill_value的矩阵
  34. torch.arange(start=0, end, step=1, …) #返回从start到end, 单位步长为step的1-d tensor.
  35. torch.linspace(start, end, steps=100, …) #返回从start到end, 间隔中的插值数目为steps的1-d tensor
  36. torch.logspace(start, end, steps=100, …) #返回1-d tensor ,从10start到10end的steps个对数间隔
  37. # 4. 随机生成
  38. torch.normal(mean, std, out=None)
  39. torch.rand(*size, out=None, dtype=None, …) #返回[0,1]之间均匀分布的随机数值
  40. torch.rand_like(input, dtype=None, …) #返回与input相同size的tensor, 填充均匀分布的随机数值
  41. torch.randint(low=0, high, size,…) #返回均匀分布的[low,high]之间的整数随机值
  42. torch.randint_like(input, low=0, high, dtype=None, …) #
  43. torch.randn(*sizes, out=None, …) #返回大小为size,由均值为0,方差为1的正态分布的随机数值
  44. torch.randn_like(input, dtype=None, …)
  45. torch.randperm(n, out=None, dtype=torch.int64) # 返回0到n-1的数列的随机排列
复制代码
二、tensor的加减乘除


    1. torch.mm
    复制代码
    : 用于两个矩阵(不包括向量)的乘法。如维度为(l,m)和(m,n)相乘
    1. torch.bmm
    复制代码
    : 用于带batch的三维向量的乘法。如维度为(b,l,m)和(b,m,n)相乘
    1. torch.mul
    复制代码
    : 用于两个同维度矩阵的逐像素点相乘(点乘)。如维度为(l,m)和(l,m)相乘
    1. torch.mv
    复制代码
    : 用于矩阵和向量之间的乘法(矩阵在前,向量在后)。如维度为(l,m)和(m)相乘,结果的维度为(l)。
    1. torch.matmul
    复制代码
    : 用于两个张量(后两维满足矩阵乘法的维度)相乘或者是矩阵与向量间的乘法,因为其具有广播机制(broadcasting,自动补充维度)。如维度为(b,l,m)和(b,m,n);(l,m)和(b,m,n);(b,c,l,m)和(b,c,m,n);(l,m)和(m)相乘等。【其作用包含torch.mm、torch.bmm和torch.mv】
    1. @
    复制代码
    运算符 : 其作用类似于
    1. torch.matmul
    复制代码
    1. *
    复制代码
    运算符 : 其作用类似于
    1. torch.mul
    复制代码
    1. einsum
    复制代码
    (Einstein summation convention,即爱因斯坦求和约定)的用法:
  • c i k = ∑ j a i j b j k c_{i k}=\sum_j a_{i j} b_{j k} cik​=∑j​aij​bjk​ 的写法如下:
  1. c = np.dot(a, b)                 # 常规
  2. c = np.einsum('ij,jk->ik', a, b) # einsum
复制代码

  • 再比如 c k l = ∑ i ∑ j a i j k b i j l c_{\mathrm{kl}}=\sum_{\mathrm{i}} \sum_{\mathrm{j}} \mathrm{a}_{\mathrm{ijk}} \mathrm{b}_{\mathrm{ijl}} ckl​=∑i​∑j​aijk​bijl​ :
    1. c = np.einsum('ijk,jkl->kl', a, b)
    复制代码
  1. # 对数运算
  2. torch.log(input, out=None)  # y_i=log_e(x_i)
  3. torch.log1p(input, out=None)  #y_i=log_e(x_i+1)
  4. torch.log2(input, out=None)   #y_i=log_2(x_i)
  5. torch.log10(input,out=None)  #y_i=log_10(x_i)
  6. # 幂函数
  7. torch.pow(input, exponent, out=None)  # y_i=input^(exponent)
  8. # 指数运算
  9. torch.exp(tensor, out=None)    #y_i=e^(x_i)
  10. torch.expm1(tensor, out=None)   #y_i=e^(x_i) -1
复制代码
三、torch.argmax()函数


  • (1)
    1. torch.argmax(input, dim=None, keepdim=False)
    复制代码
    返回指定维度最大值的序号;
  • (2)
    1. dim
    复制代码
    给定的定义是:the demention to reduce.也就是把
    1. dim
    复制代码
    这个维度的,变成这个维度的最大值的index。
  1. import torch
  2. a=torch.tensor([
  3.               [
  4.                   [1, 5, 5, 2],
  5.                   [9, -6, 2, 8],
  6.                   [-3, 7, -9, 1]
  7.               ],
  8.               [
  9.                   [-1, 7, -5, 2],
  10.                   [9, 6, 2, 8],
  11.                   [3, 7, 9, 1]
  12.               ]])
  13. b=torch.argmax(a,dim=1)
  14. print(a)
  15. print(a.shape)
  16. print(b)
复制代码
(1)这个例子,
  1. tensor(2, 3, 4)
复制代码
,因为是
  1. dim=1
复制代码
,即将第二维度去掉,变成
  1. tensor(2, 4)
复制代码
,将每一个3x4数组,变成1x4数组。
  1. [1, 5, 5, 2],
  2. [9, -6, 2, 8],
  3. [-3, 7, -9, 1]
复制代码
如上所示的3×4矩阵,取每一列的最大值对应的下标,a[0]中第一列的最大值的行标为1, 第二列的最大值的行标为2,第三列的最大值行标为0,第4列的最大值行标为1,所以最后输出[1, 2, 0, 1],取每一列的最大值,结果为:
  1. tensor([[[ 1,  5,  5,  2],         [ 9, -6,  2,  8],         [-3,  7, -9,  1]],        [[-1,  7, -5,  2],         [ 9,  6,  2,  8],         [ 3,  7,  9,  1]]])torch.Size([2, 3, 4])tensor([[1, 2, 0, 1],        [1, 0, 2, 1]])
复制代码
(1)如果改成
  1. dim=2
复制代码
,即将第三维去掉,即取每一行的最大值对应的下标,结果为
  1. tensor(2, 3)
复制代码
  1. import torch
  2. a=torch.tensor([
  3.               [
  4.                   [1, 5, 5, 2],
  5.                   [9, -6, 2, 8],
  6.                   [-3, 7, -9, 1]
  7.               ],
  8.               [
  9.                   [-1, 7, -5, 2],
  10.                   [9, 6, 2, 8],
  11.                   [3, 7, 9, 1]
  12.               ]])
  13. b=torch.argmax(a,dim=2)
  14. print(b)
  15. print(a.shape)
  16. """
  17. tensor([[2, 0, 1],
  18.         [1, 0, 2]])
  19. torch.Size([2, 3, 4])
  20. """
复制代码
四、gathter函数
  1. torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor
复制代码
  1. torch.gather()
复制代码
函数:利用index来索引input特定位置的数值
  1. dim = 1
复制代码
表示横向。
对于三维张量,其output是:
  1. out[i][j][k] = input[index[i][j][k]][j][k]  # if dim == 0
  2. out[i][j][k] = input[i][index[i][j][k]][k]  # if dim == 1
  3. out[i][j][k] = input[i][j][index[i][j][k]]  # if dim == 2
复制代码
小栗子1
比如现在有4个句子(句子长度不一),现在的序列标注问题需要给每个单词都标上一个标签,标签如下:
  1. input = [
  2.     [2, 3, 4, 5],
  3.     [1, 4, 3],
  4.     [4, 2, 2, 5, 7],
  5.     [1]
  6. ]
复制代码
长度分别为4,3,5,1,其中第一个句子的标签为2,3,4,5。在NLP中,一般需要对不同长度的句子进行padding到相同长度(用0进行padding),所以padding后的结果:
  1. input = [    [2, 3, 4, 5, 0, 0],    [1, 4, 3, 0, 0, 0],    [4, 2, 2, 5, 7, 0],    [1, 0, 0, 0, 0, 0]]
复制代码
  1. import torchinput = [    [2, 3, 4, 5, 0, 0],    [1, 4, 3, 0, 0, 0],    [4, 2, 2, 5, 7, 0],    [1, 0, 0, 0, 0, 0]]input = torch.tensor(input)length = torch.LongTensor([[4], [3], [5], [1]])# index之所以减1,是因为序列维度从0开始计算的out = torch.gather(input, 1, length - 1)print(out)
复制代码
out的结果为如下,比如length的第一行是
  1. [4]
复制代码
,即找出input的第一行的第4个元素为5(这里
  1. length-1
复制代码
后就是下标从1开始计算了)。
  1. tensor([[5],
  2.         [3],
  3.         [7],
  4.         [1]])
复制代码
小栗子2:如果每行需要索引多个元素:
  1. >>> t = torch.Tensor([[1,2],[3,4]])
  2. 1  2
  3. 3  4
  4. >>> torch.gather(t,1,torch.LongTensor([[0,0],[1,0]])
  5. 1  1
  6. 4  3
  7. [torch.FloatTensor of size 2x2]
复制代码
五、针对某一维度的操作


  • mean
  • softmax
  • BN
  • LN

六、改变维度、拼接、堆叠等操作
  1. import torch
  2. x = torch.arange(12)
  3. # tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
  4. x1 = x.reshape(3, 4)  # 改变维度
  5. x2 = x.reshape(-1, 4)
  6. x3 = torch.zeros((2, 3, 4))
  7. x4 = torch.ones((2, 3, 4)) # 所有元素都为1
  8. # 正态分布
  9. x5 = torch.randn(3, 4)
  10. x6 = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
  11. x = torch.tensor([1.0, 2, 4, 8])
  12. y = torch.tensor([2, 2, 2, 2])
  13. # 都是按元素操作,注意**是求幂运算
  14. print(x + y, x - y, x * y, x / y, x ** y)
  15. X = torch.arange(12, dtype=torch.float32).reshape((3,4))
  16. Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
  17. # 每行(上下)拼接, dim=1为左右拼接
  18. print(torch.cat((X, Y), dim=0), "\n", torch.cat((X, Y), dim=1))
  19. # 判断每个位置是否相同
  20. X == Y
  21. # 广播机制, 两个矩阵维度不同(数学上不能按元素相加),通过广播(a赋值列,b赋值行)后相加
  22. a = torch.arange(3).reshape((3, 1))
  23. b = torch.arange(2).reshape((1, 2))
  24. print(a + b)
  25. # 切片和索引, 和numpy差不多
  26. X[-1], X[1:3]
  27. X[1, 2]
  28. X[0:2, :] = 12  # 赋值
复制代码
  1. view
复制代码
改变维度,可以在其中一个维度传参为-1,会自动计算。
  1. import torch
  2. a = torch.arange(1, 7)
  3. print(a)
  4. b = a.view(2, 3)
  5. print(b)
  6. c = a.view(3, -1)
  7. print(c)
复制代码
  1. flatten
复制代码
压平操作
  1. input1 = torch.tensor(range(2*3*4*5)).view(2, 3, 4, 5)
  2. # input1.shape
  3. torch.flatten(input1, start_dim = 1, end_dim=2).shape
  4. # torch.Size([2, 12, 5])
复制代码
  1. repeat_interleave
复制代码
是将张量中的元素沿某一维度复制n次
  1. import torch
  2. x = torch.tensor([[1, 2, 3],[4,5,6]])
  3. x1 = x.repeat_interleave(3,0)
  4. print("x1:\n", x1)
  5. x2 = x.repeat_interleave(3,1)
  6. print("x2:\n",x2)
  7. x1:
  8. tensor([[1, 2, 3],
  9.         [1, 2, 3],
  10.         [1, 2, 3],
  11.         [4, 5, 6],
  12.         [4, 5, 6],
  13.         [4, 5, 6]])
  14. x2:
  15. tensor([[1, 1, 1, 2, 2, 2, 3, 3, 3],
  16.         [4, 4, 4, 5, 5, 5, 6, 6, 6]])
  17. Process finished with exit code 0
复制代码
其他函数:
  1. torch.lerp(star, end, weight) : 返回结果是out= star t+ (end-start) * weight
  2. torch.rsqrt(input) : 返回平方根的倒数
  3. torch.mean(input) : 返回平均值
  4. torch.std(input) : 返回标准偏差
  5. torch.prod(input) : 返回所有元素的乘积
  6. torch.sum(input) : 返回所有元素的之和
  7. torch.var(input) : 返回所有元素的方差
  8. torch.tanh(input) :返回元素双正切的结果
  9. torch.equal(torch.Tensor(a), torch.Tensor(b)) :两个张量进行比较,如果相等返回true
  10. torch.max(input): 返回输入元素的最大值
  11. torch.min(input) : 返回输入元素的最小值
  12. element_size() :返回单个元素的字节
  13. torch.from_numpy(obj),利用一个numpy的array创建Tensor。注意,若obj原来是1列或者1行,无论obj是否为2维,所生成的Tensor都是一阶的,若需要2阶的Tensor,需要利用view()函数进行转换。
  14. torch.numel(obj),返回Tensor对象中的元素总数。
  15. torch.ones_like(input),返回一个全1的Tensor,其维度与input相一致
  16. torch.cat(seq, dim),在给定维度上对输入的张量序列进行连接操作
  17. torch.chunk(input, chunks, dim)在给定维度(轴)上将输入张量进行分块
  18. torch.squeeze(input),将input中维度数值为1的维度去除。可以指定某一维度。共享input的内存
  19. torch.unsqeeze(input, dim),在input目前的dim维度上增加一维
  20. torch.clamp(input, min, max),将input的值约束在min和max之间
  21. torch.trunc(input),将input的小数部分舍去
复制代码

Reference
[1] 透彻理解torch.tensor中对某一维度的操作们(mean,Softmax,batch norm, layer norm)
到此这篇关于python中的torch常用tensor处理函数的文章就介绍到这了,更多相关torch常用tensor处理函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/python/292004wqh.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具