Python 如何将pytorch张量中一行中的最大n个元素设置为1和о;是零吗?

Python 如何将pytorch张量中一行中的最大n个元素设置为1和о;是零吗?,python,numpy,pytorch,Python,Numpy,Pytorch,例如,如果我有张量 0.8, 0.1, 0.9, 0.2 0.7, 0.1, 0.4, 0.6 n=2,我想得到 1, 0, 1, 0 1, 0, 0, 1 或者最好是简单地做,但问题是相同的。对于性能效率,我们可以使用- 或者我们可以在argpartition步骤中使用np.argpartition(-a,n,axis=1)[:,:n] 样本运行- In [56]: a Out[56]: array([[0.8, 0.1, 0.9, 0.2], [0.7, 0.1, 0.4

例如,如果我有张量

0.8, 0.1, 0.9, 0.2
0.7, 0.1, 0.4, 0.6
n=2,我想得到

1, 0, 1, 0
1, 0, 0, 1

或者最好是简单地做,但问题是相同的。

对于性能效率,我们可以使用-

或者我们可以在
argpartition
步骤中使用
np.argpartition(-a,n,axis=1)[:,:n]

样本运行-

In [56]: a
Out[56]: 
array([[0.8, 0.1, 0.9, 0.2],
       [0.7, 0.1, 0.4, 0.6]])

In [57]: partition_assign(a, n=2)
Out[57]: 
array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

In [58]: partition_assign(a, n=3)
Out[58]: 
array([[1, 0, 1, 1],
       [1, 0, 1, 1]])

你可以使用列表理解。 简单快速

首先为每个数组选择阈值(基于
n

def张量_阈值(张量,n):
阈值=[arr张量中arr的排序(arr)[-n]
返回[[0如果x小于arr中x的第1个,则返回]
对于arr,th in-zip(张量,阈值)]
T=[[0.8,0.1,0.9,0.2],[0.7,0.1,0.4,0.6]]
张量_阈值(T,n=2)
>>> [[1, 0, 1, 0], [1, 0, 0, 1]]
您可以使用获取索引,然后将其设置为新张量的
1

t=torch.tensor([[0.8,0.1,0.9,0.2],[0.7,0.1,0.4,0.6])
tb=火炬。零(t形)#为1,0创建新的张量
#将“1”设置为topk索引
tb[(torch.arange(len(t)).unsqueze(1),torch.topk(t,2).指数)]=1
结核病
张量([[1,0,1,0.],
[1., 0., 0., 1.]])
n=3

tb=火炬零点(t形)
tb[(torch.arange(len(t)).unsqueze(1),torch.topk(t,3).指数)]=1
结核病
张量([[1,0,1,1.],
[1., 0., 1., 1.]])
In [56]: a
Out[56]: 
array([[0.8, 0.1, 0.9, 0.2],
       [0.7, 0.1, 0.4, 0.6]])

In [57]: partition_assign(a, n=2)
Out[57]: 
array([[1, 0, 1, 0],
       [1, 0, 0, 1]])

In [58]: partition_assign(a, n=3)
Out[58]: 
array([[1, 0, 1, 1],
       [1, 0, 1, 1]])
def tensor_threshold(tensor, n):
    thresholds = [sorted(arr)[-n] for arr in tensor]
    return [[0 if x < th else 1 for x in arr]
            for arr, th in zip(tensor, thresholds)]


T = [[0.8, 0.1, 0.9, 0.2], [0.7, 0.1, 0.4, 0.6]]

tensor_threshold(T, n=2)
>>> [[1, 0, 1, 0], [1, 0, 0, 1]]