tensor

作者: 三方斜阳 | 来源:发表于2021-02-27 15:53 被阅读0次

Tensor在PyTorch中负责存储基本数据,PyTorch针对Tensor也提供了相对丰富的函数和方法,所以PyTorch中的Tensor与NumPy的数组具有极高的相似性。
这里记录常用的用法,以便写代码时查阅:

1. 生成新的张量:

a = torch.Tensor([1, 2])
print(a)
>>
tensor([1., 2.])
是默认张量类型torch.FloatTensor()的别名,意思是生成浮点类型的别名
>>
======================================================================
a = torch.FloatTensor(2,3)
print(a)
a = torch.Tensor(2, 3)
print(a)
>>
tensor([[0., 0., 0.],
        [0., 0., 0.]])
tensor([[2.3694e-38, 2.3694e-38, 2.3694e-38],
        [2.3694e-38, 2.3694e-38, 2.3694e-38]])
>>
没有加中括号,参数就代表指定的维度
a = torch.Tensor(2,3,5)
print(a)
>>
tensor([[[1.4013e-45, 0.0000e+00, 2.8026e-45, 0.0000e+00, 4.2039e-45],
         [0.0000e+00, 5.6052e-45, 0.0000e+00, 5.6052e-45, 0.0000e+00],
         [7.0065e-45, 0.0000e+00, 8.4078e-45, 0.0000e+00, 9.8091e-45]],

        [[0.0000e+00, 2.8026e-45, 0.0000e+00, 2.8026e-45, 0.0000e+00],
         [2.8026e-45, 0.0000e+00, 1.4013e-45, 0.0000e+00, 1.1210e-44],
         [0.0000e+00, 1.1210e-44, 0.0000e+00, 1.1210e-44, 0.0000e+00]]])

2. 将数据转换为 tensor 并且指定类型

a = torch.tensor([2,3,4,5,6],dtype=float)
print(a)
>>
tensor([2., 3., 4., 5., 6.], dtype=torch.float64)

3. 生成随机 tensor

  • torch.randn: 随机生成的浮点数的取值满足均值为0,方差为1的正太分布。
  • torch.rand: 随机生成的浮点数据在0~1区间均匀分布。
  • 以及遍历tensor 访问其中的每个值的时候,需要 .item() 函数转换为一般数值,否则无法访问,比如需要得到每个值作为索引实数值的时候
a = torch.randn(2,3)
print(a)
for i in a:
  print(i)
  for j in i:
    print(j,j.item())
>>
tensor([[ 1.3661,  1.5158,  0.7361],
        [ 0.3195,  1.4628, -0.5975]])
tensor([1.3661, 1.5158, 0.7361])
tensor(1.3661) 1.3660553693771362
tensor(1.5158) 1.5157848596572876
tensor(0.7361) 0.7361060380935669
tensor([ 0.3195,  1.4628, -0.5975])
tensor(0.3195) 0.3195198178291321
tensor(1.4628) 1.4627504348754883
tensor(-0.5975) -0.5975139141082764

4. 生成全部为0 的tensor

a = torch.zeros(2,3)
print(a)
>>
tensor([[0., 0., 0.],
        [0., 0., 0.]])

5. tensor 维度变换 squeeze()

  • squeeze: 降低维度
  • unsqueeze: 增加维度
a=torch.Tensor(2,2,4)
print(a)
print(a[0], a[0].shape)
b=a[0].unsqueeze(1)
print(b,b.shape)
>>
tensor([[[1.0561e-38, 1.0929e-38, 1.0102e-38, 4.5918e-39],
         [9.9184e-39, 9.0000e-39, 1.0561e-38, 1.0561e-38]],

        [[1.0561e-38, 1.0745e-38, 1.0561e-38, 8.7245e-39],
         [9.6429e-39, 9.6429e-39, 8.7245e-39, 4.2246e-39]]])
tensor([[1.0561e-38, 1.0929e-38, 1.0102e-38, 4.5918e-39],
        [9.9184e-39, 9.0000e-39, 1.0561e-38, 1.0561e-38]]) torch.Size([2, 4])
tensor([[[1.0561e-38, 1.0929e-38, 1.0102e-38, 4.5918e-39]],

        [[9.9184e-39, 9.0000e-39, 1.0561e-38, 1.0561e-38]]]) torch.Size([2, 1, 4])
>>
  • 若squeeze()括号内为空,则将张量中所有维度为1的维数进行压缩,如将2131的张量降维到23维;若维度中无1维的维数,则保持源维度不变,如将234维的张量进行squeeze,则转换后维度不会变。
import torch
a=torch.Tensor(32,256,2)
a=a.squeeze(1)
a.size()
>>
torch.Size([32, 256, 2])

a=torch.Tensor(32,1,2)
a=a.squeeze(1)
a.size()
>>
torch.Size([32, 2])

tensor 切片:

选取固定行数的tensor,比如下例,分别选择奇数行和偶数行tensor,组成新的tensor

import torch
a=torch.rand(5,3)
print(a)
print(a[0::2]) #偶数
print(a[1::2])#奇数
>>
tensor([[0.3447, 0.4256, 0.9710],
        [0.0845, 0.6519, 0.5991],
        [0.1357, 0.5992, 0.0781],
        [0.2815, 0.2553, 0.2702],
        [0.0434, 0.2621, 0.3043]])
tensor([[0.3447, 0.4256, 0.9710],
        [0.1357, 0.5992, 0.0781],
        [0.0434, 0.2621, 0.3043]])
