Skip to content

# Train a field of study (domain) classification of sentences on the MAG dataset¶

SciBERT achieves an F1-score of 0.6571 on this dataset. This notebook shows that better results can be achieved without even using transformers.

In [1]:
Copied!

    import json
    from typing import Tuple
    from great_ai.utilities import clean, simple_parallel_map
    from tqdm.cli import tqdm

    def preprocess(line: str) -> Tuple[str, str]:
        data_point = json.loads(line)

        return (clean(data_point["text"], convert_to_ascii=True), data_point["label"])

    with open("../../tutorial/data/train.txt", encoding="utf-8") as f:
        training_data = simple_parallel_map(preprocess, f.readlines())

    X_train = [d[0] for d in training_data]
    y_train = [d[1] for d in training_data]

    with open("../../tutorial/data/test.txt", encoding="utf-8") as f:
        test_data = simple_parallel_map(preprocess, f.readlines())

    X_test = [d[0] for d in test_data]
    y_test = [d[1] for d in test_data]

import json from typing import Tuple from great_ai.utilities import clean, simple_parallel_map from tqdm.cli import tqdm def preprocess(line: str) -> Tuple[str, str]: data_point = json.loads(line) return (clean(data_point["text"], convert_to_ascii=True), data_point["label"]) with open("../../tutorial/data/train.txt", encoding="utf-8") as f: training_data = simple_parallel_map(preprocess, f.readlines()) X_train = [d[0] for d in training_data] y_train = [d[1] for d in training_data] with open("../../tutorial/data/test.txt", encoding="utf-8") as f: test_data = simple_parallel_map(preprocess, f.readlines()) X_test = [d[0] for d in test_data] y_test = [d[1] for d in test_data]

    100%|██████████| 84000/84000 [00:16<00:00, 4964.08it/s]
    100%|██████████| 22399/22399 [00:05<00:00, 3847.04it/s]

In [2]:
Copied!

    from collections import Counter
    import matplotlib.pyplot as plt

    domains, counts = zip(*Counter(y_train).most_common())

    # Configure matplotlib to have nice, high-resolution charts
    %matplotlib inline
    plt.rcParams["figure.facecolor"] = "white"
    plt.rcParams["font.size"] = 18
    plt.rcParams["figure.figsize"] = (8, 5)

    fig, ax = plt.subplots()

    plt.xticks(rotation=90)
    ax.bar(domains, counts)
    ax.set_ylabel("Count")
    fig.tight_layout()
    fig.savefig("mag-distribution.png", dpi=500)
    None

from collections import Counter import matplotlib.pyplot as plt domains, counts = zip(*Counter(y_train).most_common()) # Configure matplotlib to have nice, high-resolution charts %matplotlib inline plt.rcParams["figure.facecolor"] = "white" plt.rcParams["font.size"] = 18 plt.rcParams["figure.figsize"] = (8, 5) fig, ax = plt.subplots() plt.xticks(rotation=90) ax.bar(domains, counts) ax.set_ylabel("Count") fig.tight_layout() fig.savefig("mag-distribution.png", dpi=500) None
In [3]:
Copied!

    from sklearn.naive_bayes import MultinomialNB
    from sklearn.pipeline import Pipeline
    from sklearn.feature_extraction.text import TfidfVectorizer

    def create_pipeline() -> Pipeline:
        return Pipeline(
            steps=[
                ("vectorizer", TfidfVectorizer(sublinear_tf=True)),
                ("classifier", MultinomialNB()),
            ]
        )

from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer def create_pipeline() -> Pipeline: return Pipeline( steps=[ ("vectorizer", TfidfVectorizer(sublinear_tf=True)), ("classifier", MultinomialNB()), ] )
In [4]:
Copied!

    from sklearn.model_selection import GridSearchCV
    import pandas as pd

    optimisation_pipeline = GridSearchCV(
        create_pipeline(),
        {
            "vectorizer__min_df": [5, 20, 100],
            "vectorizer__max_df": [0.05, 0.1],
            "classifier__alpha": [0.5, 1],
            "classifier__fit_prior": [True, False],
        },
        scoring="f1_macro",
        cv=3,
        n_jobs=-1,
        verbose=1,
    )
    optimisation_pipeline.fit(X_train, y_train)

    results = pd.DataFrame(optimisation_pipeline.cv_results_)
    results.sort_values("rank_test_score")

