C1W1_Got wrong answer for weighted loss

I am getting wrong values of weighted loss in C1M1_Assignment.
Here is my code :

# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)
def get_weighted_loss(pos_weights, neg_weights, epsilon=1e-7):
    """
    Return weighted loss function given negative weights and positive weights.

    Args:
      pos_weights (np.array): array of positive weights for each class, size (num_classes)
      neg_weights (np.array): array of negative weights for each class, size (num_classes)
    
    Returns:
      weighted_loss (function): weighted loss function
    """
    #−(wpylog(f(x))+wn(1−y)log(1−f(x))).
    def weighted_loss(y_true, y_pred):
        """
        Return weighted loss value. 

        Args:
            y_true (Tensor): Tensor of true labels, size is (num_examples, num_classes)
            y_pred (Tensor): Tensor of predicted labels, size is (num_examples, num_classes)
        Returns:
            loss (float): overall scalar loss summed across all classes
        """
        # initialize loss to zero
        loss = 0.0
        
        ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ###

        for i in range(len(pos_weights)):
            # for each class, add average weighted loss for that class 
            loss += -(pos_weights[i]*y_true*K.log(y_pred)+neg_weights[i]*(1-y_true)*K.log(1-y_pred)+epsilon)
        return K.mean(loss)
    
        ### END CODE HERE ###
    return weighted_loss

Can someone help where I am making mistake ?
Thanks.

@Maverick06 Here y_true and y_pred are not 1d arrays, Its shape is (num_examples, num_classes). So inside the for loop, you need to take only its corresponding class. Take all rows and corresponding column.

1 Like

I had posted an issue before. It pertained to indexing, I dove into the TensorFlow guide on multi-axis_indexing, tried again. I seemingly solved the issue. I say “seemingly” because I don’t really understand what was different about this particular try. I removed it because it contained my code