# How to convert torch.norm to cosine distance

I want to change norm distance to cosine distance, help me convert this function to cosine distance

``````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
``````

This is original function using norm distance with shapes:
self.objective_vectors[i].reshape(-1,1,1).expand(-1, H, W): torch.Size([256, 128, 224])
feat: torch.Size([8, 256, 128, 224]) with 8 is batch_size

``````def get_cosine_distance(x: Tensor, y: Tensor):
"""
:param x: [B1, D]
:param y: [B2, D]
:return: [B1, B2]
"""
x_norm = torch.norm(x, dim=1, keepdim=True)
y_norm = torch.norm(y, dim=1, keepdim=True)
return torch.mm(x, y.transpose(0, 1)) / x_norm / y_norm.transpose(0, 1)

get_cosine_distance(objective_vectors[i].reshape..., feat)
``````

I think replacing the `torch.norm` part in your code with `get_cosine_distance` would resolve your issue.
Is it what you want?

I have tried but no success. Because feat_proto_distance[:, i, :, :] is 4 dimensional but it returns 2 dimensional

Help me! :(((((((((((((((((((((((