1
|
|
|
""" |
2
|
|
|
Word2Vec Embedding |
3
|
|
|
|
4
|
|
|
.................................................................................................... |
5
|
|
|
MIT License |
6
|
|
|
Copyright (c) 2021-2023 AUT Iran, Mohammad H Forouhesh |
7
|
|
|
Copyright (c) 2021-2022 MetoData.ai, Mohammad H Forouhesh |
8
|
|
|
.................................................................................................... |
9
|
|
|
This module encapsulate the Word2Vec embedding of a given corpus. |
10
|
|
|
""" |
11
|
|
|
|
12
|
1 |
|
import pickle |
13
|
1 |
|
import gensim |
14
|
1 |
|
import numpy as np |
15
|
1 |
|
import pandas as pd |
16
|
1 |
|
from typing import List, Generator |
|
|
|
|
17
|
|
|
|
18
|
1 |
|
from gensim import utils |
19
|
1 |
|
from sklearn.pipeline import Pipeline |
20
|
1 |
|
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer |
21
|
1 |
|
from .w2v_corpus import W2VCorpus |
22
|
|
|
|
23
|
|
|
|
24
|
1 |
View Code Duplication |
class W2VEmb: |
|
|
|
|
25
|
1 |
|
def __init__(self, text_document=None): |
26
|
1 |
|
self.wv2_corpus = None |
27
|
1 |
|
self.w2v_model = None |
28
|
1 |
|
self.tf_idf_transformation = None |
29
|
1 |
|
if text_document is not None: self.__init(text_document) |
|
|
|
|
30
|
|
|
|
31
|
1 |
|
def __init(self, text_document: pd.Series) -> None: |
32
|
|
|
""" |
33
|
|
|
Constructor |
34
|
|
|
:param text_document: text corpus |
35
|
|
|
:return: None |
36
|
|
|
""" |
37
|
|
|
text_document = text_document.fillna('') |
38
|
|
|
self.tf_idf_transformation = self.tf_idf_transformer(text_document) |
39
|
|
|
self.wv2_corpus = W2VCorpus(text_document) |
40
|
|
|
self.w2v_model = gensim.models.Word2Vec(sentences=self.wv2_corpus, min_count=1, vector_size=900, epochs=50) |
|
|
|
|
41
|
|
|
|
42
|
1 |
|
def __getitem__(self, text: str) -> np.ndarray: |
43
|
|
|
""" |
44
|
|
|
getitem overwrite to get word embedding for a given text. |
45
|
|
|
:param text: Input text. |
46
|
|
|
:return: A numpy array of embedding array. |
47
|
|
|
""" |
48
|
1 |
|
try: return self.w2v_model.wv[text] |
|
|
|
|
49
|
1 |
|
except KeyError: return np.array([0 for _ in range(0, self.w2v_model.vector_size)]) |
|
|
|
|
50
|
|
|
|
51
|
1 |
|
def tf_idf_transformer(self, text_series): |
|
|
|
|
52
|
|
|
""" |
53
|
|
|
TF-IDF transformer for weighting words |
54
|
|
|
:param text_series: |
55
|
|
|
:return: |
56
|
|
|
""" |
57
|
|
|
tfidf = Pipeline([('count', CountVectorizer(encoding='utf-8', min_df=3, #max_df=0.9, |
58
|
|
|
max_features=900, |
59
|
|
|
ngram_range=(1, 2))), |
60
|
|
|
('tfid', TfidfTransformer(sublinear_tf=True, norm='l2'))]).fit(text_series.ravel()) |
|
|
|
|
61
|
|
|
return tfidf |
62
|
|
|
|
63
|
1 |
|
def encode(self, text: str) -> np.ndarray: |
64
|
|
|
""" |
65
|
|
|
Encoding function |
66
|
|
|
:param text: Input text |
67
|
|
|
:return: A numpy array of embedding array. |
68
|
|
|
""" |
69
|
1 |
|
stream = utils.simple_preprocess(text) |
70
|
1 |
|
tf_idf_vec = self.tf_idf_transformation.transform(stream).toarray() |
71
|
1 |
|
w2v_encode = self[stream] |
72
|
1 |
|
return np.mean(list(self.tf_idf_mean(tf_idf_vec, w2v_encode)), axis=0) |
73
|
|
|
|
74
|
1 |
|
def save(self, path: str) -> None: |
75
|
|
|
""" |
76
|
|
|
A tool to save model w2v to disk |
77
|
|
|
:param path: Saving path. |
78
|
|
|
:return: None. |
79
|
|
|
""" |
80
|
|
|
|
81
|
|
|
with open(path, 'wb') as f: |
|
|
|
|
82
|
|
|
pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL) |
83
|
|
|
|
84
|
1 |
|
def load(self, path: str) -> None: |
85
|
|
|
""" |
86
|
|
|
A tool to load w2v model from disk. |
87
|
|
|
:param path: Model path. |
88
|
|
|
:return: None |
89
|
|
|
""" |
90
|
|
|
|
91
|
1 |
|
with open(path, 'rb') as f: |
|
|
|
|
92
|
1 |
|
self.__dict__.update(pickle.load(f).__dict__) |
93
|
|
|
|
94
|
1 |
|
@staticmethod |
95
|
1 |
|
def tf_idf_mean(tf_idf_vec: np.ndarray, w2v_encode: np.ndarray) -> Generator[List[float], None, None]: |
|
|
|
|
96
|
|
|
""" |
97
|
|
|
Mean pooling to encode sentences using tf-idf weights of words. |
98
|
|
|
:param tf_idf_vec: A tf-idf vector of the sentence |
99
|
|
|
:param w2v_encode: A word2vec vector of the sentence |
100
|
|
|
:return: A generator that yield relative vector of a word with respect to its tf-idf vector. |
|
|
|
|
101
|
|
|
""" |
102
|
|
|
|
103
|
1 |
|
for ind in range(len(tf_idf_vec)): |
|
|
|
|
104
|
|
|
yield tf_idf_vec[ind]*w2v_encode[ind] |
105
|
|
|
|