Exercise 18: TF-IDF - calculate the distances between each line to find which are the closest
How do i calculate the Manhattan distance between two lines when the vectors are not of same size. Should i put zero’s in the places where the word is not availale
in the given text
'''Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
all the king's horses and all the king's men
couldn't put Humpty together again'''
I have calculated the final tf_idf_vector as
[
[0.125, 0.08333333333333333, 0.041666666666666664, 0.041666666666666664, 0.08333333333333333, 0.041666666666666664],
[0.125, 0.08333333333333333, 0.041666666666666664, 0.08333333333333333, 0.041666666666666664, 0.041666666666666664],
[0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.027777777777777776, 0.027777777777777776, 0.1111111111111111, 0.1111111111111111, 0.1111111111111111, 0.027777777777777776],
[0.05, 0.05, 0.15000000000000002, 0.05, 0.05]
]
where line 3 has size 9 while rest has size 6
I need to "calculate the distances between each line to find which are the closest"I tried with
def manhattan_distance(list1, list2):
min_len = min(len(list1), len(list2))
distance = 0
for i in range(min_len):
distance += abs(list1[i] - list2[i])
if len(list1) > len(list2):
distance += sum(abs(value) for value in list1[min_len:])
elif len(list2) > len(list1):
distance += sum(abs(value) for value in list2[min_len:])
return distance
def calculate_manhattan_distances(lists):
n = len(lists)
dist = np.empty((n, n), dtype=float)
for i in range(n):
for j in range(i, n):
dist[i, j] = manhattan_distance(lists[i], lists[j])
dist[j, i] = dist[i, j]
return dist
But it does not pass all the testcases
Am I calculating the distance wrong, I checked the values it is correct.