tensor([[0.0845, 0.6519, 0.5991],
        [0.2815, 0.2553, 0.2702]])
  1. 通过 tensor.index 选择指定行或者列数:
    torch.index_select(a, 0, torch.tensor(ji))
  • 参数1:被选择的 tensor
  • 参数2:0 按行,1 按列
  • 参数3:指定行数或者列数
import torch
a=torch.rand(5,3)
print(a,list(a.size())[0])
ji=list(range(1,list(a.size())[0],2))#选择奇数行
ou=list(range(0,list(a.size())[0],2))#选择偶数行
print(ji,ou)
index=torch.tensor(ji)#list转换为tensor
b = torch.index_select(a, 0, torch.tensor(ji))
print(b)
c = torch.index_select(a, 0, torch.tensor(ou))
print(c)
  1. 获得每个batch的第一个token的表示向量,取得[CLS] token 向量常用:
a=torch.Tensor(6,3,3)
print(a)
print(a.size())
b=a[:,0]
print(b)
print(b.size())
ji=b[1::2]
ou=b[0::2]
print(ji,ou)
output = F.cosine_similarity(ji, ou)#奇数偶数列对应计算余弦相似度
print(output)

torch.ne():

torch.ne(input, other, *, out=None) → Tensor

  • input (Tensor) – the tensor to compare
  • other (Tensor or float) – the tensor or value to compare
    逐个元素比较是否等于:
#比较input_ids 中哪些是等于padding_id,将这些置为mask,然后计算position id
mask = input_ids.ne(padding_idx).int()
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + 0) * mask

torch.cumsum()

设置 dim=1,tensor 后一列等于前一列值相加,这样来这是position id,之后乘以 mask,将设置为 padding的部分置零

将tensor某个维度进行顺序变换

import random
a=torch.rand(3,5)
print(a)
a=a[torch.randperm(a.size(0))]
print(a)
>>
tensor([[0.5561, 0.1485, 0.9181, 0.0765, 0.2890],
        [0.8729, 0.8473, 0.8055, 0.2315, 0.0465],
        [0.9385, 0.7309, 0.9644, 0.9727, 0.5027]])
tensor([[0.9385, 0.7309, 0.9644, 0.9727, 0.5027],
        [0.5561, 0.1485, 0.9181, 0.0765, 0.2890],
        [0.8729, 0.8473, 0.8055, 0.2315, 0.0465]])

reapt()

a=torch.tensor([[1,2,3]])

print(a.size())
b=a.repeat(2,1)
print(b,b.size())
print(a)

1. 将一句话的所有token 向量在每个维度取均值,获得句子向量表示:

import torch
a=torch.tensor([[1.0,2.0,3.0],[2.0,3.0,4.0]])
print(a)
m= torch.mean(a, dim=0)
print(m)
>>
tensor([[1., 2., 3.],
        [2., 3., 4.]])
tensor([1.5000, 2.5000, 3.5000])

2. 获得一个batch内 的每个句子的第一个token 即[CLS] 表示:

import torch
a=torch.tensor([[[1.0,2.0,3.0],[2.0,3.0,4.0]],[[9.0,9.0,9.0],[2.0,3.0,4.0]]])
print(a,a.shape)  # [batch,seq_length,dim]
m=a[:,0]
print(m)
>>
tensor([[[1., 2., 3.],
         [2., 3., 4.]],

        [[9., 9., 9.],
         [2., 3., 4.]]]) torch.Size([2, 2, 3])
tensor([[1., 2., 3.],
        [9., 9., 9.]])

3. 将bert不同层进行对应batch的[CLS]向量表示进行合并操作:concatenate,sum,mean:

import torch
a=torch.tensor([[1.0,2.0,3.0],[2.0,3.0,4.0]])
b=torch.tensor([[9.0,9.0,9.0],[3.0,3.0,4.0]])
print('a:',a)
print('b:',b)
d=torch.stack((a,b),dim=0).sum(0)
c=torch.stack((a,b),dim=0).mean(0)
e=torch.cat((a,b),dim=1)
print('d sum:',d)
print('c mean:',c)
print('e concat:',e)
>>
a: tensor([[1., 2., 3.],
           [2., 3., 4.]])  # [2*3]=[batch,dim]
b: tensor([[9., 9., 9.],
           [3., 3., 4.]])
d sum: tensor([[10., 11., 12.],
              [ 5.,  6.,  8.]])
c mean: tensor([[5.0000, 5.5000, 6.0000],
                [2.5000, 3.0000, 4.0000]])           
e concat: tensor([[1., 2., 3., 9., 9., 9.],
                  [2., 3., 4., 3., 3., 4.]])                

4. 将bert 字向量合并成词向量等操作:concatenate,sum,mean

import torch
a=torch.tensor([[1.0,2.0,3.0]])
b=torch.tensor([[2.0,2.0,3.0]])
print(a,a.shape)
print(b,b.shape)
d=torch.cat((a,b),dim=0) 
print(d,d.shape)
s=d.sum(0)
m=d.mean(0)
print(s,s.shape)
print(m,m.shape)
>>
tensor([[1., 2., 3.]]) torch.Size([1, 3])  # unsqueeze(0)
tensor([[2., 2., 3.]]) torch.Size([1, 3])
tensor([[1., 2., 3.],
        [2., 2., 3.]]) torch.Size([2, 3])
tensor([3., 4., 6.]) torch.Size([3])
tensor([1.5000, 2.0000, 3.0000]) torch.Size([3])

相关文章

网友评论

      本文标题:tensor

      本文链接:https://www.haomeiwen.com/subject/xyvvfltx.html