英文:
How to take the top-k values of a tensor after a step function?
问题
我有一个张量:
my_tensor = torch.tensor([1.0, -0.5, -0.2, 0.6, 0.88])
我将这个张量通过一个step function
(不一定是这个函数,但是根据某个阈值,大于阈值的值为1,小于阈值的值为0):
values = torch.tensor([0.0])
step_func_out = torch.heaviside(my_tensor, values)
step_func_out
>>> torch.tensor([1.0, 0.0, 0.0, 1.0, 1.0])
然后,我需要根据原始张量的值,仅选择那些大于阈值的前k个值。例如,如果我们设定k=2
,输出应为:
final_output = torch.tensor([1.0, 0.0, 0.0, 0.0, 1.0])
如果k=4
,输出应为:
final_output = torch.tensor([1.0, 0.0, 0.0, 1.0, 1.0])
因为只有3个值大于阈值。
英文:
I have a tensor:
my_tensor = torch.tensor([1.0, -0.5, -0.2, 0.6, 0.88])
I'm sending this tensor through some step function
(not necessarily this one, but given some threshold the values above it are 1 and below are 0):
values = torch.tensor([0.0])
step_func_out = torch.heaviside(my_tensor, values)
step_func_out
>>> torch.tensor([1.0, 0.0, 0.0, 1.0, 1.0])
I then need to take the top-k
values based on the original tensor's values, but only those that are above the treshold. For example, if we say that k=2
the output should be:
final_output = torch.tensor([1.0, 0.0, 0.0, 0.0, 1.0])
if k=4
, the output should be:
final_output = torch.tensor([1.0, 0.0, 0.0, 1.0, 1.0])
since only 3 values are above the threshold
答案1
得分: 1
你可以这样做:
import torch
import numpy as np
my_tensor = torch.tensor([1.0, -0.5, -0.2, 0.6, 0.88])
values = torch.tensor([0.0])
step_func_out = torch.heaviside(my_tensor, values)
# 用于存储结果的张量
final_output = torch.zeros_like(step_func_out)
# 找到前k个元素的索引
_, inds = torch.topk(step_func_out * my_tensor, k=4)
# 将索引转换为布尔掩码
mask = torch.zeros_like(step_func_out).bool()
mask[inds] = True
# 在满足阈值函数条件的前k个元素位置上放置1.0
final_output[mask & (step_func_out == 1)] = 1
# 更新:如果my_tensor是多维的,可以按照以下方式更改上述代码:
...
_, inds = torch.topk((step_func_out * my_tensor).flatten(), k=4)
inds = np.array(np.unravel_index(inds.numpy(), final_output.shape))
...
希望对你有帮助!
英文:
You can do this
my_tensor = torch.tensor([1.0, -0.5, -0.2, 0.6, 0.88])
values = torch.tensor([0.0])
step_func_out = torch.heaviside(my_tensor, values)
# Tensor for result
final_output = torch.zeros_like(step_func_out)
# Find indicies of top-k
_, inds = torch.topk(step_func_out * my_tensor, k = 4)
# Convert indicies to boolean mask
mask = torch.zeros_like(step_func_out).bool()
mask[inds] = True
# Place 1.0 in places of values which:
# 1) into top-k
# 2) satisfies the conditions of the threshold function
final_output[mask & (step_func_out == 1)] = 1
Update
In case if my_tensor is multidimensional, change above code this way:
...
_, inds = torch.topk((step_func_out * my_tensor).flatten(), k = 4)
inds = np.array(np.unravel_index(inds.numpy(), final_output.shape))
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论