Course 5 Week 2 Assignment 1 Exercise 2

I am having a hard time to understand how to compute the cosine similarity in Excercise 2 - complete analogy

From the template # Compute cosine similarity between the vector (e_b - e_a) and the vector ((w’s vector representation) - e_c)

How to best compute the second argument "(w’s vector representation - e_c) when calling the cosine similarity subroutine?
I used: ‘word_to_vec_map[w] - e_c’ but get an error when I run the complete_analogy_test

However, I am not sure if the error is related to this line of code?


TypeError Traceback (most recent call last)
in
33 print("\033[92mAll tests passed")
34
—> 35 complete_analogy_test(complete_analogy)

in complete_analogy_test(target)
26 word_to_vec_map[key] = np.array(word_to_vec_map[key])
27
—> 28 assert(target(‘a’, ‘a_nw’, ‘c’, word_to_vec_map) == ‘c_nw’)
29 assert(target(‘a’, ‘a_s’, ‘c’, word_to_vec_map) == ‘c_s’)
30 assert(target(‘a’, ‘synonym_of_a’, ‘c’, word_to_vec_map) != ‘c’), “Best word cannot be input query”

in complete_analogy(word_a, word_b, word_c, word_to_vec_map)
44 # If the cosine_sim is more than the max_cosine_sim seen so far,
45 # then: set the new max_cosine_sim to the current cosine_sim and the best_word to the current word (≈3 lines)
—> 46 if None > None:
47 max_cosine_sim = None
48 best_word = None

TypeError: ‘>’ not supported between instances of ‘NoneType’ and ‘NoneType’

That is the correct code for the 2nd parameter that is sent to consine_similarity(…)

1 Like

The problem seems to be that you haven’t completed the last three lines in the complete_analogy() function (where all those “None” statements are).

hi TMosh, i did cosine_sim = cosine_similarity(e_b-e_a, word_to_vec_map[‘c_w’]-e_c) and complete the function as you said, but still got error , could you have a check?


TypeError Traceback (most recent call last)
in
33 print("\033[92mAll tests passed")
34
—> 35 complete_analogy_test(complete_analogy)

in complete_analogy_test(target)
26 word_to_vec_map[key] = np.array(word_to_vec_map[key])
27
—> 28 assert(target(‘a’, ‘a_nw’, ‘c’, word_to_vec_map) == ‘c_nw’)
29 assert(target(‘a’, ‘a_s’, ‘c’, word_to_vec_map) == ‘c_s’)
30 assert(target(‘a’, ‘synonym_of_a’, ‘c’, word_to_vec_map) != ‘c’), “Best word cannot be input query”

in complete_analogy(word_a, word_b, word_c, word_to_vec_map)
41 print(word_to_vec_map[w])
42 print(np.shape(word_to_vec_map[w]))
—> 43 cosine_sim = cosine_similarity(e_b-e_a, word_to_vec_map[w]-e_c)
44
45 # If the cosine_sim is more than the max_cosine_sim seen so far,

TypeError: unsupported operand type(s) for -: ‘str’ and ‘str’

Your case seems to be simple, since you tried to subtract “string” from “string”. The most possible error is you did not convert “string” to “vector” by using “word_to_vec_map”.

Most likely the issue is in the code you implemented for this comment instruction:
# Get the word embeddings e_a, e_b and e_c (≈1-3 lines)