Menu
CoddyTech

predict-Methode

Lektion 14 von 19 im Kurs Einführung in maschinelles Lernen von Coddy.

challenge icon

Aufgabe

Einfach

Die Methode predict weist einem neuen Datenpunkt eine Klasse zu (oder sagt diese voraus), indem sie die folgende Formel verwendet:
 

temperaturemoodmotivationwindy
lowhappyhighyes
p_yes = probability_features["temperature"]["low"]["yes"] *
	probability_features["mood"]["happy"]["yes"] *
	probability_features["motivation"]["high"]["yes"] *
	probability_features["windy"]["yes"]["yes"] *
	probability_target["yes"]

In der vorherigen Lektion haben wir get_classes_probability geschrieben.

In der Methode predict müssen wir nun die Ausgabe von get_classes_probability für den neuen Datenpunkt zurückgeben.

Probier es selbst

class NaiveBayes:
    def __init__(self):
        pass
    
    def get_classes_probability(self, X):
        # X holds a dataframe with a single row
        # use self.classes that was saved in fit method
        # write your code below
        classes_probabilities = {}
        for cls in self.classes:
            classes_probabilities[cls] = 1
            for column in X.columns:
                for distinct_value in X[column].unique():
                    classes_probabilities[cls] *= self.probability_features[column][distinct_value][cls]
            classes_probabilities[cls] *= self.probability_target[cls]
        # --------------------------
        return classes_probabilities
    
    def fit(self, X_train, y_train):
        self.probability_features = {}
        self.probability_target = {}
        self.classes = y_train.unique()
        target_variable = "target"
        df = X_train.copy()
        df[target_variable] = y_train
        # Copy your code from previous lesson
        # Don't forget to Add self. to probability_features and probability_target
        distinct_target_values = df[target_variable].unique()
        for column in df.columns:
            if column == target_variable:
                continue
            self.probability_features[column] = {}
            distinct_values = df[column].unique()
            for value in distinct_values:
                self.probability_features[column][value] = {}
                for target_value in distinct_target_values: 
                    total = len(df[(df[column] == value) & (df[target_variable] == target_value)][target_variable])
                    count = len(df[(df[column] == value)])
                    self.probability_features[column][value][target_value] = total / count

        for target_value in distinct_target_values: 
            total = len(df[(df[target_variable] == target_value)][target_variable])
            self.probability_target[target_value] = total / len(df[target_variable])

        
    
    def predict(self, X_test):
        pass

Alle Lektionen in Einführung in maschinelles Lernen

Übe selbstständig: Online-Python-Compiler