【发布时间】:2021-02-09 17:52:44
【问题描述】:
我有一个形状为 (batch_size, number_maps, x_val, y_val) 的火炬张量。张量使用 sigmoid 函数进行归一化,因此在[0, 1] 范围内。我想找到每个地图的协方差,所以我想要一个形状为 (batch_size, number_maps, 2, 2) 的张量。据我所知,在 numpy 中没有 torch.cov() 函数。如何在不将其转换为 numpy 的情况下有效地计算协方差?
编辑:
def get_covariance(tensor):
bn, nk, w, h = tensor.shape
tensor_reshape = tensor.reshape(bn, nk, 2, -1)
x = tensor_reshape[:, :, 0, :]
y = tensor_reshape[:, :, 1, :]
mean_x = torch.mean(x, dim=2).unsqueeze(-1)
mean_y = torch.mean(y, dim=2).unsqueeze(-1)
xx = torch.sum((x - mean_x) * (x - mean_x), dim=2).unsqueeze(-1) / (h*w - 1)
xy = torch.sum((x - mean_x) * (y - mean_y), dim=2).unsqueeze(-1) / (h*w - 1)
yx = xy
yy = torch.sum((y - mean_y) * (y - mean_y), dim=2).unsqueeze(-1) / (h*w - 1)
cov = torch.cat((xx, xy, yx, yy), dim=2)
cov = cov.reshape(bn, nk, 2, 2)
return cov
我现在尝试了以下方法,但我很确定它不正确。
【问题讨论】:
标签: python pytorch covariance torch