Get startedGet started for free

Part 2: Treasure hunt

Now there's a little twist to the treasure hunt. You have forgotten to pack your laptop and you only have a device with limited memory on you. The code you write should be less than 4 lines of code (excluding comments). Since you need to make the code as compact as possible you will be using list comprehension.

List comprehension is a great way to loop through data with a single line of code. For example, if you want to get all the even numbers from a list of numbers, you can do [n for n in range(100) if n%2==0]. So as you can see, list comprehension allows you to combine for loops and if statements in a single line of code.

This exercise is part of the course

Machine Translation with Keras

View Course

Exercise instructions

  • Get the word IDs for the onehot encoded vectors in the treasure_map.
  • Get the batch size (the very first dimension) of the treasure map and use that to create a for loop.
  • Get the words of the i-th sentence by iterating the i-th row of the word_ids while ignoring word IDs equal to zero.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Get the word IDs from the treasure map
word_ids = np.argmax(____, axis=-1)
# Get the batch size from the treasure map
for i in range(treasure_map.shape[____]):
  	# Get all the words of the i-th sentence using list comprehension
	words = [index2word[____] for wid in word_ids[____] if wid != ____]
	print("Instruction ", i+1, ": ", ' '.join(words))
Edit and Run Code