CONTEXT_SIZE = 2 EMBEDDING_DIM = 10 # We will use Shakespeare Sonnet 2 test_sentence = """When forty winters shall besiege thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery so gazed on now, Will be a totter'd weed of small worth held: Then being asked, where all thy beauty lies, Where all the treasure of thy lusty days; To say, within thine own deep sunken eyes, Were an all-eating shame, and thriftless praise. How much more praise deserv'd thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count, and make my old excuse,' Proving his beauty by succession thine! This were to be new made when thou art old, And see thy blood warm when thou feel'st it cold.""".split() # we should tokenize the input, but we will ignore that for now # build a list of tuples. # Each tuple is ([ word_i-CONTEXT_SIZE, ..., word_i-1 ], target word) ngrams = [ ( [test_sentence[i - j - 1] for j in range(CONTEXT_SIZE)], test_sentence[i] ) for i in range(CONTEXT_SIZE, len(test_sentence)) ] # Print the first 3, just so you can see what they look like. print(ngrams[:3]) vocab = set(test_sentence) word_to_ix = {word: i for i, word in enumerate(vocab)} class NGramLanguageModeler([nn.Module](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")): def __init__(self, vocab_size, embedding_dim, context_size): super([NGramLanguageModeler](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module"), self).__init__() self.embeddings = [nn.Embedding](https://docs.pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding "torch.nn.Embedding")(vocab_size, embedding_dim) self.linear1 = [nn.Linear](https://docs.pytorch.org/docs/stable/generated/torch.nn.Linear.html#torch.nn.Linear "torch.nn.Linear")(context_size * embedding_dim, 128) self.linear2 = [nn.Linear](https://docs.pytorch.org/docs/stable/generated/torch.nn.Linear.html#torch.nn.Linear "torch.nn.Linear")(128, vocab_size) def forward(self, inputs): [embeds](https://docs.pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding "torch.nn.Embedding") = self.embeddings(inputs).view((1, -1)) out = [F.relu](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.relu.html#torch.nn.functional.relu "torch.nn.functional.relu")(self.linear1([embeds](https://docs.pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding "torch.nn.Embedding"))) out = self.linear2(out) [log_probs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [F.log_softmax](https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.log_softmax.html#torch.nn.functional.log_softmax "torch.nn.functional.log_softmax")(out, dim=1) return [log_probs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") losses = [] [loss_function](https://docs.pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss "torch.nn.NLLLoss") = [nn.NLLLoss](https://docs.pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss "torch.nn.NLLLoss")() model = [NGramLanguageModeler](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "torch.nn.Module")(len(vocab), EMBEDDING_DIM, CONTEXT_SIZE) [optimizer](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD "torch.optim.SGD") = [optim.SGD](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD "torch.optim.SGD")([model.parameters](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.parameters "torch.nn.Module.parameters")(), lr=0.001) for epoch in range(10): total_loss = 0 for context, target in ngrams: # Step 1. Prepare the inputs to be passed to the model (i.e, turn the words # into integer indices and wrap them in tensors) [context_idxs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [torch.tensor](https://docs.pytorch.org/docs/stable/generated/torch.tensor.html#torch.tensor "torch.tensor")([word_to_ix[w] for w in context], dtype=[torch.long](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "torch.dtype")) # Step 2. Recall that torch *accumulates* gradients. Before passing in a # new instance, you need to zero out the gradients from the old # instance [model.zero_grad](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.zero_grad "torch.nn.Module.zero_grad")() # Step 3. Run the forward pass, getting log probabilities over next # words [log_probs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = model([context_idxs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor")) # Step 4. Compute your loss function. (Again, Torch wants the target # word wrapped in a tensor) [loss](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor") = [loss_function](https://docs.pytorch.org/docs/stable/generated/torch.nn.NLLLoss.html#torch.nn.NLLLoss "torch.nn.NLLLoss")([log_probs](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor"), [torch.tensor](https://docs.pytorch.org/docs/stable/generated/torch.tensor.html#torch.tensor "torch.tensor")([word_to_ix[target]], dtype=[torch.long](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "torch.dtype"))) # Step 5. Do the backward pass and update the gradient [loss.backward](https://docs.pytorch.org/docs/stable/generated/torch.Tensor.backward.html#torch.Tensor.backward "torch.Tensor.backward")() [optimizer.step](https://docs.pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD.step "torch.optim.SGD.step")() # Get the Python number from a 1-element Tensor by calling tensor.item() total_loss += [loss](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "torch.Tensor").item() losses.append(total_loss) print(losses) # The loss decreased every iteration over the training data! # To get the embedding of a particular word, e.g. "beauty" print([model.embeddings.weight](https://docs.pytorch.org/docs/stable/generated/torch.nn.parameter.Parameter.html#torch.nn.parameter.Parameter "torch.nn.parameter.Parameter")[word_to_ix["beauty"]])