gpt4 book ai didi

python - 如何向量化总和?张量[i, :, :,:] + 张量[i]

转载 作者:行者123 更新时间:2023-12-01 00:48:37 27 4
gpt4 key购买 nike

我想矢量化以下代码:

def style_noise(self, y, style):
n = torch.randn(y.shape)
for i in range(n.shape[0]):
n[i] = (n[i] - n.mean(dim=(1, 2, 3))[i]) * style.std(dim=(1, 2, 3))[i] / n.std(dim=(1, 2, 3))[i] + style.mean(dim=(1, 2, 3))[i]
noise = Variable(n, requires_grad=False).to(y.device)
return noise

我没有找到这样做的好方法。

y 和 style 是 4d 张量,例如 style.shape = y.shape = [64, 3, 128, 128]

我想返回噪声张量,noise.shape = [64, 3, 128, 128]

如果问题不清楚,请在评论中告诉我。

最佳答案

您的用例正是 .mean.std 方法带有 keepdim 参数的原因。您可以利用它来启用 broadcasting semantics为您矢量化事物:

def style_noise(self, y, style):
n = torch.randn(y.shape)
n_mean = n.mean(dim=(1, 2, 3), keepdim=True)
n_std = n.std(dim=(1, 2, 3), keepdim=True)
style_mean = style.mean(dim=(1, 2, 3), keepdim=True)
style_std = style.std(dim=(1, 2, 3), keepdim=True)
n = (n - n_mean) * style_std / n_std + style_mean
noise = Variable(n, requires_grad=False).to(y.device)
return noise

关于python - 如何向量化总和?张量[i, :, :,:] + 张量[i],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56750040/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com