Exercise 18 Advanced
Greetings,
I am having trouble with exercise 18 advanced. I was able to get the intermediate solution and calculate vectors of TFIDF scores; i am also able to calculate the Manhattan distance between these vectors. However when I submit I get a :Test Failed: AssertionError: '(1,)' not found in ['(0, 1)', '(1, 0)'].
It looks like its looking for an array of two tuples, yet the shortest distance between one vector and another is a single number with an index that gets printed (in this case being at index 2). If anyone has time to look at my code and see where I’m falling short, I would appreciate it:
# DATA BLOCK
import numpy as np
text = '''he really really loves coffee
my sister dislikes coffee
my sister loves tea'''
import math
def distance(row1, row2):
# fix this function so that it returns
# the sum of differences between the occurrences
# of each word in row1 and row2.
# you can assume that row1 and row2 are lists with equal length, containing numeric values.
total = 0
for i in range(len(row1)):
total = total + abs(row1[i] - row2[i])
return total
def main(text):
# split the text first into lines and then into lists of words
docs = [line.split() for line in text.splitlines()]
N = len(docs)
# create the vocabulary: the list of words that appear at least once
vocabulary = list(set(text.split()))
df = {}
tf = {}
for word in vocabulary:
# tf: number of occurrences of word w in document divided by document length
# note: tf[word] will be a list containing the tf of each word for each document
# for example tf['he'][0] contains the term frequence of the word 'he' in the first
# document
tf[word] = [doc.count(word) / len(doc) for doc in docs]
# df: number of documents containing word w
df[word] = sum([word in doc for doc in docs]) / N
doc_list=[]
# loop through documents to calculate the tf-idf values
for doc_index, doc in enumerate(docs):
tfidf = []
for word in vocabulary:
# ADD THE CORRECT FORMULA HERE. Remember to use the base 10 logarithm: math.log(x, 10)
temp_list = []
temp = math.log(1 / df[word], 10) * tf[word][doc_index]
tfidf.append(temp)
doc_list.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.
dist_vector = []
for i in range(len(doc_list)):
dist=distance(doc_list[i],doc_list[i-1])
dist_vector.append(dist)
array_vector=np.array(dist_vector)
print(np.unravel_index(np.argmin(array_vector),array_vector.shape))
main(text)