Untitled
unknown
plain_text
9 months ago
2.0 kB
6
Indexable
import numpy as np
from collections import defaultdict
class NaiveBayesClassifier:
def __init__(self):
self.class_priors = {}
self.means = {}
self.variances = {}
def fit(self, X, y):
"""Trenuje klasyfikator na danych."""
self.classes = np.unique(y)
self.class_priors = {c: np.mean(y == c) for c in self.classes}
self.means = {c: np.mean(X[y == c], axis=0) for c in self.classes}
self.variances = {c: np.var(X[y == c], axis=0) for c in self.classes}
def _gaussian_pdf(self, x, mean, var):
"""Funkcja gęstości prawdopodobieństwa dla rozkładu Gaussa."""
eps = 1e-6 # Zapobiega dzieleniu przez zero
coef = 1 / np.sqrt(2 * np.pi * (var + eps))
exponent = np.exp(- (x - mean) ** 2 / (2 * (var + eps)))
return coef * exponent
def predict(self, X):
"""Przewiduje klasy dla podanych danych."""
predictions = []
for x in X:
posteriors = {}
for c in self.classes:
prior = np.log(self.class_priors[c])
likelihood = np.sum(np.log(self._gaussian_pdf(x, self.means[c], self.variances[c])))
posteriors[c] = prior + likelihood
predictions.append(max(posteriors, key=posteriors.get))
return np.array(predictions)
# Wczytanie zbioru Irysów
def load_iris():
from sklearn import datasets
iris = datasets.load_iris()
return iris.data, iris.target
# Podział danych na treningowe i testowe
from sklearn.model_selection import train_test_split
X, y = load_iris()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Inicjalizacja i trenowanie klasyfikatora
classifier = NaiveBayesClassifier()
classifier.fit(X_train, y_train)
# Predykcja i ocena
y_pred = classifier.predict(X_test)
accuracy = np.mean(y_pred == y_test)
print(f'Dokładność klasyfikatora: {accuracy:.2f}')
Editor is loading...
Leave a Comment