我有一个参数列表,我想对列表中的所有元素求和
import torch
from torch import nn
a = nn.Parameter(torch.rand(1))
b = nn.Parameter(torch.rand(1))
my_list = [a, b]
torch.sum(*my_list)
我收到错误
Traceback (most recent call last): File "<input>", line 8, in <module> TypeError: sum() received an invalid combination of arguments - got (Parameter, Parameter), but expected one of: * (Tensor input, *, torch.dtype dtype) * (Tensor input, tuple of ints dim, bool keepdim, *, torch.dtype dtype, Tensor out) * (Tensor input, tuple of names dim, bool keepdim, *, torch.dtype dtype, Tensor out)
我想知道是否有办法在
torch.sum
s 上执行类似 Parameter
的操作?
您可能想要访问例如 nn.Parameter() a.data 返回火炬张量。我希望这有帮助。
尝试打印 a 的 .data 字段以获得一些直觉:
print(a.data)
您需要使用 torch.stack 连接张量,然后求和。
import torch
from torch import nn
a=nn.Parameter(torch.rand(1))
b=nn.Parameter(torch.rand(1))
l=[a,b]
l1=torch.stack(l,dim=0)
torch.sum(l)