Naive-Bayes-Klassifikator mit scikit-learn

off the rack classifiers

Im vorigen Kapitel haben wir einen Naive-Bayes-Klassifikator von Grund auf implementiert. Hier verwenden wir GaussianNB aus scikit-learn. Der Gaussian-Naive-Bayes-Klassifikator modelliert die Verteilung jedes numerischen Merkmals innerhalb einer Klasse durch eine Gaußverteilung und kombiniert diese Wahrscheinlichkeiten unter der Naive-Bayes-Unabhängigkeitsannahme.

Im ersten Beispiel verwenden wir den Iris-Datensatz. Wichtig ist, Training und Bewertung zu trennen: Wir trainieren nur auf dem Trainingsanteil und berechnen den Report auf bislang ungesehenen Testdaten.

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.naive_bayes import GaussianNB

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.25, random_state=42, stratify=iris.target
)

model = GaussianNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

print(classification_report(y_test, y_pred, target_names=iris.target_names))
print("Konfusionsmatrix:\n", confusion_matrix(y_test, y_pred))
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        12
  versicolor       0.86      0.92      0.89        13
   virginica       0.92      0.85      0.88        13

    accuracy                           0.92        38
   macro avg       0.92      0.92      0.92        38
weighted avg       0.92      0.92      0.92        38

Konfusionsmatrix:
 [[12  0  0]
 [ 0 12  1]
 [ 0  2 11]]

Wir verwenden nun einmal die Personen-Daten aus dem vorigen Kapitel um einen weiteren Klassifikator zu trainieren:

import numpy as np

def prepare_person_dataset(fname):
    genders = ["male", "female"]
    persons = []
    with open(fname) as fh:
        for line in fh:
            persons.append(line.strip().split())
            
    dataset = [] #Größe, Gewicht und Geschlecht
    
    for person in persons:
        height_weight = (float(person[2]), float(person[3]))
        dataset.append( (height_weight, person[4])) 
    return dataset

learnset = prepare_person_dataset("data/person_data.txt")
testset = prepare_person_dataset("data/person_data_testset.txt")
#print(learnset)
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.naive_bayes import GaussianNB

model = GaussianNB()
X_train_persons, y_train_persons = zip(*learnset)
X_test_persons, y_test_persons = zip(*testset)

X_train_persons = np.asarray(X_train_persons, dtype=float)
X_test_persons = np.asarray(X_test_persons, dtype=float)
y_train_persons = np.asarray(y_train_persons)
y_test_persons = np.asarray(y_test_persons)

model.fit(X_train_persons, y_train_persons)
y_pred_persons = model.predict(X_test_persons)

print(classification_report(y_test_persons, y_pred_persons, zero_division=0))
print("Konfusionsmatrix:\n", confusion_matrix(y_test_persons, y_pred_persons))