如何创建一个 PyTorch 张量,在第三维的中间全为 0 和 1?

How can I create a PyTorch tensor with all zeroes and a 1 in the middle of the third dimension?

我有一个张量,torch.Size([161, 161, 11]),我想将它全部设置为零,我可以这样做:self.conv1.weight.data = torch.zeros(self.conv1.weight.data.size())

除此之外,我希望第三维的第 6 列(中间)全部为 1。我该怎么做?

您可以在之后分配它:

self.conv1.weight.data[:, :, 6] = 1.0

或者如果这个张量是可训练的:

with torch.no_grad():
    self.conv1.weight.data[:, :, 6] = 1.0