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 70 71 72 73 74 75 76 77 78 79
| import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim
torch.manual_seed(666)
CONTEXT_SIZE = 2 EMBEDDING_DIM = 10
test_data = """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()
data = [] for i in range(2, len(test_data)-2): context = [test_data[i-2],test_data[i-1], test_data[i+1], test_data[i+2]] target = test_data[i] data.append((context, target))
vocab = set(test_data) word_to_id = {} for id,word in enumerate(vocab): word_to_id[word] = id
VOCAB_SIZE = len(vocab) CONTEXT_SIZE = 2 EMBEDDING_DIM = 10 EPOCHS = 150
class CBOW(nn.Module): def __init__(self, vocab_size, embedding_dim, context_size): super(CBOW, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.linear1 = nn.Linear(embedding_dim,128) self.linear2 = nn.Linear(128, vocab_size)
def forward(self, x): embeds = sum(self.embedding(x)).view(1,-1) t1 = F.relu(self.linear1(embeds)) t2 = self.linear2(t1) out = F.log_softmax(t2,dim = 1) return out
loss_fn = nn.NLLLoss() model = CBOW(VOCAB_SIZE,EMBEDDING_DIM,CONTEXT_SIZE) optimizer = optim.SGD(model.parameters(), lr =0.001)
def train(): model.train() for epoch in range(EPOCHS): total_loss = 0 for context, target in data: model.zero_grad() context_ids = torch.LongTensor([word_to_id[w] for w in context]) target_ids = torch.LongTensor([word_to_id[target]]) log_probs = model(context_ids) loss = loss_fn(log_probs,target_ids) loss.backward() optimizer.step()
total_loss += loss.item() print("epoch=",epoch," loss=",total_loss) train()
|