-
Notifications
You must be signed in to change notification settings - Fork 93
/
text_tfidf_model.py
94 lines (85 loc) · 3.55 KB
/
text_tfidf_model.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
"""Text classification / regression model using TFIDF"""
import random
import numpy as np
import scipy as sp
import datatable as dt
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LinearRegression, LogisticRegression
from h2oaicore.models import CustomModel
from h2oaicore.transformer_utils import CustomTransformer
class TextTFIDFModel(CustomModel):
"""Text classification / regression model using TFIDF"""
_regression = True
_binary = True
_multiclass = True
_can_handle_non_numeric = True
_can_handle_text = True
_testing_can_skip_failure = False # ensure tested as if shouldn't fail
_included_transformers = ["TextOriginalTransformer"]
def set_default_params(self, accuracy=None, time_tolerance=None,
interpretability=None, **kwargs):
self.params = dict(max_features=kwargs.get("max_features", None),
ngram_range=kwargs.get("ngram_range", (1, 1)))
def mutate_params(self, accuracy=None, time_tolerance=None, interpretability=None, **kwargs):
self.params["max_features"] = np.random.choice([50000, 100000, None])
self.params["ngram_range"] = random.choice([(1, 1), (1, 2), (1, 3)])
def fit(self, X, y, sample_weight=None, eval_set=None, sample_weight_eval_set=None, **kwargs):
orig_cols = list(X.names)
text_names = X[:, [str]].names
if self.num_classes >= 2:
lb = LabelEncoder()
lb.fit(self.labels)
y = lb.transform(y)
# somehow seeing: solver lbfgs supports only \\'l2\\' or \\'none\\' penalties, got l1 penalty.
model = LogisticRegression(random_state=2019, solver='lbfgs', penalty='l2')
else:
model = LinearRegression()
self.tfidf_objs = {}
new_X = None
for col in text_names:
XX = X[:, col].to_pandas()
XX = XX[col].astype(str).fillna("NA").values.tolist()
tfidf_vec = TfidfVectorizer(**self.params)
try:
XX = tfidf_vec.fit_transform(XX)
except ValueError as e:
if 'vocab' in str(e):
# skip non-text-like column
continue
else:
raise
self.tfidf_objs[col] = tfidf_vec
if new_X is None:
new_X = XX
else:
new_X = sp.sparse.hstack([new_X, XX])
model.fit(new_X, y)
model = (model, self.tfidf_objs)
self.tfidf_objs = {}
importances = [1] * len(orig_cols)
self.set_model_properties(model=model,
features=orig_cols,
importances=importances,
iterations=0)
def predict(self, X, **kwargs):
(model, tfidf_objs), _, _, _ = self.get_model_properties()
X = dt.Frame(X)
new_X = None
text_names = X[:, [str]].names
for col in text_names:
if col not in tfidf_objs:
continue
XX = X[:, col].to_pandas()
XX = XX[col].astype(str).fillna("NA").values.tolist()
tfidf_vec = tfidf_objs[col]
XX = tfidf_vec.transform(XX)
if new_X is None:
new_X = XX
else:
new_X = sp.sparse.hstack([new_X, XX])
if self.num_classes == 1:
preds = model.predict(new_X)
else:
preds = model.predict_proba(new_X)
return preds