bagaco3 / classifier /scripts /fit_classifier.py
duarteocarmo
update
880db5d
Raw History Blame Contribute Delete
3.1 kB
"""Train a sparse text classifier."""
import fire
import numpy as numpy
import polars as polars
from sentence_transformers import SentenceTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import StandardScaler
MINIMUM_PER_CATEGORY = 100
RANDOM_STATE = 42
def sample_data(data: polars.DataFrame, sample_size: int) -> polars.DataFrame:
data = data.with_row_index(name="row_index")
category_sample = data.group_by("category").map_groups(
lambda group: group.sample(n=MINIMUM_PER_CATEGORY, seed=RANDOM_STATE)
)
remaining_sample = (
data.join(
category_sample.select("row_index"),
on="row_index",
how="anti",
)
.sample(n=sample_size - category_sample.height, seed=RANDOM_STATE)
)
return polars.concat(items=[category_sample, remaining_sample]).drop("row_index")
def main(
target: str = "educational_score",
data: str = "data/annotated.parquet",
sample_size: int = 36_000,
test_size: float = 0.2,
model: str = "intfloat/multilingual-e5-small",
device: str = "mps",
batch_size: int = 64,
) -> None:
sampled_data = sample_data(
data=polars.read_parquet(source=data),
sample_size=sample_size,
)
texts = [str(text)[:1500] for text in sampled_data.get_column("text")]
labels = sampled_data.get_column(target).to_list()
splitter = StratifiedShuffleSplit(
n_splits=1,
test_size=test_size,
random_state=RANDOM_STATE,
)
train_indices, test_indices = next(splitter.split(X=texts, y=labels))
embeddings = SentenceTransformer(model_name_or_path=model, device=device).encode(
inputs=texts,
batch_size=batch_size,
normalize_embeddings=True,
show_progress_bar=True,
)
text_lengths = numpy.log1p(
numpy.array([len(str(text)) for text in sampled_data.get_column("text")])
).reshape(-1, 1)
length_scaler = StandardScaler().fit(X=text_lengths[train_indices])
embeddings = numpy.column_stack(
tup=(embeddings, length_scaler.transform(X=text_lengths) * 0.1)
)
train_labels = [labels[index] for index in train_indices]
test_labels = [labels[index] for index in test_indices]
classifier = LogisticRegression(
C=1.0,
class_weight="balanced",
max_iter=5_000,
random_state=RANDOM_STATE,
)
classifier.fit(X=embeddings[train_indices], y=train_labels)
predictions = classifier.predict(X=embeddings[test_indices])
print(
classification_report(
y_true=test_labels,
y_pred=predictions,
zero_division="warn",
)
)
matrix = confusion_matrix(
y_true=test_labels,
y_pred=predictions,
labels=classifier.classes_,
)
print(f"Confusion matrix (labels: {classifier.classes_.tolist()}):\n{matrix}")
if __name__ == "__main__":
fire.Fire(component=main)