Neural network 只有一个元素张量可以转换为python标量

Neural network 只有一个元素张量可以转换为python标量,neural-network,pytorch,layer,Neural Network,Pytorch,Layer,在获取网络输出的培训过程中,上述函数产生了以下错误,它在自定义层内调用,我不知道它引用了什么,有什么想法吗?列表理解中的问题,如blah是张量列表 我将通过循环a.shape[0]和a.shape[1]创建一个简单的张量列表,然后将所有内容堆叠到一个张量中 def Log(A): ''' theta = arccos((tr(A)-1)/2) K=1/(2sin(theta))(A-A^T) log(A)=theta K ''' theta=tor

在获取网络输出的培训过程中,上述函数产生了以下错误,它在自定义层内调用,我不知道它引用了什么,有什么想法吗?

列表理解中的问题,如
blah
是张量列表

我将通过循环
a.shape[0]
a.shape[1]
创建一个简单的张量列表,然后将所有内容堆叠到一个张量中

def Log(A):
    '''
    theta = arccos((tr(A)-1)/2)
    K=1/(2sin(theta))(A-A^T)
    log(A)=theta K
    '''
    theta=torch.acos(torch.tensor((torch.trace(A)-1)/2))
    K=(1/(2*torch.sin(theta)))*(torch.add(A,-torch.transpose(A,0,1)))
    
    return theta*K

def tensor_Log(A):
    blah=[[Log(A[i,j]) for j in range(A.shape[1])] for i in range(A.shape[0])]
    new=torch.tensor(blah)
    
    return new

ValueError: only one element tensors can be converted to Python scalars
然后,您可以使用
重塑
查看
恢复所需格式:

R = torch.stack([Log(A[i,j]) for i in range(A.shape[0]) for j in range(A.shape[1])])

清单理解中的问题是一系列张量

我将通过循环
a.shape[0]
a.shape[1]
创建一个简单的张量列表,然后将所有内容堆叠到一个张量中

def Log(A):
    '''
    theta = arccos((tr(A)-1)/2)
    K=1/(2sin(theta))(A-A^T)
    log(A)=theta K
    '''
    theta=torch.acos(torch.tensor((torch.trace(A)-1)/2))
    K=(1/(2*torch.sin(theta)))*(torch.add(A,-torch.transpose(A,0,1)))
    
    return theta*K

def tensor_Log(A):
    blah=[[Log(A[i,j]) for j in range(A.shape[1])] for i in range(A.shape[0])]
    new=torch.tensor(blah)
    
    return new

ValueError: only one element tensors can be converted to Python scalars
然后,您可以使用
重塑
查看
恢复所需格式:

R = torch.stack([Log(A[i,j]) for i in range(A.shape[0]) for j in range(A.shape[1])])

tensor\u Log
Log
的输入形状是什么?@Ivan tensor\u Log是一个4张量,而Log只是一个4张量matrix@Ivan更具体地说,张量_Log是bs x额外尺寸x 3 x 3,Log接受3x3矩阵,哪一行准确地抛出了这个错误?
tensor\u Log
Log
的输入形状是什么?@Ivan tensor\u Log是一个4张量,而Log只是一个4张量matrix@Ivan更具体地说,tensor_Log是bs x extra dim x 3 x 3,Log接受一个3x3矩阵,哪一行准确地抛出了这个错误?干杯,mate,修正了它。奇怪的是,我在自定义层中使用的另一个函数上使用了相同类型的列表comp,并且没有在其中抛出错误。这个实例
Log
已经返回了一个张量,因此您的列表理解变成了一个张量列表,它
torch.tensor
不喜欢接收。如果
Log
返回了一个标量,它就可以工作了,也许这就是它在其他函数中工作的原因。我很高兴这有帮助。干杯,伙计,修好了。奇怪的是,我在自定义层中使用的另一个函数上使用了相同类型的列表comp,并且没有在其中抛出错误。这个实例
Log
已经返回了一个张量,因此您的列表理解变成了一个张量列表,它
torch.tensor
不喜欢接收。如果
Log
返回了一个标量,它就可以工作了,也许这就是它在其他函数中工作的原因。我很高兴这有帮助。