Operands could not be broadcast together with shapes (50,) (2,) (50,)

Getting this error: operands could not be broadcast together with shapes (50,) (2,) (50,)

I am initializing like this: avg = np.zeros(shape=50)

Hi @Hraday

Which assignment ?

C5 W2 A2 Emojify : Exercise 1 - sentence_to_avg

words = [i.lower() for i in sentence.split()]

# Initialize the average word vector, should have the same shape as your word vectors.
avg = np.zeros(shape=50)
# Initialize count to 0
count = 0

# Step 2: average the word vectors. You can loop over the words in the list "words".
for w in ((words)):
    # Check that word exists in word_to_vec_map
    if w in word_to_vec_map:
        avg += word_to_vec_map[w]
        # Increment count
        count +=1
if count > 0:
    # Get the average. But only if count > 0
    avg = avg/len(words)

return avg

Can you tell me what am I doing wrong ?

ValueError: operands could not be broadcast together with shapes (50,) (2,) (50,)

I am curious why you feel that a hard-coded value of 50 is the correct shape?

Please review the instructions:

The notebook provides some code that selects a word “any_word” from the dictionary. That’s the correct key to use to get the desired shape.

@TMosh @Kic
Thanks a lot for highlighting “any words”. You guys are gem.

I’m really lost here, can I get some help? I looked at this after I read the key error love thread, and surmised my issue is in initializing the avg array before I had:
Now I have something along the lines of:
but I’m stuck and not sure what goes in the brackets, I know not to hard code the answer but a random number doesn’t work either.

Hi @olarson117

any_word should be used as an index to word_to_vec_map. So to get the shape of the word vector:

1 Like

thanks so much! figured it out thank you.

Can anyone tell what we should take the size of the avg array as?

Honestly I still don’t understand why hard coding 50 in np.zeros(50) as the initialization doesn’t work whereas word_to_vec_map[list(word_to_vec_map.keys())[0]].shape which also returns (50,) works ? What am I missing here ?

We can not assume that the shape of a vector map is always 50. It can be 60, 100, whatever…
If a vector map is enhanced and now includes additional features like total 100, do you want to re-write your code ? This is quite inefficient. Once you get the shape dynamically and use it for initialization, then, you do not need to touch any even if a vector map is enhanced.
Think about modern system which consists of millions of code. You can not check one by one.

Dear Hitoro & mentors;

initiation avg=np.zeros(word_to_vec_map[list(word_to_vec_map.keys())[0]].shape)

gives test error as love.

_________________any idea?