-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_embeddings.py
69 lines (54 loc) · 2.63 KB
/
model_embeddings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2019-20: Homework 5
model_embeddings.py: Embeddings for the NMT model
Pencheng Yin <[email protected]>
Sahil Chopra <[email protected]>
Anand Dhoot <[email protected]>
Michael Hahn <[email protected]>
"""
import torch.nn as nn
# Do not change these imports; your module names should be
# `CNN` in the file `cnn.py`
# `Highway` in the file `highway.py`
# Uncomment the following two imports once you're ready to run part 1(j)
from cnn import CNN
from highway import Highway
# End "do not change"
class ModelEmbeddings(nn.Module):
"""
Class that converts input words to their CNN-based embeddings.
"""
def __init__(self, word_embed_size, vocab):
"""
Init the Embedding layer for one language
@param word_embed_size (int): Embedding size (dimensionality) for the output word
@param vocab (VocabEntry): VocabEntry object. See vocab.py for documentation.
Hints: - You may find len(self.vocab.char2id) useful when create the embedding
"""
super(ModelEmbeddings, self).__init__()
self.word_embed_size = word_embed_size
self.char_embed_size = 50
self.max_word_len = 21
self.dropout_p = 0.3
self.ch_emb = nn.Embedding(len(vocab.char2id), self.char_embed_size, padding_idx=vocab.char_pad)
self.cnn = CNN(self.char_embed_size, self.word_embed_size, self.max_word_len)
self.hw = Highway(self.word_embed_size)
self.dropout = nn.Dropout(self.dropout_p)
def forward(self, input):
"""
Looks up character-based CNN embeddings for the words in a batch of sentences.
@param input: Tensor of integers of shape (sentence_length, batch_size, max_word_length) where
each integer is an index into the character vocabulary
@param output: Tensor of shape (sentence_length, batch_size, word_embed_size), containing the
CNN-based embeddings for each word of the sentences in the batch
"""
X_emb = self.ch_emb(input) # Tensor: (max_sentence_length, batch_size, max_word_length, char_embed_size)
X_emb_reshaped = X_emb.reshape(X_emb.size(0) * X_emb.size(1), X_emb.size(2), X_emb.size(3)) # Tensor: (max_sentence_length*batch_size, max_word_length, char_embed_size)
X_emb_reshaped = X_emb_reshaped.permute(0,2,1) # Tensor: (max_sentence_length*batch_size, char_embed_size, max_word_length)
X_convout = self.cnn(X_emb_reshaped)
X_hw = self.hw(X_convout)
output = self.dropout(X_hw)
output = output.reshape(input.size(0), input.size(1), X_convout.size(1))
return output