【问题标题】:How to convert torch.norm to cosine distance如何将 torch.norm 转换为余弦距离
【发布时间】:2021-08-13 14:56:23
【问题描述】:

我想把范数距离改成余弦距离,帮我把这个函数转换成余弦距离

def feat_prototype_distance(self, feat):
    N, C, H, W = feat.shape
    feat_proto_distance = -torch.ones((N, self.class_numbers, H, W)).to(feat.device)
    for i in range(self.class_numbers):
        feat_proto_distance[:, i, :, :] = torch.norm(self.objective_vectors[i].reshape(-1,1,1).expand(-1, H, W) - feat, 2, dim=1)
    return feat_proto_distance

这是使用带形状的范数距离的原始函数: self.objective_vectors[i].reshape(-1,1,1).expand(-1, H, W): torch.Size([256, 128, 224]) 壮举:torch.Size([8, 256, 128, 224]) with 8 is batch_size

【问题讨论】:

    标签: pytorch torch cosine-similarity


    【解决方案1】:

    你可以使用torch.nn.CosineSimilarity

    你的代码结构对我来说不是很清楚,但你可能会这样做:

    def feat_prototype_distance(self, feat):
        distance_metric = torch.nn.CosineSimilarity(dim=1)
        N, C, H, W = feat.shape
        feat_proto_distance = -torch.ones((N, self.class_numbers, H, W)).to(feat.device)
        for i in range(self.class_numbers):
            feat_proto_distance[:, i, :, :] = distance_metric(self.objective_vectors[i].reshape(-1,1,1).expand(-1, H, W), feat)
        return feat_proto_distance
    

    【讨论】:

    • 我也尝试过这种方式,但没有成功。因为它们的形状不同。 self.objective_vectors[i].reshape(-1,1,1).expand(-1, H, W) 是形状为 [256, 128, 224] 的簇的中心,feat 是形状为的向量是 [8, 256, 128, 224] 其中 8 是 batch_size
    • 请帮帮我! :((((
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2017-12-12
    • 2021-09-09
    • 1970-01-01
    • 2017-09-27
    • 2016-12-05
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多