0

I've got the following problem: I have a list (which is a single row of a matrix) with 4 values (features). Let's say:

x_temp = [3.4, 2.1, 3.3, 6.6]

at the same time I have an other array theta with 4 objects in it:

theta = [obj1, obj2, obj3, obj4]

So x_temp has the same length as theta.

Each of this objects have a method called get_log_probability(). However these objects are not from the same class. so obj1 is from class A, obj2 from class B, obj3 from class C and obj4 from class D.

How can I call efficiently the get_log_probability() for each element in x_temp with the according object in theta?

Final outcome should be:

call obj1.get_log_probability(x_temp[1])
call obj2.get_log_probability(x_temp[2]) 
call obj3.get_log_probability(x_temp[3])
call obj4.get_log_probability(x_temp[4])

and then append to these probabilities to a new array.

the toy example with just 3 for loops looks as follows:

def predict(self, X):
    
    y_hat = []
    for z, new_x in enumerate(X):
        # store the probability for each class 
        prob_classes = []
        
        # 1st calculate log_prob of each class for new_x
        for i, c in enumerate(self._classes):
            prob_c = np.log(self._pi[i])
            # 2nd calculate the log_prob of each feature
            for j, theta in enumerate(self._theta[i]):
                new_x_j = new_x[j]
                prob_c += theta.get_log_probability([new_x_j])[0]
                
            prob_classes.append(prob_c)                
        
        # select the highest posterior probability
        max_y_hat = np.argmax(prob_classes)
        
        y_hat.append(self._classes[max_y_hat])
    
    return y_hat

self._theta is a 3x4 matrix with 3 classes and 4 features. each cell of this matrix contains an object with different methods. And I would like to call the same method (get_log_probability) for each object with its according value which is stored in new_x_j. new_x_j is an array with 4 values.

In my example the matrix is not that big, its more about how to elegantly apply the methods and to avoid looping over single values of a matrix!

  • What is your criteria for "efficiency"? Performance, memory, overhead, ...? – MisterMiyagi Nov 23 '21 at 10:26
  • Performance! Sorry for not being specific. The goal is basically to NOT iterate over every single value of a matrix but only to iterate over its rows and map to this row the according methods of the objects. – Loco_Vegano Nov 23 '21 at 12:54
  • How big is the matrix, and how long does each call take? – MisterMiyagi Nov 23 '21 at 12:57
  • I adjusted the question to illustrate a bit more. Maybe this helps? The matrix in my example is 30x4 matrix which is not incredibly big but its more a question of principle... – Loco_Vegano Nov 23 '21 at 13:23

0 Answers0