先上代码:

import torch
#coco
#索引操作
# 设置一个随机种子
torch.manual_seed(100)
# 生成一个形状为2x3的矩阵
x = torch.randn(2,3)
print(x)
# tensor([[ 0.3607, -0.2859, -0.3938],
#         [ 0.2429, -1.3833, -2.3134]])
# 根据索引获取第1行,所有数据
# 第一参数大家都知道是表示对象。
# 第二个参数dim表示维度,具体取哪一个维度就要看你对象原本的维度数了,
# 比如一个torch.Size([1, 3, 3])的张量,你想取某一列,那dim就该取2或-1,
# 一个torch.Size([ 3,3])的张量,想取某一行的话,那dim就该取1或-1。
# index表示你想取的索引的序号,比如torch.tensor([0, 1])就是取第一第二列
b = torch.index_select(x,1,torch.LongTensor([0]))
print('bbbbbb',b)
# bbbbbb tensor([[0.3607],
#         [0.2429]])
# 取指定元素
# input (Tensor) – 源张量
# dim (int) – 索引的轴
# index (LongTensor) – 聚合元素的下标
cc=torch.gather(x, 1, torch.LongTensor([[0, 0], [1, 0]]))
print('cccc',cc)
# cccc tensor([[ 0.3607,  0.3607],
#         [-1.3833,  0.2429]])
x[0, :]
# 获取最后一列数据
x[:, -1]
# 生成是否大于0的Byter张量
mask = x > 0
print(mask)
# tensor([[ True, False, False],
#         [ True, False, False]])
# 获取大于0的值
tt=torch.masked_select(x, mask)
print(tt)
# tensor([0.3607, 0.2429])
# 获取非0下标,即行,列索引
pp=torch.nonzero(mask)
print(pp)
# tensor([[0, 0],
#         [1, 0]])

# 获取指定索引对应的值,输出根据以下规则得到
# out[i][j] = input[index[i][j]][j]  # if dim == 0
# out[i][j] = input[i][index[i][j]]  # if dim == 1
index = torch.LongTensor([[0, 1, 1]])
print(index)
# tensor([[0, 1, 1]])
aa=torch.gather(x, 0, index)  #取横坐标为0,1,1的数据
print(aa)
# tensor([[ 0.3607, -1.3833, -2.3134]])
index = torch.LongTensor([[0, 1, 1], [1, 1, 1]])
a = torch.gather(x, 1, index)
print(a)
# 原来的tensor([[ 0.3607, -0.2859, -0.3938],
#         [ 0.2429, -1.3833, -2.3134]]) 通过公式取:[0,0]、[0,1]、[0,1]    [1,1]、[1,1]、[1,1]
# tensor([[ 0.3607, -0.2859, -0.2859],
#         [-1.3833, -1.3833, -1.3833]])
# 把a的值返回到一个2x3的0矩阵中,对应位置补充数据
z = torch.zeros(2, 3)
z.scatter_(1, index, a)
print(z)
# tensor([[ 0.3607, -0.2859,  0.0000],
#         [ 0.0000, -1.3833,  0.0000]])

        我想赢,这是我的动力来源。不管怎么郁闷纠结或者找借口,结果都不会改变。新的敌人是自己。

——羽生结弦 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