|
| 1 | +__author__ = 'SherlockLiao' |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn.functional as F |
| 5 | +from torch import nn, optim |
| 6 | +from torch.autograd import Variable |
| 7 | + |
| 8 | +training_data = [("The dog ate the apple".split(), |
| 9 | + ["DET", "NN", "V", "DET", "NN"]), |
| 10 | + ("Everybody read that book".split(), ["NN", "V", "DET", |
| 11 | + "NN"])] |
| 12 | + |
| 13 | +word_to_idx = {} |
| 14 | +tag_to_idx = {} |
| 15 | +for context, tag in training_data: |
| 16 | + for word in context: |
| 17 | + if word not in word_to_idx: |
| 18 | + word_to_idx[word] = len(word_to_idx) |
| 19 | + for label in tag: |
| 20 | + if label not in tag_to_idx: |
| 21 | + tag_to_idx[label] = len(tag_to_idx) |
| 22 | +alphabet = 'abcdefghijklmnopqrstuvwxyz' |
| 23 | +character_to_idx = {} |
| 24 | +for i in range(len(alphabet)): |
| 25 | + character_to_idx[alphabet[i]] = i |
| 26 | + |
| 27 | + |
| 28 | +class CharLSTM(nn.Module): |
| 29 | + def __init__(self, n_char, char_dim, char_hidden): |
| 30 | + super(CharLSTM, self).__init__() |
| 31 | + self.char_embedding = nn.Embedding(n_char, char_dim) |
| 32 | + self.char_lstm = nn.LSTM(char_dim, char_hidden, batch_first=True) |
| 33 | + |
| 34 | + def forward(self, x): |
| 35 | + x = self.char_embedding(x) |
| 36 | + _, h = self.char_lstm(x) |
| 37 | + return h[1] |
| 38 | + |
| 39 | + |
| 40 | +class LSTMTagger(nn.Module): |
| 41 | + def __init__(self, n_word, n_char, char_dim, n_dim, char_hidden, n_hidden, |
| 42 | + n_tag): |
| 43 | + super(LSTMTagger, self).__init__() |
| 44 | + self.word_embedding = nn.Embedding(n_word, n_dim) |
| 45 | + self.char_lstm = CharLSTM(n_char, char_dim, char_hidden) |
| 46 | + self.lstm = nn.LSTM(n_dim + char_hidden, n_hidden, batch_first=True) |
| 47 | + self.linear1 = nn.Linear(n_hidden, n_tag) |
| 48 | + |
| 49 | + def forward(self, x, word): |
| 50 | + char = torch.FloatTensor() |
| 51 | + for each in word: |
| 52 | + char_list = [] |
| 53 | + for letter in each: |
| 54 | + char_list.append(character_to_idx[letter.lower()]) |
| 55 | + char_list = torch.LongTensor(char_list) |
| 56 | + char_list = char_list.unsqueeze(0) |
| 57 | + if torch.cuda.is_available(): |
| 58 | + tempchar = self.char_lstm(Variable(char_list).cuda()) |
| 59 | + else: |
| 60 | + tempchar = self.char_lstm(Variable(char_list)) |
| 61 | + tempchar = tempchar.squeeze(0) |
| 62 | + char = torch.cat((char, tempchar.cpu().data), 0) |
| 63 | + char = char.squeeze(1) |
| 64 | + if torch.cuda.is_available(): |
| 65 | + char = char.cuda() |
| 66 | + char = Variable(char) |
| 67 | + x = self.word_embedding(x) |
| 68 | + x = torch.cat((x, char), 1) |
| 69 | + x = x.unsqueeze(0) |
| 70 | + x, _ = self.lstm(x) |
| 71 | + x = x.squeeze(0) |
| 72 | + x = self.linear1(x) |
| 73 | + y = F.log_softmax(x) |
| 74 | + return y |
| 75 | + |
| 76 | + |
| 77 | +model = LSTMTagger( |
| 78 | + len(word_to_idx), len(character_to_idx), 10, 100, 50, 128, len(tag_to_idx)) |
| 79 | +if torch.cuda.is_available(): |
| 80 | + model = model.cuda() |
| 81 | +criterion = nn.CrossEntropyLoss() |
| 82 | +optimizer = optim.SGD(model.parameters(), lr=1e-2) |
| 83 | + |
| 84 | + |
| 85 | +def make_sequence(x, dic): |
| 86 | + idx = [dic[i] for i in x] |
| 87 | + idx = Variable(torch.LongTensor(idx)) |
| 88 | + return idx |
| 89 | + |
| 90 | + |
| 91 | +for epoch in range(300): |
| 92 | + print('*' * 10) |
| 93 | + print('epoch {}'.format(epoch + 1)) |
| 94 | + running_loss = 0 |
| 95 | + for data in training_data: |
| 96 | + word, tag = data |
| 97 | + word_list = make_sequence(word, word_to_idx) |
| 98 | + tag = make_sequence(tag, tag_to_idx) |
| 99 | + if torch.cuda.is_available(): |
| 100 | + word_list = word_list.cuda() |
| 101 | + tag = tag.cuda() |
| 102 | + # forward |
| 103 | + out = model(word_list, word) |
| 104 | + loss = criterion(out, tag) |
| 105 | + running_loss += loss.data[0] |
| 106 | + # backward |
| 107 | + optimizer.zero_grad() |
| 108 | + loss.backward() |
| 109 | + optimizer.step() |
| 110 | + print('Loss: {}'.format(running_loss / len(data))) |
| 111 | +print() |
| 112 | +input = make_sequence("Everybody ate the apple".split(), word_to_idx) |
| 113 | +if torch.cuda.is_available(): |
| 114 | + input = input.cuda() |
| 115 | + |
| 116 | +out = model(input, "Everybody ate the apple".split()) |
| 117 | +print(out) |
0 commit comments