学习参数的约束线性组合是pytorch?

Constrained Linear combination of learned parameters is pytorch?

我有三个张量 X、Y、Z,我想学习这些张量的最优凸组合,需要一定的代价,即

aX + bY + cZ 使得 a + b + c = 1。我如何在 Pytorch 中轻松地做到这一点?

我知道我可以沿着未压缩的轴连接然后应用线性层:

X = X.unsqueeze(-1)
Y = Y.unsqueeze(-1)
Z = Z.unsqueeze(-1)
W = torch.cat([X,Y,Z], dim = -1)   #third axis has dimension  3)
W = torch.linear(3,1)(W)

但这不会应用凸组合约束...

我找到了一个对那些感兴趣的人来说效果很好的答案,它可以概括为 N 个张量的线性组合,您只需要更改权重 dim 和连接的张量数量。

weights = nn.Parameter(torch.rand(1,3))
X = X.unsqueeze(-1)
Y = Y.unsqueeze(-1)
Z = Z.unsqueeze(-1)
weights_normalized = nn.functional.softmax(weights, dim=-1)
output = torch.matmul(torch.cat([X, Y, Z], dim=-1), weights_normalized.t()).squeeze()