按照group取tensor中最大值的下标

1.创建一个tensor,取每个元素对应的组存在index里面,如下例,5个group。输出每个group最大值在对应group中的下标。

输出结果为 

即 每个group中 的最大值 在每个group的下标。 index的值0-4表示5个group,index中元素值相同的表示在 tensor中是一个group。

import torch

# 假设tensor为N*1维的tensor
tensor = torch.tensor([1, 2, 4, 3, 5, 6, 7, 8, 9, 1,41])

# 假设index为N*1维的tensor
index = torch.tensor([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4])

# 将tensor和index合并为一个N*2的tensor
combined_tensor = torch.stack((index, tensor), dim=1)

# 使用torch.max函数取出每一组的最大值的下标
max_indices = torch.zeros(index.max().item() + 1, dtype=torch.long)
for i in range(index.max().item() + 1):
    max_indices[i] = combined_tensor[combined_tensor[:, 0] == i, 1].argmax()

print(max_indices)

2.

1.创建一个tensor,取每个元素对应的组存在index里面,如下例,5个group。输出每个group最大值在对应原始中的下标。

输出结果为 

即 每个group中 的最大值 在每个group的下标。 index的值0-4表示5个group,index中元素值相同的表示在 tensor中是一个group。

import torch

# 假设tensor为N*1维的tensor
tensor = torch.tensor([1, 3, 2, 5, 4, 7, 6, 1,9, 8, 10,41])

# 假设index为N*1维的tensor
index = torch.tensor([0, 0, 1, 1, 2, 2, 3, 3, 3, 4, 4,4])

max_indices = []
for i in range(index.max().item() + 1):
    group = (index == i)  # 找出属于当前组的元素
    max_index = torch.argmax(tensor[group])  # 找出当前组中的最大值的索引
    true_index = torch.nonzero(group)[max_index].item()  # 找到在原始tensor中的索引
    max_indices.append(true_index)

print(max_indices)  # 输出每一组最大值在原始tensor中的下标

相关推荐

  1. clickhouse 查询group 分组一行数据。

    2024-01-12 07:58:04       41 阅读
  2. 力扣1802.有界数组指定下标

    2024-01-12 07:58:04       30 阅读
  3. PHP获取数组下标

    2024-01-12 07:58:04       48 阅读
  4. C语言求数组

    2024-01-12 07:58:04       48 阅读
  5. (60)矩阵局部

    2024-01-12 07:58:04       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-12 07:58:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-12 07:58:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-12 07:58:04       82 阅读
  4. Python语言-面向对象

    2024-01-12 07:58:04       91 阅读

热门阅读

  1. openssl3.2 - 官方dmeo学习 - sconnect.c

    2024-01-12 07:58:04       51 阅读
  2. 本地由LeetCode输入构建二叉树(C++版)

    2024-01-12 07:58:04       51 阅读
  3. 探索计算机网络:应用层的魅力

    2024-01-12 07:58:04       55 阅读
  4. 计算机网络层之ICMP与IGMP

    2024-01-12 07:58:04       56 阅读
  5. 决策树回归(Decision Tree Regression)

    2024-01-12 07:58:04       58 阅读
  6. 视觉SLAM十四讲|【五】相机与IMU时间戳同步

    2024-01-12 07:58:04       52 阅读
  7. 自然语言处理(NLP)技术

    2024-01-12 07:58:04       51 阅读
  8. 使用Sqoop将Hive数据导出到TiDB

    2024-01-12 07:58:04       53 阅读
  9. k8s存储卷和数据卷下

    2024-01-12 07:58:04       46 阅读