记录一些对tensor的操作

这篇博客介绍了如何在PyTorch中操作Tensor。内容包括从Tensor中取出单个value使用.item()方法,处理包含多个value的Tensor则用.tolist()转为list。还展示了如何在Tensor中插入值,通过torch.cat()函数实现。此外,讲解了torch.ne()函数用于判断元素是否不相等,并给出了实例。
摘要由CSDN通过智能技术生成

从 tensor 中 取出 value: 

print(tensor_value)
# tensor(26602)

print(tensor_value.item())
# 26602
# 但是这种方法要注意的是 tensor_vale 当中只能有一个value,否则的话,会报错

# 如果tensor 当中有多个 value, 则可以使用 tensor_value.tolist() 将 tensor 转换为 list

tensor 插入

token_tensor
Out[27]: 
tensor([[    0, 45093,   766,    13, 26602, 45200,    16, 50264,     4, 34222,
         45200,     6,     5,  3260,  5377,    16, 26602, 45200, 15747,  5457,
            92, 26602, 45200, 47006, 15747,     4, 48696, 47006,     2]])

part1 = self.token_tensor[:,0:location]
Out[31]: tensor([[    0, 45093,   766,    13, 26602, 45200,    16]])

afterPart = self.token_tensor[:,location+1:]  # 我这里需要将location 位置上的值挖掉
Out[43]: 
tensor([[    4, 34222, 45200,     6,     5,  3260,  5377,    16, 26602, 45200,
         15747,  5457,    92, 26602, 45200, 47006, 15747,     4, 48696, 47006,
             2]])


token_tensor = torch.cat([beforPart,insertID_tensor,afterPart],dim=1)  # 维度都是 1*length
Out[42]: 
tensor([[    0, 45093,   766,    13, 26602, 45200,    16, 50264,    42,     4,
         34222, 45200,     6,     5,  3260,  5377,    16, 26602, 45200, 15747,
          5457,    92, 26602, 45200, 47006, 15747,     4, 48696, 47006,     2]])

torch.ne()——判断元素是否不相等

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

import torch
a=torch.arange(10).view(2,5)
b=torch.arange(5).view(1,5)
c=torch.ne(a,b)
c
Out[5]:
tensor([[False, False, False, False, False],
        [ True,  True,  True,  True,  True]])

# 比较 d 中的元素 和 6 是否相等
d = a.ne(6)
d
Out[8]: 
tensor([[ True,  True,  True,  True,  True],
        [ True, False,  True,  True,  True]])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值