def build_embedding_matrix(dataset):
    """Load or build Glove embedding matrix."""
    embed_filename = 'dataset/glove_embedding_300d_{}.pt'.format(dataset)
    if os.path.exists(embed_filename):
        print('Loading embedding:', embed_filename)
        embedding_matrix = torch.load(embed_filename)
    else:
        print('Loading Glove word vectors...')
        word2idx_dict, _ = load_dict(dataset)
        embedding_matrix = np.random.random((len(word2idx_dict) + 2, 300))  # 2 for padding token and start token
        fname = '../glove.42B.300d.txt'  # Glove file
        # fname = '../GoogleNews-vectors-negative300.bin' # Google Word2Vec file
        word2vec_dict = load_word_vec(fname, word2idx_dict=word2idx_dict, type='glove')
        print('Building embedding matrix:', embed_filename)
        for word, i in word2idx_dict.items():
            if word in word2vec_dict:
                # words not found in embedding index will be randomly initialized.
                embedding_matrix[int(i)] = word2vec_dict[word]
        embedding_matrix = torch.FloatTensor(embedding_matrix)
        torch.save(embedding_matrix, embed_filename)
    return embedding_matrix
Load or build Glove embedding matrix.
utils/text_process.py