1+ import numpy as np
2+ import torch
3+ import torch .nn as nn
4+
5+
6+ def abs_diff_linalg_norm (res_vector ):
7+ """
8+ Calculates the Euclidean norm (also known as the L2 norm) of a given array res_vector. This is equivalent to finding the square
9+ root of the sum of the squares of all the elements in the array. It's a fundamental operation in linear algebra and is often used
10+ to measure the "length" or "magnitude" of a vector. More at https://numpy.org/devdocs/reference/generated/numpy.linalg.norm.html
11+ Args:
12+ res_vector (list): The list of abs diff
13+
14+ Returns:
15+ float: "magnitude" of the diff vector.
16+ """
17+ return np .linalg .norm (res_vector )
18+
19+ def list_mean (val_list ):
20+ """
21+ Calculates the mean for all the values in a given list.
22+ Args:
23+ val_list (list): The list of values
24+
25+ Returns:
26+ float: mean value calculated.
27+ """
28+ return np .mean (val_list )
29+
30+ def tensor_abs_diff (tensor1 , tensor2 ):
31+ """
32+ Calculate the absolute difference between two tensors.
33+
34+ Args:
35+ tensor1 (torch.Tensor): The first input tensor.
36+ tensor2 (torch.Tensor): The second input tensor.
37+
38+ Returns:
39+ torch.Tensor: The absolute difference tensor.
40+
41+ Example:
42+ >>> tensor1 = torch.tensor([1, 2, 3])
43+ >>> tensor2 = torch.tensor([4, 5, 6])
44+ >>> abs_diff(tensor1, tensor2)
45+ torch.tensor([3, 3, 3])
46+ """
47+ abs_diff = torch .abs (tensor1 - tensor2 )
48+ return abs_diff
49+
50+ def tensor_cos_sim (tensor1 , tensor2 ):
51+ """
52+ Computes the cosine similarity between two tensors.
53+
54+ Args:
55+ tensor1 (torch.Tensor): The first input tensor.
56+ tensor2 (torch.Tensor): The second input tensor.
57+
58+ Returns:
59+ torch.Tensor: The cosine similarity between the two input tensors.
60+
61+ Example:
62+ >>> import torch
63+ >>> tensor1 = torch.randn(3, 5)
64+ >>> tensor2 = torch.randn(3, 5)
65+ >>> sim = cos_sim(tensor1, tensor2)
66+ >>> print(sim)
67+ """
68+ cos = nn .CosineSimilarity (dim = - 1 )
69+ tensor1 [tensor1 == 0.0 ] = 1e-6
70+ tensor2 [tensor2 == 0.0 ] = 1e-6
71+ cos_sim = cos (tensor1 , tensor2 )
72+ return cos_sim
0 commit comments