153 KiB
153 KiB
In [1]:
import warnings
import json
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_20newsgroups, load_iris
from sklearn.exceptions import ConvergenceWarning
from sklearn.metrics import (
ConfusionMatrixDisplay,
accuracy_score,
classification_report,
f1_score,
)
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import ComplementNB
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
RANDOM_STATE = 42
warnings.filterwarnings("ignore", category=ConvergenceWarning)In [2]:
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=RANDOM_STATE, stratify=y
)
clf = MLPClassifier(hidden_layer_sizes=(10,), activation="relu", max_iter=500,
random_state=RANDOM_STATE)
clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test), zero_division=0)) precision recall f1-score support
0 1.00 1.00 1.00 10
1 1.00 0.90 0.95 10
2 0.91 1.00 0.95 10
accuracy 0.97 30
macro avg 0.97 0.97 0.97 30
weighted avg 0.97 0.97 0.97 30
In [3]:
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=RANDOM_STATE,
stratify=y,
)
iteration_results = []
for max_iter in [100, 500, 2500]:
model = MLPClassifier(
hidden_layer_sizes=(10,),
activation="relu",
max_iter=max_iter,
random_state=RANDOM_STATE,
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
iteration_results.append(
{
"max_iter": max_iter,
"n_iter_": model.n_iter_,
"accuracy": accuracy_score(y_test, y_pred),
"loss": model.loss_,
}
)
pd.DataFrame(iteration_results)Out [3]:
| max_iter | n_iter_ | accuracy | loss | |
|---|---|---|---|---|
| 0 | 100 | 100 | 0.500000 | 0.973367 |
| 1 | 500 | 500 | 0.966667 | 0.417845 |
| 2 | 2500 | 1248 | 1.000000 | 0.095463 |
In [4]:
categories = [
"comp.graphics",
"rec.sport.hockey",
"sci.space",
"talk.politics.misc",
]
news = fetch_20newsgroups(
subset="all",
categories=categories,
remove=("headers", "footers", "quotes"),
random_state=RANDOM_STATE,
)
news_frame = pd.DataFrame(
{
"text": news.data,
"target": news.target,
"target_name": [news.target_names[index] for index in news.target],
}
)
news_frame = news_frame[news_frame["text"].str.strip().ne("")]
news_frame = news_frame.sample(n=1200, random_state=RANDOM_STATE)
news_frame[["target_name"]].value_counts().rename("documents")Out [4]:
target_name rec.sport.hockey 332 sci.space 327 comp.graphics 320 talk.politics.misc 221 Name: documents, dtype: int64
In [5]:
news_frame["target_name"].value_counts().plot(kind="bar", figsize=(8, 4))
plt.title("Распределение документов по категориям")
plt.xlabel("Категория")
plt.ylabel("Количество документов")
plt.xticks(rotation=30, ha="right")
plt.tight_layout()
plt.show()In [6]:
X_train_text, X_test_text, y_train_text, y_test_text = train_test_split(
news_frame["text"],
news_frame["target_name"],
test_size=0.25,
random_state=RANDOM_STATE,
stratify=news_frame["target_name"],
)
text_mlp_pipeline = Pipeline(
steps=[
(
"tfidf",
TfidfVectorizer(
stop_words="english",
max_features=3000,
min_df=2,
),
),
(
"classifier",
MLPClassifier(
hidden_layer_sizes=(30,),
activation="relu",
max_iter=80,
random_state=RANDOM_STATE,
),
),
]
)
text_mlp_pipeline.fit(X_train_text, y_train_text)
news_predictions = text_mlp_pipeline.predict(X_test_text)
print(classification_report(y_test_text, news_predictions)) precision recall f1-score support
comp.graphics 0.85 0.94 0.89 80
rec.sport.hockey 0.93 0.93 0.93 83
sci.space 0.82 0.84 0.83 82
talk.politics.misc 0.89 0.73 0.80 55
accuracy 0.87 300
macro avg 0.87 0.86 0.86 300
weighted avg 0.87 0.87 0.87 300
In [7]:
ConfusionMatrixDisplay.from_predictions(
y_test_text,
news_predictions,
xticks_rotation=30,
cmap="Blues",
)
plt.title("Матрица ошибок: 20 Newsgroups")
plt.tight_layout()
plt.show()In [8]:
sms_frame = pd.read_csv("data/sms_messages.csv").dropna(subset=["label", "text"])
sms_frame["text"] = sms_frame["text"].str.strip()
sms_frame = sms_frame.loc[sms_frame["text"].ne("")].drop_duplicates(subset="text")
sms_frame["label"].value_counts()Out [8]:
label ham 30 spam 30 Name: count, dtype: int64
In [9]:
sms_frame["label"].value_counts().plot(kind="bar", figsize=(6, 4))
plt.title("Распределение SMS по классам")
plt.xlabel("Класс")
plt.ylabel("Количество сообщений")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()In [10]:
X_train_sms, X_test_sms, y_train_sms, y_test_sms = train_test_split(
sms_frame["text"],
sms_frame["label"],
test_size=0.25,
random_state=RANDOM_STATE,
stratify=sms_frame["label"],
)
sms_pipeline = Pipeline(
steps=[
(
"tfidf",
TfidfVectorizer(
stop_words="english",
max_features=2500,
min_df=2,
),
),
(
"classifier",
MLPClassifier(
hidden_layer_sizes=(20,),
activation="relu",
max_iter=80,
random_state=RANDOM_STATE,
),
),
]
)
sms_pipeline.fit(X_train_sms, y_train_sms)
sms_predictions = sms_pipeline.predict(X_test_sms)
print(classification_report(y_test_sms, sms_predictions)) precision recall f1-score support
ham 0.64 0.88 0.74 8
spam 0.75 0.43 0.55 7
accuracy 0.67 15
macro avg 0.69 0.65 0.64 15
weighted avg 0.69 0.67 0.65 15
In [11]:
ConfusionMatrixDisplay.from_predictions(
y_test_sms,
sms_predictions,
cmap="Greens",
)
plt.title("Матрица ошибок: SMS spam/ham")
plt.tight_layout()
plt.show()In [12]:
def compare_models(name, pipeline, features_train, labels_train, features_test,
labels_test, mlp_predictions):
"""Оценить MLP и ComplementNB на одном отложенном наборе."""
vectorizer = TfidfVectorizer(**pipeline.named_steps["tfidf"].get_params())
baseline = Pipeline([("tfidf", vectorizer), ("clf", ComplementNB(alpha=0.1))])
baseline.fit(features_train, labels_train)
predictions = baseline.predict(features_test)
return [
{"dataset": name, "model": model, "train": len(labels_train),
"test": len(labels_test), "accuracy": accuracy_score(labels_test, output),
"macro_f1": f1_score(labels_test, output, average="macro", zero_division=0)}
for model, output in [("MLP", mlp_predictions), ("ComplementNB", predictions)]
]
results = compare_models("20 Newsgroups", text_mlp_pipeline, X_train_text, y_train_text,
X_test_text, y_test_text, news_predictions)
results += compare_models("SMS", sms_pipeline, X_train_sms, y_train_sms,
X_test_sms, y_test_sms, sms_predictions)
results_frame = pd.DataFrame(results)
results_frameOut [12]:
| dataset | model | train | test | accuracy | macro_f1 | |
|---|---|---|---|---|---|---|
| 0 | 20 Newsgroups | MLP | 900 | 300 | 0.870000 | 0.862973 |
| 1 | 20 Newsgroups | ComplementNB | 900 | 300 | 0.893333 | 0.890945 |
| 2 | SMS | MLP | 45 | 15 | 0.666667 | 0.641148 |
| 3 | SMS | ComplementNB | 45 | 15 | 0.733333 | 0.700000 |
In [13]:
# Сохраняем числовые результаты в выводе ячейки для проверки отчёта.
print(json.dumps({
"iris": iteration_results,
"text": results,
"news_mlp": classification_report(y_test_text, news_predictions, output_dict=True,
zero_division=0),
"sms_mlp": classification_report(y_test_sms, sms_predictions, output_dict=True,
zero_division=0),
"sms_counts": sms_frame["label"].value_counts().to_dict(),
}, indent=2)){
"iris": [
{
"max_iter": 100,
"n_iter_": 100,
"accuracy": 0.5,
"loss": 0.9733665764086701
},
{
"max_iter": 500,
"n_iter_": 500,
"accuracy": 0.9666666666666667,
"loss": 0.4178449831431617
},
{
"max_iter": 2500,
"n_iter_": 1248,
"accuracy": 1.0,
"loss": 0.09546343106638029
}
],
"text": [
{
"dataset": "20 Newsgroups",
"model": "MLP",
"train": 900,
"test": 300,
"accuracy": 0.87,
"macro_f1": 0.862973321858864
},
{
"dataset": "20 Newsgroups",
"model": "ComplementNB",
"train": 900,
"test": 300,
"accuracy": 0.8933333333333333,
"macro_f1": 0.8909452813555188
},
{
"dataset": "SMS",
"model": "MLP",
"train": 45,
"test": 15,
"accuracy": 0.6666666666666666,
"macro_f1": 0.6411483253588517
},
{
"dataset": "SMS",
"model": "ComplementNB",
"train": 45,
"test": 15,
"accuracy": 0.7333333333333333,
"macro_f1": 0.7
}
],
"news_mlp": {
"comp.graphics": {
"precision": 0.8522727272727273,
"recall": 0.9375,
"f1-score": 0.8928571428571429,
"support": 80.0
},
"rec.sport.hockey": {
"precision": 0.927710843373494,
"recall": 0.927710843373494,
"f1-score": 0.927710843373494,
"support": 83.0
},
"sci.space": {
"precision": 0.8214285714285714,
"recall": 0.8414634146341463,
"f1-score": 0.8313253012048193,
"support": 82.0
},
"talk.politics.misc": {
"precision": 0.8888888888888888,
"recall": 0.7272727272727273,
"f1-score": 0.8,
"support": 55.0
},
"accuracy": 0.87,
"macro avg": {
"precision": 0.8725752577409204,
"recall": 0.8584867463200918,
"f1-score": 0.862973321858864,
"support": 300.0
},
"weighted avg": {
"precision": 0.8714261664261664,
"recall": 0.87,
"f1-score": 0.8686574870912221,
"support": 300.0
}
},
"sms_mlp": {
"ham": {
"precision": 0.6363636363636364,
"recall": 0.875,
"f1-score": 0.7368421052631579,
"support": 8.0
},
"spam": {
"precision": 0.75,
"recall": 0.42857142857142855,
"f1-score": 0.5454545454545454,
"support": 7.0
},
"accuracy": 0.6666666666666666,
"macro avg": {
"precision": 0.6931818181818181,
"recall": 0.6517857142857143,
"f1-score": 0.6411483253588517,
"support": 15.0
},
"weighted avg": {
"precision": 0.6893939393939393,
"recall": 0.6666666666666666,
"f1-score": 0.6475279106858054,
"support": 15.0
}
},
"sms_counts": {
"ham": 30,
"spam": 30
}
}