Exercise 18: TF-IDF I am Stuck
Any one help me to resolve this problem
Test Failed: AssertionError: '[[0.05017166594399686, 0.0, 0.10034333188799371, 0.0, 0.0, 0.0, 0.10034333188799371, 0.0, 0.0, 0.020823122768049988, 0.05017166594399686, 0.0, 0.10034333188799371, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.05017166594399686, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.020823122768049988, 0.05017166594399686, 0.0, 0.0, 0.10034333188799371, 0.0, 0.10034333188799371, 0.10034333188799371, 0.0, 0.0], [0.0, 0.06689555459199581, 0.0, 0.13379110918399162, 0.13379110918399162, 0.0, 0.0, 0.13379110918399162, 0.06689555459199581, 0.0, 0.0, 0.06689555459199581, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.12041199826559246, 0.0, 0.0, 0.0, 0.024987747321659988, 0.0, 0.0, 0.0, 0.0, 0.12041199826559246, 0.0, 0.0, 0.12041199826559246, 0.12041199826559246]]' not found in ['(0, 1)', '(1, 0)']
import math
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'''
def main(text):
# tasks your code should perform:
# 1. split the text into words, and get a list of unique words that appear in it
# a short one-liner to separate the text into sentences (with words lower-cased to make words equal
# despite casing) can be done with
docs = [line.lower().split() for line in text.split('\n')]
N = len(docs)
# 2. go over each unique word and calculate its term frequency, and its document frequency
vocabulary = list(set(text.lower().split()))
df = {word: sum(word in doc for doc in docs) / N for word in vocabulary}
tf = {word: [doc.count(word) / len(doc) for doc in docs] for word in vocabulary}
# 3. after you have your term frequencies and document frequencies, go over each line in the text and
# calculate its TF-IDF representation, which will be a vector
tfidf_vectors = []
for doc_index, doc in enumerate(docs):
tfidf = [tf[word][doc_index] * math.log(1 / df[word], 10) if df[word] != 0 else 0 for word in vocabulary]
tfidf_vectors.append(tfidf)
# 4. after you have calculated the TF-IDF representations for each line in the text, you need to
# calculate the distances between each line to find which are the closest.
distances = [[sum(abs(tfidf_vectors[i][j] - tfidf_vectors[k][j]) for j in range(len(vocabulary))) for k in range(N)] for i in range(N)]
print(tfidf_vectors)
print(distances)
main(text)