[SOLVED] How can I replace these two functions with a single function?

Issue

I have the following two functions:

def predict(self, X):
    y_pred = [self._predict(x) for x in X]
    return np.array(y_pred)

def _predict(self, x):
    probs = []
    for idx, c in enumerate(self.classes):
        prior = self.classesPrior[idx]
        probs_c = np.sum(np.log(self.density_function(x, idx, self.classesMean[idx], self.classesVariance[idx])))
        probs.append(probs_c + np.log(prior))
    return self.classes[np.argmax(probs)]

I am trying to compose this code into a function named predict that has the same behavior as observed when using the above two functions.

This is what I tried to do:

def predict(self, X):
    probs = []
    # calculate posterior probability for each class
    for idx, c in enumerate(self.classes):
        prior = self.classesPrior[idx]
        for x in X:
            probs_c = np.sum(np.log(self.density_function(x, idx, self.classesMean[idx], self.classesVariance[idx])))
            probs.append(np.argmax(probs_c + np.log(prior)))

    y_pred = self.classes[probs]
    # return class with highest posterior probability
    return np.array(y_pred)

Solution

You can remove the list comprehension and use a for loop instead, placing the function definition of _predict() inside the for loop with minor modifications:

def predict(self, X):
    y_pred = []
    
    for x in X:
        probs = []
        for idx, c in enumerate(self.classes):
            prior = self.classesPrior[idx]
            probs_c = np.sum(np.log(self.density_function(x, idx, self.classesMean[idx], self.classesVariance[idx])))
            probs.append(probs_c + np.log(prior))
        y_pred.append(self.classes[np.argmax(probs)])
        
    return np.array(y_pred)

Answered By – BrokenBenchmark

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.