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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| import numpy as np import torch from torch import nn, optim import random from collections import Counter import matplotlib.pyplot as plt
with open('/content/text8') as f: text = f.read()
EMBEDDING_DIM = 2 PRINT_EVERY = 1000 EPOCHS = 3 BATCH_SIZE = 5 N_SAMPLES = 3 WINDOW_SIZE = 5 FREQ = 0 DELETE_WORDS = False
def preprocess(text, FREQ): text = text.lower() words = text.split() word_counts = Counter(words) trimmed_words = [word for word in words if word_counts[word] > FREQ] return trimmed_words words = preprocess(text, FREQ)
vocab = set(words) vocab2int = {w: c for c, w in enumerate(vocab)} int2vocab = {c: w for c, w in enumerate(vocab)}
int_words = [vocab2int[w] for w in words]
int_word_counts = Counter(int_words) total_count = len(int_words) word_freqs = {w: c/total_count for w, c in int_word_counts.items()}
if DELETE_WORDS: t = 1e-5 prob_drop = {w: 1-np.sqrt(t/word_freqs[w]) for w in int_word_counts} train_words = [w for w in int_words if random.random()<(1-prob_drop[w])] else: train_words = int_words
word_freqs = np.array(list(word_freqs.values())) unigram_dist = word_freqs / word_freqs.sum() noise_dist = torch.from_numpy(unigram_dist ** (0.75) / np.sum(unigram_dist ** (0.75)))
def get_target(words, idx, WINDOW_SIZE): target_window = np.random.randint(1, WINDOW_SIZE+1) start_point = idx-target_window if (idx-target_window)>0 else 0 end_point = idx+target_window targets = set(words[start_point:idx]+words[idx+1:end_point+1]) return list(targets)
def get_batch(words, BATCH_SIZE, WINDOW_SIZE): n_batches = len(words)//BATCH_SIZE words = words[:n_batches*BATCH_SIZE] for idx in range(0, len(words), BATCH_SIZE): batch_x, batch_y = [],[] batch = words[idx:idx+BATCH_SIZE] for i in range(len(batch)): x = batch[i] y = get_target(batch, i, WINDOW_SIZE) batch_x.extend([x]*len(y)) batch_y.extend(y) yield batch_x, batch_y
class SkipGramNeg(nn.Module): def __init__(self, n_vocab, n_embed, noise_dist): super().__init__() self.n_vocab = n_vocab self.n_embed = n_embed self.noise_dist = noise_dist self.in_embed = nn.Embedding(n_vocab, n_embed) self.out_embed = nn.Embedding(n_vocab, n_embed) self.in_embed.weight.data.uniform_(-1, 1) self.out_embed.weight.data.uniform_(-1, 1) def forward_input(self, input_words): input_vectors = self.in_embed(input_words) return input_vectors def forward_output(self, output_words): output_vectors = self.out_embed(output_words) return output_vectors def forward_noise(self, size, N_SAMPLES): noise_dist = self.noise_dist noise_words = torch.multinomial(noise_dist, size * N_SAMPLES, replacement=True) noise_vectors = self.out_embed(noise_words).view(size, N_SAMPLES, self.n_embed) return noise_vectors
class NegativeSamplingLoss(nn.Module): def __init__(self): super().__init__()
def forward(self, input_vectors, output_vectors, noise_vectors): BATCH_SIZE, embed_size = input_vectors.shape input_vectors = input_vectors.view(BATCH_SIZE, embed_size, 1) output_vectors = output_vectors.view(BATCH_SIZE, 1, embed_size) test = torch.bmm(output_vectors, input_vectors) out_loss = torch.bmm(output_vectors, input_vectors).sigmoid().log() out_loss = out_loss.squeeze() noise_loss = torch.bmm(noise_vectors.neg(), input_vectors).sigmoid().log() noise_loss = noise_loss.squeeze().sum(1) return -(out_loss + noise_loss).mean()
model = SkipGramNeg(len(vocab2int), EMBEDDING_DIM, noise_dist=noise_dist) criterion = NegativeSamplingLoss() optimizer = optim.Adam(model.parameters(), lr=0.003)
steps = 0 for e in range(EPOCHS): for input_words, target_words in get_batch(train_words, BATCH_SIZE, WINDOW_SIZE): steps += 1 inputs, targets = torch.LongTensor(input_words), torch.LongTensor(target_words) input_vectors = model.forward_input(inputs) output_vectors = model.forward_output(targets) size, _ = input_vectors.shape noise_vectors = model.forward_noise(size, N_SAMPLES) loss = criterion(input_vectors, output_vectors, noise_vectors) if steps%PRINT_EVERY == 0: print("loss:",loss) optimizer.zero_grad() loss.backward() optimizer.step()
for i, w in int2vocab.items() : vectors = model.state_dict()["in_embed.weight"] x,y = float(vectors[i][0]),float(vectors[i][1]) plt.scatter(x,y) plt.annotate(w, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom') plt.show()
|