File size: 3,100 Bytes
6cdb7dc
21cb70f
1d945b4
2c3332f
21cb70f
0095773
2c3332f
52f2d88
21cb70f
2c3332f
21cb70f
e9ddbb1
21cb70f
 
 
e9ddbb1
1d945b4
 
 
21cb70f
1d945b4
 
 
 
 
 
 
e9ddbb1
1d945b4
 
 
 
 
 
880db5d
1d945b4
880db5d
0095773
 
1d945b4
 
 
 
21cb70f
1d945b4
 
 
 
 
 
21cb70f
1d945b4
0095773
52f2d88
0095773
 
 
 
2c3332f
 
 
 
 
 
 
1d945b4
 
21cb70f
2c3332f
 
 
 
 
 
0095773
 
21cb70f
e9ddbb1
 
1d945b4
880db5d
e9ddbb1
21cb70f
52f2d88
 
 
 
 
 
21cb70f
 
 
1d945b4
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
"""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)