v9.1.1
Menu

One-Hot Sequence Encoder

easyFREESequence ProcessingNLP 2: Applications

Given a vocabulary and a sequence of words, encode each word as a one-hot vector.

Input:

  • vocab: list of vocabulary words (sorted); a word's index is its position in this list
  • words: list of words to encode

Each word becomes a vector of length |vocab| with 1 at the word's index and 0 elsewhere. If a word is not in the vocabulary, use all zeros.

Output: A list of vectors (one list of 0s and 1s per input word, in the same order as words).

Example

Input
cat,dog,fish
dog cat fish
Output
[0, 1, 0]
[1, 0, 0]
[0, 0, 1]
Reasoning
  • Inputs: vocab is the ordered list cat, dog, fish, so ∣V∣=3|V| = 3 and each word's position is fixed by that order: cat →0\to 0, dog →1\to 1, fish →2\to 2. words is the sequence dog cat fish to encode.
  • The math: a word at vocabulary position ii maps to the standard basis vector ei∈{0,1}∣V∣e_i \in \{0,1\}^{|V|}, whose entry kk is 11 if k=ik = i and 00 otherwise.
  • Worked through: "dog" sits at position 11, giving e1=e_1 = [0, 1, 0]; "cat" at position 00 gives e0=e_0 = [1, 0, 0]; "fish" at position 22 gives e2=e_2 = [0, 0, 1].
  • Output: one vector per input word, in the order the words appear, each of length ∣V∣=3|V| = 3 and summing to exactly 11.
  • Notice that stacking the three rows gives a permutation of the 3×33 \times 3 identity matrix, because each vocabulary word appears once. A repeated word repeats its row, and a word outside the vocabulary has no position, so its vector is all zeros and sums to 00.

Constraints

  • Vocabulary is comma-separated and sorted
  • Each output vector has length = vocabulary size
  • Unknown words get all-zero vectors
  • Output each vector as a Python list

Learn this in

More from NLP 2: Applications

solution.py

Test results

Sign in to run your code against the test cases.