from sklearn.model_selection import GridSearchCV import pandas as pd optimisation_pipeline = GridSearchCV( create_pipeline(), { "vectorizer__min_df": [5, 20, 100], "vectorizer__max_df": [0.05, 0.1], "classifier__alpha": [0.5, 1], "classifier__fit_prior": [True, False], }, scoring="f1_macro", cv=3, n_jobs=-1, verbose=1, ) optimisation_pipeline.fit(X_train, y_train) results = pd.DataFrame(optimisation_pipeline.cv_results_) results.sort_values("rank_test_score")

    Fitting 3 folds for each of 24 candidates, totalling 72 fits

Out[4]:

| mean_fit_time | std_fit_time | mean_score_time | std_score_time | param_classifier__alpha | param_classifier__fit_prior | param_vectorizer__max_df | param_vectorizer__min_df | params | split0_test_score | split1_test_score | split2_test_score | mean_test_score | std_test_score | rank_test_score
--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---
12 | 2.352721 | 0.257936 | 1.357399 | 0.094580 | 1 | True | 0.05 | 5 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.677283 | 0.670398 | 0.665671 | 0.671118 | 0.004768 | 1
15 | 2.544958 | 0.051976 | 1.245658 | 0.137108 | 1 | True | 0.1 | 5 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.676970 | 0.670244 | 0.666123 | 0.671112 | 0.004470 | 2
18 | 2.472888 | 0.053978 | 1.447181 | 0.051170 | 1 | False | 0.05 | 5 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.675678 | 0.669321 | 0.665305 | 0.670101 | 0.004271 | 3
21 | 2.467637 | 0.005358 | 1.216254 | 0.048319 | 1 | False | 0.1 | 5 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.675569 | 0.669482 | 0.665225 | 0.670092 | 0.004245 | 4
3 | 2.477612 | 0.134880 | 1.428521 | 0.017417 | 0.5 | True | 0.1 | 5 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.675225 | 0.668912 | 0.665652 | 0.669930 | 0.003974 | 5
0 | 2.484810 | 0.067836 | 1.249979 | 0.209959 | 0.5 | True | 0.05 | 5 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.675264 | 0.668781 | 0.665394 | 0.669813 | 0.004095 | 6
9 | 2.452453 | 0.049376 | 1.279694 | 0.089200 | 0.5 | False | 0.1 | 5 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.674199 | 0.668005 | 0.664456 | 0.668887 | 0.004026 | 7
6 | 2.748628 | 0.098077 | 1.255213 | 0.101334 | 0.5 | False | 0.05 | 5 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.673996 | 0.668048 | 0.664572 | 0.668872 | 0.003891 | 8
13 | 2.371907 | 0.204820 | 1.375143 | 0.193984 | 1 | True | 0.05 | 20 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.656459 | 0.647433 | 0.644864 | 0.649585 | 0.004972 | 9
16 | 2.557486 | 0.184332 | 1.272137 | 0.133980 | 1 | True | 0.1 | 20 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.656196 | 0.646960 | 0.645436 | 0.649530 | 0.004754 | 10
4 | 2.362093 | 0.109796 | 1.344960 | 0.083562 | 0.5 | True | 0.1 | 20 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.654424 | 0.644690 | 0.644991 | 0.648035 | 0.004519 | 11
1 | 2.668012 | 0.131751 | 1.383441 | 0.049157 | 0.5 | True | 0.05 | 20 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.654622 | 0.644901 | 0.644425 | 0.647983 | 0.004699 | 12
19 | 2.517576 | 0.154192 | 1.374269 | 0.026773 | 1 | False | 0.05 | 20 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.655125 | 0.645586 | 0.643166 | 0.647959 | 0.005163 | 13
22 | 2.386240 | 0.069718 | 0.967638 | 0.076766 | 1 | False | 0.1 | 20 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.654254 | 0.645409 | 0.643514 | 0.647726 | 0.004680 | 14
7 | 2.416211 | 0.138001 | 1.316785 | 0.036402 | 0.5 | False | 0.05 | 20 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.652727 | 0.643691 | 0.642749 | 0.646389 | 0.004498 | 15
10 | 2.397768 | 0.244951 | 1.330007 | 0.008983 | 0.5 | False | 0.1 | 20 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.652290 | 0.642975 | 0.643421 | 0.646229 | 0.004290 | 16
14 | 2.590127 | 0.054396 | 1.155976 | 0.187602 | 1 | True | 0.05 | 100 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.587097 | 0.577411 | 0.580170 | 0.581560 | 0.004075 | 17
17 | 2.497556 | 0.085952 | 1.169808 | 0.061336 | 1 | True | 0.1 | 100 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.585713 | 0.577197 | 0.580763 | 0.581224 | 0.003492 | 18
2 | 2.467611 | 0.168399 | 1.313936 | 0.109695 | 0.5 | True | 0.05 | 100 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.586346 | 0.576987 | 0.579852 | 0.581062 | 0.003915 | 19
5 | 2.339322 | 0.092595 | 1.209515 | 0.132825 | 0.5 | True | 0.1 | 100 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.585634 | 0.576217 | 0.580320 | 0.580723 | 0.003855 | 20
20 | 2.644488 | 0.119967 | 1.238554 | 0.048871 | 1 | False | 0.05 | 100 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.581096 | 0.572833 | 0.576280 | 0.576736 | 0.003389 | 21
8 | 2.456030 | 0.072136 | 1.240463 | 0.092383 | 0.5 | False | 0.05 | 100 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.580841 | 0.572391 | 0.575731 | 0.576321 | 0.003475 | 22
23 | 2.335796 | 0.082338 | 0.786187 | 0.073499 | 1 | False | 0.1 | 100 | {'classifier__alpha': 1, 'classifier__fit_prio... | 0.579769 | 0.572373 | 0.576699 | 0.576280 | 0.003034 | 23
11 | 2.530331 | 0.107199 | 1.247842 | 0.078229 | 0.5 | False | 0.1 | 100 | {'classifier__alpha': 0.5, 'classifier__fit_pr... | 0.579743 | 0.571607 | 0.576352 | 0.575901 | 0.003337 | 24

In [5]:
Copied!

    from sklearn import set_config

    set_config(display="diagram")

    classifier = create_pipeline()
    classifier.set_params(**optimisation_pipeline.best_params_)
    classifier.fit(X_train, y_train)

from sklearn import set_config set_config(display="diagram") classifier = create_pipeline() classifier.set_params(**optimisation_pipeline.best_params_) classifier.fit(X_train, y_train)
Out[5]:

    Pipeline(steps=[('vectorizer',
                     TfidfVectorizer(max_df=0.05, min_df=5, sublinear_tf=True)),
                    ('classifier', MultinomialNB(alpha=1))])

In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Pipeline

    Pipeline(steps=[('vectorizer',
                     TfidfVectorizer(max_df=0.05, min_df=5, sublinear_tf=True)),
                    ('classifier', MultinomialNB(alpha=1))])

TfidfVectorizer

    TfidfVectorizer(max_df=0.05, min_df=5, sublinear_tf=True)

MultinomialNB

    MultinomialNB(alpha=1)

In [12]:
Copied!

    from sklearn import metrics
    import matplotlib.pyplot as plt

    y_predicted = classifier.predict(X_test)

    %matplotlib inline
    plt.rcParams["figure.figsize"] = (20, 18)
    plt.rcParams["figure.facecolor"] = "white"
    plt.rcParams["font.size"] = 22
    plt.rcParams["axes.xmargin"] = 0

    print(metrics.classification_report(y_test, y_predicted, digits=4))
    metrics.ConfusionMatrixDisplay.from_predictions(
        y_true=y_test,
        y_pred=y_predicted,
        xticks_rotation="vertical",
        normalize="pred",
        values_format=".2f",
    )
    plt.tight_layout()
    plt.savefig("mag-confusion.png", dpi=600)

from sklearn import metrics import matplotlib.pyplot as plt y_predicted = classifier.predict(X_test) %matplotlib inline plt.rcParams["figure.figsize"] = (20, 18) plt.rcParams["figure.facecolor"] = "white" plt.rcParams["font.size"] = 22 plt.rcParams["axes.xmargin"] = 0 print(metrics.classification_report(y_test, y_predicted, digits=4)) metrics.ConfusionMatrixDisplay.from_predictions( y_true=y_test, y_pred=y_predicted, xticks_rotation="vertical", normalize="pred", values_format=".2f", ) plt.tight_layout() plt.savefig("mag-confusion.png", dpi=600)

                  precision    recall  f1-score   support

        business     0.6412    0.7258    0.6808      3198
       economics     0.6635    0.7146    0.6881      3189
       geography     0.7461    0.6791    0.7111      3207
        medicine     0.8806    0.9021    0.8912      3187
        politics     0.5563    0.5895    0.5724      3169
      psychology     0.7654    0.6811    0.7208      3252
       sociology     0.5165    0.4698    0.4921      3197

        accuracy                         0.6803     22399
       macro avg     0.6814    0.6803    0.6795     22399
    weighted avg     0.6817    0.6803    0.6796     22399

Last update: July 16, 2022