import numpy as np
def average_precision_score(y_true, y_scores):
"""Calculate the average precision score.
- y_true: 1D array-like, true binary labels (0 or 1).
- y_scores: 1D array-like, predicted scores or probabilities for positive class.
"""
# Combine true labels and predicted scores into a sorted list of (true label, score) pairs.
data = list(zip(y_true, y_scores))
data.sort(key=lambda x: x[1], reverse=True)
# Initialize variables for precision, recall, and total positive examples.
precision_values = []
recall_values = []
true_positives = 0
num_positive_examples = sum(y_true)
# Calculate precision and recall at each threshold.
for i, (true_label, score) in enumerate(data, start=1):
if true_label == 1:
true_positives += 1
precision = true_positives / i
recall = true_positives / num_positive_examples
precision_values.append(precision)
recall_values.append(recall)
# Calculate the average precision by integrating the precision-recall curve.
average_precision = np.trapz(precision_values, recall_values)
return average_precision