Home > Mobile >  How can I replace these two functions with a single function?
How can I replace these two functions with a single function?

Time:02-19

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)

CodePudding user response:

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)

CodePudding user response:

This isn't really composition, as @mkriger1 pointed out, but if all you want is to "unroll" the list comprehension and inline the function, you could do the following:

Keep in mind that the list comprehension y_pred = [something(x) for x in X] is equivalent to the code

y_pred = []
for x in X:
    y_pred.append(something(x))

Therefore, you could do

def predict(self, X):
    y_pred = []  # Initialize y_pred
    for for x in X:  # Iterate over 'X'
        # Here we repeat the content of _predict
        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))
        # Finally we append what _predict was previously returning
        y_pred.append(self.classes[np.argmax(probs))
    return np.array(y_pred)
  • Related