从 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]])