Python Pytorch:使用张量沿多个轴进行索引,或一次分散到多个索引

Python Pytorch:使用张量沿多个轴进行索引,或一次分散到多个索引,python,numpy,indexing,pytorch,Python,Numpy,Indexing,Pytorch,我试图更新Pytorch中多维张量的非常具体的索引,但我不确定如何访问正确的索引。在Numpy中,我可以用一种非常简单的方式来实现这一点: import numpy as np #set up the array containing the data data = 100*np.ones((10,10,2)) data[5:,:,:] = 0 #select the data points that I want to update idxs = np.nonzero(data.sum(2))

我试图更新Pytorch中多维张量的非常具体的索引,但我不确定如何访问正确的索引。在Numpy中,我可以用一种非常简单的方式来实现这一点:

import numpy as np
#set up the array containing the data
data = 100*np.ones((10,10,2))
data[5:,:,:] = 0
#select the data points that I want to update
idxs = np.nonzero(data.sum(2))
#generate the updates that I am going to do
updates = np.random.randint(5,size=(idxs[0].shape[0],2))
#update the data
data[idxs[0],idxs[1],:] = updates

我需要在Pytorch中实现这一点,但我不确定如何实现。看起来我需要散射函数,但它只在一个维度上有效,而不是我需要的多个维度。如何实现这一点?

这些操作在PyTorch中的工作原理完全相同,除了默认情况下返回大小为[z,n]的张量,其中z是非零元素的数量,n是维度的数量,而不是像NumPy那样返回大小为[z]的n个张量的元组,但这种行为可以通过设置为_tuple=True来改变

除此之外,您可以直接将其转换为PyTorch,但您需要确保类型匹配,因为您无法将torch.long default of torch.randint类型的张量指定给torch.float default of torch.ones类型的张量。在这种情况下,数据的类型可能为torch.long:

设置包含数据的数组 数据=100*火炬。一个10,10,2,数据类型=火炬。长 数据[5:,:,:]=0 选择要更新的数据点 idxs=torch.nonzerodata.sum2,因为tuple=True 生成我将要执行的更新 updates=torch.randint5,size=idxs[0]。shape[0],2 更新数据 数据[idxs[0],idxs[1],:]=更新
这些操作在PyTorch对应的操作中的工作方式完全相同,除了,默认情况下返回大小为[z,n]的张量,其中z是非零元素的数量,n是维度的数量,而不是像NumPy那样返回大小为[z]的n个张量的元组,但可以通过设置为_tuple=True来更改该行为

除此之外,您可以直接将其转换为PyTorch,但您需要确保类型匹配,因为您无法将torch.long default of torch.randint类型的张量指定给torch.float default of torch.ones类型的张量。在这种情况下,数据的类型可能为torch.long:

设置包含数据的数组 数据=100*火炬。一个10,10,2,数据类型=火炬。长 数据[5:,:,:]=0 选择要更新的数据点 idxs=torch.nonzerodata.sum2,因为tuple=True 生成我将要执行的更新 updates=torch.randint5,size=idxs[0]。shape[0],2 更新数据 数据[idxs[0],idxs[1],:]=更新
我知道了,我习惯了Tensorfow惯例,用聚集,分散,等等做所有这些,我习惯了Tensorfow惯例,用聚集,分散,等等做所有这些