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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
VECTORIZER_DIRECTORY = Path(__file__).resolve().parent / "vectorizers"
|
| 13 |
+
DIMENSIONS = {
|
| 14 |
+
"essays": ("O", "C", "E", "A", "N"),
|
| 15 |
+
"mbti": ("O", "C", "E", "A"),
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CustomNetwork(nn.Module):
|
| 20 |
+
def __init__(self, input_size):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.fc1 = nn.Linear(input_size, 5)
|
| 23 |
+
self.fc2 = nn.Linear(5, 5)
|
| 24 |
+
self.fc3 = nn.Linear(5, 1)
|
| 25 |
+
|
| 26 |
+
def forward(self, inputs):
|
| 27 |
+
inputs = torch.relu(self.fc1(inputs))
|
| 28 |
+
inputs = torch.relu(self.fc2(inputs))
|
| 29 |
+
return torch.sigmoid(self.fc3(inputs))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def clean_text(text):
|
| 33 |
+
text = text.lower()
|
| 34 |
+
text = re.sub(r'https?://[^\s<>"]+|www\.[^\s<>"]+', " ", text)
|
| 35 |
+
return re.sub("[^0-9a-z]", " ", text)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _lemmatize(text):
|
| 39 |
+
try:
|
| 40 |
+
from nltk.stem import WordNetLemmatizer
|
| 41 |
+
except ImportError as error:
|
| 42 |
+
raise RuntimeError(
|
| 43 |
+
"NLTK is required for text prediction. Install it with "
|
| 44 |
+
"`pip install nltk==3.8.1`."
|
| 45 |
+
) from error
|
| 46 |
+
|
| 47 |
+
lemmatizer = WordNetLemmatizer()
|
| 48 |
+
try:
|
| 49 |
+
return [
|
| 50 |
+
lemmatizer.lemmatize(word)
|
| 51 |
+
for word in text.split()
|
| 52 |
+
if len(word) > 2
|
| 53 |
+
]
|
| 54 |
+
except LookupError as error:
|
| 55 |
+
raise RuntimeError(
|
| 56 |
+
"NLTK WordNet data is missing. Run "
|
| 57 |
+
"`python -m nltk.downloader wordnet omw-1.4`."
|
| 58 |
+
) from error
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def raw_corpus(dataset):
|
| 62 |
+
if dataset == "essays":
|
| 63 |
+
dataframe = pd.read_csv(
|
| 64 |
+
REPOSITORY_ROOT / "dataset/raw/essays.csv",
|
| 65 |
+
encoding="iso-8859-1",
|
| 66 |
+
)
|
| 67 |
+
return dataframe["TEXT"].astype(str).tolist()
|
| 68 |
+
if dataset == "mbti":
|
| 69 |
+
dataframe = pd.read_csv(REPOSITORY_ROOT / "dataset/raw/mbti.csv")
|
| 70 |
+
return dataframe["posts"].astype(str).tolist()
|
| 71 |
+
raise ValueError(f"Unsupported dataset: {dataset}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def load_vectorizer(dataset):
|
| 75 |
+
path = VECTORIZER_DIRECTORY / f"{dataset}_tfidf.npz"
|
| 76 |
+
if not path.is_file():
|
| 77 |
+
raise FileNotFoundError(
|
| 78 |
+
f"Missing vectorizer artifact: {path}. Run "
|
| 79 |
+
"`/usr/bin/python3 model_training/export_vectorizer.py "
|
| 80 |
+
f"{dataset}` using the preprocessing environment."
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
with np.load(path) as artifact:
|
| 84 |
+
terms = artifact["terms"].tolist()
|
| 85 |
+
idf = artifact["idf"].astype(np.float32)
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
"terms": terms,
|
| 89 |
+
"vocabulary": {term: index for index, term in enumerate(terms)},
|
| 90 |
+
"idf": idf,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def verify_vectorizer(vectorizer, dataframe, samples=5):
|
| 95 |
+
raw_texts = raw_corpus_from_rows(dataframe)
|
| 96 |
+
vectorizer_bundle = {
|
| 97 |
+
"input_size": len(vectorizer["terms"]),
|
| 98 |
+
"vocabulary": vectorizer["vocabulary"],
|
| 99 |
+
"idf": vectorizer["idf"],
|
| 100 |
+
}
|
| 101 |
+
actual = np.stack(
|
| 102 |
+
[vectorize_text(text, vectorizer_bundle) for text in raw_texts]
|
| 103 |
+
)
|
| 104 |
+
expected = np.stack(dataframe["text"].iloc[:samples].to_numpy())
|
| 105 |
+
|
| 106 |
+
if not np.allclose(actual, expected, rtol=1e-5, atol=1e-7):
|
| 107 |
+
difference = float(np.max(np.abs(actual - expected)))
|
| 108 |
+
raise RuntimeError(
|
| 109 |
+
"Rebuilt TF-IDF vectors do not match the stored training data "
|
| 110 |
+
f"(maximum absolute difference: {difference:.6g}). Refusing to "
|
| 111 |
+
"save an incompatible deployment artifact."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def raw_corpus_from_rows(dataframe, samples=5):
|
| 116 |
+
dataset = "essays" if "N" in dataframe.columns else "mbti"
|
| 117 |
+
corpus = raw_corpus(dataset)
|
| 118 |
+
return [
|
| 119 |
+
corpus[int(user_id)]
|
| 120 |
+
for user_id in dataframe["user"].iloc[:samples]
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def save_bundle(path, models, vectorizer, config):
|
| 125 |
+
path = Path(path)
|
| 126 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 127 |
+
|
| 128 |
+
bundle = {
|
| 129 |
+
"format_version": 1,
|
| 130 |
+
"dataset": config["dataset"],
|
| 131 |
+
"feature": config["feature"],
|
| 132 |
+
"loss": config["loss"],
|
| 133 |
+
"threshold": 0.5,
|
| 134 |
+
"input_size": len(vectorizer["terms"]),
|
| 135 |
+
"dimensions": list(models),
|
| 136 |
+
"vocabulary": vectorizer["vocabulary"],
|
| 137 |
+
"idf": vectorizer["idf"],
|
| 138 |
+
"models": {
|
| 139 |
+
dimension: {
|
| 140 |
+
key: value.detach().cpu()
|
| 141 |
+
for key, value in model.network.state_dict().items()
|
| 142 |
+
}
|
| 143 |
+
for dimension, model in models.items()
|
| 144 |
+
},
|
| 145 |
+
"metrics": {
|
| 146 |
+
dimension: {
|
| 147 |
+
"epoch": model.epoch,
|
| 148 |
+
"balanced_accuracy": model.ba,
|
| 149 |
+
"regular_accuracy": model.ra,
|
| 150 |
+
}
|
| 151 |
+
for dimension, model in models.items()
|
| 152 |
+
},
|
| 153 |
+
}
|
| 154 |
+
torch.save(bundle, path)
|
| 155 |
+
return path
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_bundle(path):
|
| 159 |
+
bundle = torch.load(Path(path), map_location="cpu")
|
| 160 |
+
required = {
|
| 161 |
+
"format_version",
|
| 162 |
+
"input_size",
|
| 163 |
+
"dimensions",
|
| 164 |
+
"vocabulary",
|
| 165 |
+
"idf",
|
| 166 |
+
"models",
|
| 167 |
+
}
|
| 168 |
+
missing = required.difference(bundle)
|
| 169 |
+
if missing:
|
| 170 |
+
raise ValueError(f"Invalid model bundle; missing: {sorted(missing)}")
|
| 171 |
+
return bundle
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def vectorize_text(text, bundle):
|
| 175 |
+
vocabulary = bundle["vocabulary"]
|
| 176 |
+
# The notebook fitted vocabulary on cleaned text, but transformed the
|
| 177 |
+
# already-created splits from raw text. Preserve that training behavior.
|
| 178 |
+
counts = Counter(_lemmatize(text.lower()))
|
| 179 |
+
features = np.zeros(bundle["input_size"], dtype=np.float32)
|
| 180 |
+
|
| 181 |
+
for token, count in counts.items():
|
| 182 |
+
index = vocabulary.get(token)
|
| 183 |
+
if index is not None:
|
| 184 |
+
features[index] = count
|
| 185 |
+
|
| 186 |
+
features *= np.asarray(bundle["idf"], dtype=np.float32)
|
| 187 |
+
norm = np.linalg.norm(features)
|
| 188 |
+
if norm:
|
| 189 |
+
features /= norm
|
| 190 |
+
return features
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def load_networks(bundle):
|
| 194 |
+
networks = {}
|
| 195 |
+
for dimension in bundle["dimensions"]:
|
| 196 |
+
network = CustomNetwork(bundle["input_size"])
|
| 197 |
+
network.load_state_dict(bundle["models"][dimension])
|
| 198 |
+
network.eval()
|
| 199 |
+
networks[dimension] = network
|
| 200 |
+
return networks
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def predict_text(text, bundle, networks=None):
|
| 204 |
+
features = torch.from_numpy(vectorize_text(text, bundle)).unsqueeze(0)
|
| 205 |
+
threshold = float(bundle.get("threshold", 0.5))
|
| 206 |
+
predictions = {}
|
| 207 |
+
networks = networks or load_networks(bundle)
|
| 208 |
+
|
| 209 |
+
with torch.no_grad():
|
| 210 |
+
for dimension, network in networks.items():
|
| 211 |
+
probability = float(network(features).item())
|
| 212 |
+
predictions[dimension] = {
|
| 213 |
+
"probability": probability,
|
| 214 |
+
"prediction": int(probability >= threshold),
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
return predictions
|