iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >【Pytorch基础教程39】torch常用tensor处理函数
  • 905
分享到

【Pytorch基础教程39】torch常用tensor处理函数

pytorch深度学习张量运算原力计划 2023-09-02 15:09:20 905人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

note 文章目录 note一、tensor的创建二、tensor的加减乘除三、torch.argmax()函数四、gathter函数小栗子1小栗子2:如果每行需要索引多个元素: 四、针对

note

文章目录

一、tensor的创建

  • torch.tensor会复制data,不想复制可以使用torch.Tensor.detach()
  • 如果是获得numpy数组数据,可以使用torch.from_numpy(),共享内存
# 1. tensortorch.tensor(data, dtype=None, device=None,requires_grad=False)data - 可以是list, tuple, numpy array, Scalar或其他类型dtype - 可以返回想要的tensor类型device - 可以指定返回的设备requires_grad - 可以指定是否进行记录图的操作,默认为False# example 1torch.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]])# example 2torch.tensor([0, 1]) # Type inference on datatensor([ 0, 1])# example 3torch.tensor([[0.11111, 0.222222, 0.3333333]],dtype=torch.float64,device=torch.device(‘cuda:0)) # creates a torch.cuda.DoubleTensortensor([[ 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([])# 2. 从numpy中获得数据torch.from_numpy(ndarry)# 3. 创建特定数值的tensortorch.zeros(*sizes, out=None,)# 返回大小为sizes的零矩阵1torch.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 tensortorch.logspace(start, end, steps=100,) #返回1-d tensor ,从10start到10end的steps个对数间隔# 4. 随机生成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的数列的随机排列

二、tensor的加减乘除

  • torch.mm : 用于两个矩阵(不包括向量)的乘法。如维度为(l,m)和(m,n)相乘
  • torch.bmm : 用于带batch的三维向量的乘法。如维度为(b,l,m)和(b,m,n)相乘
  • torch.mul : 用于两个同维度矩阵的逐像素点相乘(点乘)。如维度为(l,m)和(l,m)相乘
  • torch.mv: 用于矩阵和向量之间的乘法(矩阵在前,向量在后)。如维度为(l,m)和(m)相乘,结果的维度为(l)。
  • 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】
  • @运算符 : 其作用类似于torch.matmul
  • *运算符 : 其作用类似于torch.mul
  • 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=jaijbjk 的写法如下:
c = np.dot(a, b)                 # 常规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=ijaijkbijlc = np.einsum('ijk,jkl->kl', a, b)
# 对数运算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.argmax()函数

(1)torch.argmax(input, dim=None, keepdim=False)返回指定维度最大值的序号;
(2)dim给定的定义是:the demention to reduce.也就是把dim这个维度的,变成这个维度的最大值的index。

import torcha=torch.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]              ]])b=torch.argmax(a,dim=1)print(a)print(a.shape)print(b)

(1)这个例子,tensor(2, 3, 4),因为是dim=1,即将第二维度去掉,变成tensor(2, 4),将每一个3x4数组,变成1x4数组。

[1, 5, 5, 2],[9, -6, 2, 8],[-3, 7, -9, 1]

如上所示的3×4矩阵,取每一列的最大值对应的下标,a[0]中第一列的最大值的行标为1, 第二列的最大值的行标为2,第三列的最大值行标为0,第4列的最大值行标为1,所以最后输出[1, 2, 0, 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)如果改成dim=2,即将第三维去掉,即取每一行的最大值对应的下标,结果为tensor(2, 3)

import torcha=torch.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]              ]])b=torch.argmax(a,dim=2)print(b)print(a.shape)"""tensor([[2, 0, 1],        [1, 0, 2]])torch.Size([2, 3, 4])"""

四、gathter函数

torch.gather(input, dim, index, *, sparse_grad=False, out=None) → Tensor

torch.gather()函数:利用index来索引input特定位置的数值
dim = 1表示横向。

对于三维张量,其output是:

out[i][j][k] = input[index[i][j][k]][j][k]  # if dim == 0out[i][j][k] = input[i][index[i][j][k]][k]  # if dim == 1out[i][j][k] = input[i][j][index[i][j][k]]  # if dim == 2

小栗子1

比如现在有4个句子(句子长度不一),现在的序列标注问题需要给每个单词都标上一个标签,标签如下:

input = [    [2, 3, 4, 5],    [1, 4, 3],    [4, 2, 2, 5, 7],    [1]]

长度分别为4,3,5,1,其中第一个句子的标签为2,3,4,5。在NLP中,一般需要对不同长度的句子进行padding到相同长度(用0进行padding),所以padding后的结果:

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]]
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的第一行是[4],即找出input的第一行的第4个元素为5(这里length-1后就是下标从1开始计算了)。

