-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
209 lines (162 loc) · 6.18 KB
/
utils.py
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import os
import string
import random
import numpy as np
from sklearn.metrics import accuracy_score
from tqdm.notebook import tqdm
from sklearn.base import TransformerMixin
from sklearn.naive_bayes import GaussianNB, CategoricalNB
import nltk
from nltk import word_tokenize, WordNetLemmatizer
from nltk.stem import WordNetLemmatizer
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
wordnet_lemmatizer: WordNetLemmatizer = WordNetLemmatizer()
def clean_text(text: str) -> str:
# removes upper cases
text = text.lower()
# removes punctuation
for char in string.punctuation:
text = text.replace(char, "")
# lemmatize the words and join back into string text
text = " ".join([wordnet_lemmatizer.lemmatize(word) for word in word_tokenize(text)])
return text
class DenseTransformer(TransformerMixin):
def fit(self, x, y=None, **fit_params):
return self
@staticmethod
def transform(x, y=None, **fit_params):
return x.todense()
def __str__(self):
return "DenseTransformer()"
def __repr__(self):
return self.__str__()
class CleanTextTransformer(TransformerMixin):
def fit(self, x, y=None, **fit_params):
return self
@staticmethod
def transform(x, y=None, **fit_params):
return np.vectorize(clean_text)(x)
def __str__(self):
return 'CleanTextTransformer()'
def __repr__(self):
return self.__str__()
def load_imdb_sentiment_analysis_dataset(imdb_data_path, seed=123):
"""Loads the IMDb movie reviews sentiment analysis dataset.
# Arguments
data_path: string, path to the data directory.
seed: int, seed for randomizer.
# Returns
A tuple of training and validation data.
Number of training samples: 25000
Number of test samples: 25000
Number of categories: 2 (0 - negative, 1 - positive)
# References
Mass et al., http://www.aclweb.org/anthology/P11-1015
Download and uncompress archive from:
http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
"""
# Load the training data
train_texts = []
train_labels = []
for category in ['pos', 'neg']:
print(f"loading train: {category} ...")
train_path = os.path.join(imdb_data_path, 'train', category)
for fname in tqdm(sorted(os.listdir(train_path))):
if fname.endswith('.txt'):
with open(os.path.join(train_path, fname), encoding="utf-8") as f:
train_texts.append(f.read())
train_labels.append(0 if category == 'neg' else 1)
# Load the validation data.
test_texts = []
test_labels = []
for category in ['pos', 'neg']:
print(f"loading test: {category} ...")
test_path = os.path.join(imdb_data_path, 'test', category)
for fname in tqdm(sorted(os.listdir(test_path))):
if fname.endswith('.txt'):
with open(os.path.join(test_path, fname), encoding="utf-8") as f:
test_texts.append(f.read())
test_labels.append(0 if category == 'neg' else 1)
# Shuffle the training data and labels.
random.seed(seed)
random.shuffle(train_texts)
random.seed(seed)
random.shuffle(train_labels)
return ((np.array(train_texts), np.array(train_labels)),
(np.array(test_texts), np.array(test_labels)))
class CategoricalBatchNB(TransformerMixin):
def __init__(self, batch_size, classes, *args, **kwargs):
self._batch_size = batch_size
self._classes = classes
self._args = args
self._kwargs = kwargs
self._model = CategoricalNB(*args, **kwargs)
def fit(self, x, y, **fit_params):
batch_size = self._batch_size
self._model = CategoricalNB(*self._args, **self._kwargs)
for index in tqdm(range(batch_size, x.shape[0] + batch_size, batch_size)):
self._model.partial_fit(
x[index - batch_size:index, :].toarray(),
y[index - batch_size:index],
classes=self._classes
)
return self
@staticmethod
def transform(x, y=None, **fit_params):
return x
def predict(self, x):
batch_size = self._batch_size
predictions = []
for index in tqdm(range(batch_size, x.shape[0] + batch_size, batch_size)):
predictions.extend(
self._model.predict(
x[index - batch_size:index, :].toarray()
).tolist()
)
return np.array(predictions).ravel()
def score(self, x, y):
y_pred = self.predict(x)
return accuracy_score(y, y_pred)
def __str__(self):
return "CategoricalBatchNB()"
def __repr__(self):
return self.__str__()
class GaussianBatchNB(TransformerMixin):
def __init__(self, batch_size, classes, *args, **kwargs):
self._batch_size = batch_size
self._classes = classes
self._args = args
self._kwargs = kwargs
self._model = GaussianNB(*args, **kwargs)
def fit(self, x, y, **fit_params):
batch_size = self._batch_size
self._model = GaussianNB(*self._args, **self._kwargs)
for index in tqdm(range(batch_size, x.shape[0]+batch_size, batch_size)):
self._model.partial_fit(
x[index-batch_size:index, :].toarray(),
y[index-batch_size:index],
classes=self._classes
)
return self
@staticmethod
def transform(x, y=None, **fit_params):
return x
def predict(self, x):
batch_size = self._batch_size
predictions = []
for index in tqdm(range(batch_size, x.shape[0]+batch_size, batch_size)):
predictions.extend(
self._model.predict(
x[index-batch_size:index, :].toarray()
).tolist()
)
return np.array(predictions).ravel()
def score(self, x, y):
y_pred = self.predict(x)
return accuracy_score(y, y_pred)
def __str__(self):
return "GaussianBatchNB()"
def __repr__(self):
return self .__str__()