(savedir)
| 82 | |
| 83 | |
| 84 | def train_model(savedir): |
| 85 | # get the data |
| 86 | sentences, word2idx = get_wiki() #get_brown() |
| 87 | |
| 88 | |
| 89 | # number of unique words |
| 90 | vocab_size = len(word2idx) |
| 91 | |
| 92 | |
| 93 | # config |
| 94 | window_size = 5 |
| 95 | learning_rate = 0.025 |
| 96 | final_learning_rate = 0.0001 |
| 97 | num_negatives = 5 # number of negative samples to draw per input word |
| 98 | epochs = 20 |
| 99 | D = 50 # word embedding size |
| 100 | |
| 101 | |
| 102 | # learning rate decay |
| 103 | learning_rate_delta = (learning_rate - final_learning_rate) / epochs |
| 104 | |
| 105 | |
| 106 | # params |
| 107 | W = np.random.randn(vocab_size, D) # input-to-hidden |
| 108 | V = np.random.randn(D, vocab_size) # hidden-to-output |
| 109 | |
| 110 | |
| 111 | # distribution for drawing negative samples |
| 112 | p_neg = get_negative_sampling_distribution(sentences, vocab_size) |
| 113 | |
| 114 | |
| 115 | # save the costs to plot them per iteration |
| 116 | costs = [] |
| 117 | |
| 118 | |
| 119 | # number of total words in corpus |
| 120 | total_words = sum(len(sentence) for sentence in sentences) |
| 121 | print("total number of words in corpus:", total_words) |
| 122 | |
| 123 | # for subsampling each sentence |
| 124 | threshold = 1e-5 |
| 125 | p_drop = 1 - np.sqrt(threshold / p_neg) |
| 126 | |
| 127 | |
| 128 | # train the model |
| 129 | for epoch in range(epochs): |
| 130 | # randomly order sentences so we don't always see |
| 131 | # sentences in the same order |
| 132 | np.random.shuffle(sentences) |
| 133 | |
| 134 | # accumulate the cost |
| 135 | cost = 0 |
| 136 | counter = 0 |
| 137 | t0 = datetime.now() |
| 138 | for sentence in sentences: |
| 139 | # keep only certain words based on p_neg |
| 140 | sentence = [w for w in sentence \ |
| 141 | if np.random.random() < (1 - p_drop[w]) |
no test coverage detected