tensor([[5],        [3],        [7],        [1]])

小栗子2:如果每行需要索引多个元素:

>>> t = torch.Tensor([[1,2],[3,4]])1  23  4>>> torch.gather(t,1,torch.LongTensor([[0,0],[1,0]])1  14  3[torch.FloatTensor of size 2x2]

四、针对某一维度的操作

  • mean
  • softmax
  • BN
  • LN

五、改变维度、拼接、堆叠等操作

import torchx = torch.arange(12)# tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])x1 = x.reshape(3, 4)  # 改变维度x2 = x.reshape(-1, 4)x3 = torch.zeros((2, 3, 4))x4 = torch.ones((2, 3, 4)) # 所有元素都为1# 正态分布x5 = torch.randn(3, 4)x6 = torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])x = torch.tensor([1.0, 2, 4, 8])y = torch.tensor([2, 2, 2, 2])# 都是按元素操作,注意**是求幂运算print(x + y, x - y, x * y, x / y, x ** y)X = torch.arange(12, dtype=torch.float32).reshape((3,4))Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])# 每行(上下)拼接, dim=1为左右拼接print(torch.cat((X, Y), dim=0), "\n", torch.cat((X, Y), dim=1))# 判断每个位置是否相同X == Y# 广播机制, 两个矩阵维度不同(数学上不能按元素相加),通过广播(a赋值列,b赋值行)后相加a = torch.arange(3).reshape((3, 1))b = torch.arange(2).reshape((1, 2))print(a + b)# 切片和索引, 和numpy差不多X[-1], X[1:3]X[1, 2]X[0:2, :] = 12  # 赋值
  • view改变维度,可以在其中一个维度传参为-1,会自动计算。
import torcha = torch.arange(1, 7)print(a)b = a.view(2, 3)print(b)c = a.view(3, -1)print(c)
  • flatten压平操作
input1 = torch.tensor(range(2*3*4*5)).view(2, 3, 4, 5)# input1.shapetorch.flatten(input1, start_dim = 1, end_dim=2).shape# torch.Size([2, 12, 5])
  • repeat_interleave是将张量中的元素沿某一维度复制n次
import torchx = torch.tensor([[1, 2, 3],[4,5,6]])x1 = x.repeat_interleave(3,0)print("x1:\n", x1)x2 = x.repeat_interleave(3,1)print("x2:\n",x2)x1: tensor([[1, 2, 3],        [1, 2, 3],        [1, 2, 3],        [4, 5, 6],        [4, 5, 6],        [4, 5, 6]])x2: tensor([[1, 1, 1, 2, 2, 2, 3, 3, 3],        [4, 4, 4, 5, 5, 5, 6, 6, 6]])Process finished with exit code 0

其他函数:

torch.lerp(star, end, weight) : 返回结果是out= star t+ (end-start) * weighttorch.rsqrt(input) : 返回平方根的倒数torch.mean(input) : 返回平均值torch.std(input) : 返回标准偏差torch.prod(input) : 返回所有元素的乘积torch.sum(input) : 返回所有元素的之和torch.var(input) : 返回所有元素的方差torch.tanh(input) :返回元素双正切的结果torch.equal(torch.Tensor(a), torch.Tensor(b)) :两个张量进行比较,如果相等返回truetorch.max(input): 返回输入元素的最大值torch.min(input) : 返回输入元素的最小值element_size() :返回单个元素的字节torch.from_numpy(obj),利用一个numpy的array创建Tensor。注意,若obj原来是1列或者1行,无论obj是否为2维,所生成的Tensor都是一阶的,若需要2阶的Tensor,需要利用view()函数进行转换。torch.numel(obj),返回Tensor对象中的元素总数。torch.ones_like(input),返回一个全1的Tensor,其维度与input相一致torch.cat(seq, dim),在给定维度上对输入的张量序列进行连接操作torch.chunk(input, chunks, dim)在给定维度()上将输入张量进行分块torch.squeeze(input),将input中维度数值为1的维度去除。可以指定某一维度。共享input的内存torch.unsqeeze(input, dim),在input目前的dim维度上增加一维torch.clamp(input, min, max),将input的值约束在minmax之间torch.trunc(input),将input的小数部分舍去

在这里插入图片描述

Reference

[1] 透彻理解torch.tensor中对某一维度的操作们(mean,Softmax,batch norm, layer norm)

来源地址:https://blog.csdn.net/qq_35812205/article/details/130442457

--结束END--

本文标题: 【Pytorch基础教程39】torch常用tensor处理函数

本文链接: https://www.lsjlt.com/news/390985.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作