Spaces:
Sleeping
Sleeping
File size: 5,468 Bytes
667fe9d a092d54 7ce074d 85ac990 a092d54 667fe9d a092d54 667fe9d a092d54 667fe9d a092d54 85ac990 a092d54 85ac990 7ce074d 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 667fe9d 85ac990 a092d54 667fe9d 85ac990 a092d54 85ac990 a092d54 667fe9d 85ac990 204391c 667fe9d 85ac990 667fe9d 85ac990 204391c 667fe9d 85ac990 667fe9d a092d54 204391c a092d54 204391c 0ca5366 667fe9d 85ac990 204391c 667fe9d 85ac990 a092d54 85ac990 a092d54 85ac990 a092d54 85ac990 667fe9d a092d54 667fe9d 85ac990 a092d54 667fe9d a092d54 5a2db0a a092d54 5a2db0a a092d54 5a2db0a a092d54 5a2db0a |
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 |
from __future__ import annotations
import warnings
import numpy as np
import spacy
from joblib import Memory
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from tqdm import tqdm
from app.constants import CACHE_DIR
__all__ = ["create_model", "train_model", "evaluate_model"]
try:
nlp = spacy.load("en_core_web_sm", disable=["tok2vec", "parser", "ner"])
except OSError:
print("Downloading spaCy model...")
from spacy.cli import download as spacy_download
spacy_download("en_core_web_sm")
nlp = spacy.load("en_core_web_sm", disable=["tok2vec", "parser", "ner"])
class TextTokenizer(BaseEstimator, TransformerMixin):
def __init__(
self,
*,
character_threshold: int = 2,
batch_size: int = 1024,
n_jobs: int = 8,
progress: bool = True,
) -> None:
self.character_threshold = character_threshold
self.batch_size = batch_size
self.n_jobs = n_jobs
self.progress = progress
def fit(self, _data: list[str], _labels: list[int] | None = None) -> TextTokenizer:
return self
def transform(self, data: list[str]) -> list[list[str]]:
tokenized = []
for doc in tqdm(
nlp.pipe(data, batch_size=self.batch_size, n_process=self.n_jobs),
total=len(data),
disable=not self.progress,
):
tokens = []
for token in doc:
# Ignore stop words and punctuation
if token.is_stop or token.is_punct:
continue
# Ignore emails, URLs and numbers
if token.like_email or token.like_email or token.like_num:
continue
# Lemmatize and lowercase
tok = token.lemma_.lower().strip()
# Format hashtags
if tok.startswith("#"):
tok = tok[1:]
# Ignore short and non-alphanumeric tokens
if len(tok) < self.character_threshold or not tok.isalnum():
continue
# TODO: Emoticons and emojis
# TODO: Spelling correction
tokens.append(tok)
tokenized.append(tokens)
return tokenized
def identity(x: list[str]) -> list[str]:
"""Identity function for use in TfidfVectorizer.
Args:
x: Input data
Returns:
Unchanged input data
"""
return x
def create_model(
max_features: int,
seed: int | None = None,
verbose: bool = False,
) -> Pipeline:
"""Create a sentiment analysis model.
Args:
max_features: Maximum number of features
seed: Random seed (None for random seed)
verbose: Whether to log progress during training
Returns:
Untrained model
"""
return Pipeline(
[
("tokenizer", TextTokenizer(progress=True)),
(
"vectorizer",
TfidfVectorizer(
max_features=max_features,
ngram_range=(1, 2),
# disable text processing
tokenizer=identity,
preprocessor=identity,
lowercase=False,
token_pattern=None,
),
),
("classifier", LogisticRegression(max_iter=1000, random_state=seed)),
],
memory=Memory(CACHE_DIR, verbose=0),
verbose=verbose,
)
def train_model(
model: BaseEstimator,
text_data: list[str],
label_data: list[int],
seed: int = 42,
) -> tuple[BaseEstimator, float]:
"""Train the sentiment analysis model.
Args:
model: Untrained model
text_data: Text data
label_data: Label data
seed: Random seed (None for random seed)
Returns:
Trained model and accuracy
"""
text_train, text_test, label_train, label_test = train_test_split(
text_data,
label_data,
test_size=0.2,
random_state=seed,
)
param_distributions = {
"classifier__C": np.logspace(-4, 4, 20),
"classifier__penalty": ["l1", "l2"],
}
search = RandomizedSearchCV(
model,
param_distributions,
n_iter=10,
cv=5,
scoring="accuracy",
random_state=seed,
n_jobs=-1,
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# model.fit(text_train, label_train)
search.fit(text_train, label_train)
best_model = search.best_estimator_
return best_model, best_model.score(text_test, label_test)
def evaluate_model(
model: Pipeline,
text_data: list[str],
label_data: list[int],
folds: int = 5,
) -> tuple[float, float]:
"""Evaluate the model using cross-validation.
Args:
model: Trained model
text_data: Text data
label_data: Label data
folds: Number of cross-validation folds
Returns:
Mean accuracy and standard deviation
"""
scores = cross_val_score(
model,
text_data,
label_data,
cv=folds,
scoring="accuracy",
)
return scores.mean(), scores.std()
|